From 6b63fe6d61db480566968016600b8efe5bcdbae1 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Mon, 8 Apr 2024 17:57:45 +0530 Subject: [PATCH 01/48] ui: replace dialog to material alert dialog (fix: #1336) possible fix for https://github.com/celzero/rethink-app/issues/1336 --- .../bravedns/adapter/CustomDomainAdapter.kt | 24 ++++++-------- .../bravedns/adapter/CustomIpAdapter.kt | 12 +++---- .../ui/activity/ProxySettingsActivity.kt | 21 ++++++------ .../ui/bottomsheet/ConnTrackerBottomSheet.kt | 21 ++++++++---- .../ui/bottomsheet/DnsBlocklistBottomSheet.kt | 32 +++++++++++-------- .../ui/bottomsheet/OrbotBottomSheet.kt | 19 +++++++---- .../bravedns/ui/fragment/AboutFragment.kt | 21 ++++++------ .../ui/fragment/CustomDomainFragment.kt | 24 ++++++-------- .../bravedns/ui/fragment/CustomIpFragment.kt | 10 ++---- .../ui/fragment/DnsCryptListFragment.kt | 14 ++++---- .../ui/fragment/DnsProxyListFragment.kt | 14 +++----- .../bravedns/ui/fragment/DoTListFragment.kt | 13 ++++---- .../bravedns/ui/fragment/DohListFragment.kt | 20 +++++++----- .../bravedns/ui/fragment/ODoHListFragment.kt | 19 ++++++----- .../bravedns/database/RefreshDatabase.kt | 4 +-- 15 files changed, 132 insertions(+), 136 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/adapter/CustomDomainAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/CustomDomainAdapter.kt index 9e1c9faf0..a295b75dd 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/CustomDomainAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/CustomDomainAdapter.kt @@ -15,7 +15,6 @@ */ package com.celzero.bravedns.adapter -import android.app.Dialog import android.content.Context import android.content.res.ColorStateList import android.graphics.drawable.Drawable @@ -24,7 +23,6 @@ import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup -import android.view.Window import android.view.WindowManager import android.widget.ImageView import android.widget.Toast @@ -237,12 +235,18 @@ class CustomDomainAdapter(val context: Context, val rule: CustomRulesActivity.RU } private fun showEditDomainDialog(customDomain: CustomDomain) { - val dialog = Dialog(context) - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) - dialog.setTitle(context.getString(R.string.cd_dialog_edit_title)) val dBind = DialogAddCustomDomainBinding.inflate((context as CustomRulesActivity).layoutInflater) - dialog.setContentView(dBind.root) + val builder = MaterialAlertDialogBuilder(context).setView(dBind.root) + val lp = WindowManager.LayoutParams() + val dialog = builder.create() + dialog.show() + lp.copyFrom(dialog.window?.attributes) + lp.width = WindowManager.LayoutParams.MATCH_PARENT + lp.height = WindowManager.LayoutParams.WRAP_CONTENT + + dialog.setCancelable(true) + dialog.window?.attributes = lp var selectedType: DomainRulesManager.DomainType = DomainRulesManager.DomainType.getType(customDomain.type) @@ -296,14 +300,6 @@ class CustomDomainAdapter(val context: Context, val rule: CustomRulesActivity.RU } } - val lp = WindowManager.LayoutParams() - lp.copyFrom(dialog.window?.attributes) - lp.width = WindowManager.LayoutParams.MATCH_PARENT - lp.height = WindowManager.LayoutParams.WRAP_CONTENT - dialog.show() - dialog.setCancelable(true) - dialog.window?.attributes = lp - dBind.dacdUrlTitle.text = context.getString(R.string.cd_dialog_title) dBind.dacdDomainEditText.hint = context.getString( diff --git a/app/src/full/java/com/celzero/bravedns/adapter/CustomIpAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/CustomIpAdapter.kt index c4ae92198..f8433d02e 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/CustomIpAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/CustomIpAdapter.kt @@ -15,7 +15,6 @@ */ package com.celzero.bravedns.adapter -import android.app.Dialog import android.content.Context import android.content.res.ColorStateList import android.graphics.drawable.Drawable @@ -24,7 +23,6 @@ import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup -import android.view.Window import android.view.WindowManager import android.widget.ImageView import android.widget.Toast @@ -720,18 +718,16 @@ class CustomIpAdapter(private val context: Context, private val type: CustomRule } private fun showEditIpDialog(customIp: CustomIp) { - val dialog = Dialog(context) - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) - dialog.setTitle(context.getString(R.string.ci_dialog_title)) val dBind = DialogAddCustomIpBinding.inflate((context as CustomRulesActivity).layoutInflater) - dialog.setContentView(dBind.root) - + val builder = MaterialAlertDialogBuilder(context).setView(dBind.root) val lp = WindowManager.LayoutParams() + val dialog = builder.create() + dialog.show() lp.copyFrom(dialog.window?.attributes) lp.width = WindowManager.LayoutParams.MATCH_PARENT lp.height = WindowManager.LayoutParams.WRAP_CONTENT - dialog.show() + dialog.setCancelable(true) dialog.window?.attributes = lp diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/ProxySettingsActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/ProxySettingsActivity.kt index 9b864707b..032d0b073 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/ProxySettingsActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/ProxySettingsActivity.kt @@ -66,11 +66,11 @@ import com.celzero.bravedns.util.Utilities.isAtleastQ import com.celzero.bravedns.util.Utilities.isValidPort import com.celzero.bravedns.util.Utilities.showToastUiCentered import com.google.android.material.dialog.MaterialAlertDialogBuilder +import java.util.concurrent.TimeUnit import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.koin.android.ext.android.inject -import java.util.concurrent.TimeUnit class ProxySettingsActivity : AppCompatActivity(R.layout.fragment_proxy_configure) { private val b by viewBinding(FragmentProxyConfigureBinding::bind) @@ -636,18 +636,16 @@ class ProxySettingsActivity : AppCompatActivity(R.layout.fragment_proxy_configur appNames: List, appName: String ) { - val dialog = Dialog(this) - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) val dialogBinding = DialogSetProxyBinding.inflate(layoutInflater) - dialog.setContentView(dialogBinding.root) - + val builder = MaterialAlertDialogBuilder(this).setView(dialogBinding.root) val lp = WindowManager.LayoutParams() + val dialog = builder.create() + dialog.show() lp.copyFrom(dialog.window?.attributes) lp.width = WindowManager.LayoutParams.MATCH_PARENT lp.height = WindowManager.LayoutParams.WRAP_CONTENT - dialog.show() + dialog.setCancelable(false) - dialog.setCanceledOnTouchOutside(false) dialog.window?.attributes = lp val headerTxt: TextView = dialogBinding.dialogProxyHeader @@ -817,16 +815,15 @@ class ProxySettingsActivity : AppCompatActivity(R.layout.fragment_proxy_configur ) { val defaultHost = "http://127.0.0.1:8118" var host: String - val dialog = Dialog(this) - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) val dialogBinding = DialogSetProxyBinding.inflate(layoutInflater) - dialog.setContentView(dialogBinding.root) - + val builder = MaterialAlertDialogBuilder(this).setView(dialogBinding.root) val lp = WindowManager.LayoutParams() + val dialog = builder.create() + dialog.show() lp.copyFrom(dialog.window?.attributes) lp.width = WindowManager.LayoutParams.MATCH_PARENT lp.height = WindowManager.LayoutParams.WRAP_CONTENT - dialog.show() + dialog.setCancelable(false) dialog.setCanceledOnTouchOutside(false) dialog.window?.attributes = lp diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/ConnTrackerBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/ConnTrackerBottomSheet.kt index 7cf3f4b5a..3a0ec59d2 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/ConnTrackerBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/ConnTrackerBottomSheet.kt @@ -15,7 +15,6 @@ */ package com.celzero.bravedns.ui.bottomsheet -import android.app.Dialog import android.content.Intent import android.content.res.ColorStateList import android.content.res.Configuration @@ -29,7 +28,7 @@ import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup -import android.view.Window +import android.view.WindowManager import android.widget.AdapterView import android.widget.Toast import androidx.appcompat.widget.AppCompatImageView @@ -61,15 +60,16 @@ import com.celzero.bravedns.util.Utilities import com.celzero.bravedns.util.Utilities.getIcon import com.celzero.bravedns.util.Utilities.showToastUiCentered import com.google.android.material.bottomsheet.BottomSheetDialogFragment +import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.common.collect.HashMultimap import com.google.common.collect.Multimap import com.google.gson.Gson +import java.util.Locale import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.koin.android.ext.android.inject import org.koin.core.component.KoinComponent -import java.util.Locale class ConnTrackerBottomSheet : BottomSheetDialogFragment(), KoinComponent { @@ -571,10 +571,17 @@ class ConnTrackerBottomSheet : BottomSheetDialogFragment(), KoinComponent { if (blockedRule == null) return val dialogBinding = DialogInfoRulesLayoutBinding.inflate(layoutInflater) - val dialog = Dialog(requireContext()) - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) - dialog.setCanceledOnTouchOutside(true) - dialog.setContentView(dialogBinding.root) + val builder = MaterialAlertDialogBuilder(requireContext()).setView(dialogBinding.root) + val lp = WindowManager.LayoutParams() + val dialog = builder.create() + dialog.show() + lp.copyFrom(dialog.window?.attributes) + lp.width = WindowManager.LayoutParams.MATCH_PARENT + lp.height = WindowManager.LayoutParams.WRAP_CONTENT + + dialog.setCancelable(true) + dialog.window?.attributes = lp + val heading = dialogBinding.infoRulesDialogRulesTitle val okBtn = dialogBinding.infoRulesDialogCancelImg val desc = dialogBinding.infoRulesDialogRulesDesc diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/DnsBlocklistBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/DnsBlocklistBottomSheet.kt index 884c290df..a2384fc91 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/DnsBlocklistBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/DnsBlocklistBottomSheet.kt @@ -15,7 +15,6 @@ limitations under the License. */ package com.celzero.bravedns.ui.bottomsheet -import android.app.Dialog import android.content.res.ColorStateList import android.content.res.Configuration import android.graphics.drawable.Drawable @@ -27,7 +26,7 @@ import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup -import android.view.Window +import android.view.WindowManager import android.widget.AdapterView import android.widget.ImageView import androidx.appcompat.widget.AppCompatImageView @@ -58,13 +57,14 @@ import com.celzero.bravedns.util.UIUtils.updateHtmlEncodedText import com.celzero.bravedns.util.Utilities import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.google.android.material.chip.Chip +import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.common.collect.HashMultimap import com.google.common.collect.Multimap import com.google.gson.Gson +import java.util.Locale import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.koin.android.ext.android.inject -import java.util.Locale class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { private var _binding: BottomSheetDnsLogBinding? = null @@ -349,10 +349,10 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { private fun showBlocklistDialog(groupNames: Multimap) { val dialogBinding = DialogInfoRulesLayoutBinding.inflate(layoutInflater) - val dialog = Dialog(requireContext()) - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) - dialog.setCanceledOnTouchOutside(true) - dialog.setContentView(dialogBinding.root) + val builder = MaterialAlertDialogBuilder(requireContext()).setView(dialogBinding.root) + val dialog = builder.create() + dialog.show() + dialog.setCancelable(true) dialogBinding.infoRulesDialogRulesDesc.text = formatText(groupNames) dialogBinding.infoRulesDialogRulesTitle.visibility = View.GONE @@ -367,13 +367,17 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { } val dialogBinding = DialogIpDetailsLayoutBinding.inflate(layoutInflater) - val dialog = Dialog(requireContext()) - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) - dialog.setCanceledOnTouchOutside(true) - dialog.setContentView(dialogBinding.root) - val width = (resources.displayMetrics.widthPixels * 0.75).toInt() - val height = (resources.displayMetrics.heightPixels * 0.5).toInt() - dialog.window?.setLayout(width, height) + + val builder = MaterialAlertDialogBuilder(requireContext()).setView(dialogBinding.root) + val lp = WindowManager.LayoutParams() + val dialog = builder.create() + dialog.show() + lp.copyFrom(dialog.window?.attributes) + lp.width = (resources.displayMetrics.widthPixels * 0.75).toInt() + lp.height = (resources.displayMetrics.heightPixels * 0.5).toInt() + + dialog.setCancelable(true) + dialog.window?.attributes = lp if (b.dnsBlockFavIcon.isVisible) dialogBinding.ipDetailsFavIcon.setImageDrawable(b.dnsBlockFavIcon.drawable) diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/OrbotBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/OrbotBottomSheet.kt index 82ea2b529..a9e767475 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/OrbotBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/OrbotBottomSheet.kt @@ -15,7 +15,6 @@ */ package com.celzero.bravedns.ui.bottomsheet -import android.app.Dialog import android.content.DialogInterface import android.content.Intent import android.content.res.Configuration @@ -25,7 +24,7 @@ import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup -import android.view.Window +import android.view.WindowManager import android.view.animation.AccelerateInterpolator import android.view.animation.Animation import android.widget.Toast @@ -558,10 +557,18 @@ class OrbotBottomSheet : BottomSheetDialogFragment() { private fun showDialogForInfo() { val dialogBinding = DialogInfoRulesLayoutBinding.inflate(layoutInflater) - val dialog = Dialog(requireContext()) - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) - dialog.setCanceledOnTouchOutside(true) - dialog.setContentView(dialogBinding.root) + + val builder = MaterialAlertDialogBuilder(requireContext()).setView(dialogBinding.root) + val lp = WindowManager.LayoutParams() + val dialog = builder.create() + dialog.show() + lp.copyFrom(dialog.window?.attributes) + lp.width = WindowManager.LayoutParams.MATCH_PARENT + lp.height = WindowManager.LayoutParams.WRAP_CONTENT + + dialog.setCancelable(true) + dialog.window?.attributes = lp + val okBtn = dialogBinding.infoRulesDialogCancelImg val descText = dialogBinding.infoRulesDialogRulesDesc val titleText = dialogBinding.infoRulesDialogRulesTitle diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/AboutFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/AboutFragment.kt index 4eff06d15..8d8071e5f 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/AboutFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/AboutFragment.kt @@ -15,7 +15,6 @@ limitations under the License. */ package com.celzero.bravedns.ui.fragment -import android.app.Dialog import android.content.ActivityNotFoundException import android.content.DialogInterface import android.content.Intent @@ -30,7 +29,6 @@ import android.text.method.LinkMovementMethod import android.util.Log import android.view.LayoutInflater import android.view.View -import android.view.Window import android.view.WindowManager import android.widget.Toast import androidx.appcompat.app.AlertDialog @@ -65,17 +63,17 @@ import com.celzero.bravedns.util.Utilities.isFdroidFlavour import com.celzero.bravedns.util.Utilities.isPlayStoreFlavour import com.celzero.bravedns.util.Utilities.showToastUiCentered import com.google.android.material.dialog.MaterialAlertDialogBuilder -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -import org.koin.android.ext.android.inject -import org.koin.core.component.KoinComponent import java.io.File import java.io.FileInputStream import java.util.concurrent.TimeUnit import java.util.zip.ZipEntry import java.util.zip.ZipFile import java.util.zip.ZipInputStream +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.koin.android.ext.android.inject +import org.koin.core.component.KoinComponent class AboutFragment : Fragment(R.layout.fragment_about), View.OnClickListener, KoinComponent { private val b by viewBinding(FragmentAboutBinding::bind) @@ -347,14 +345,15 @@ class AboutFragment : Fragment(R.layout.fragment_about), View.OnClickListener, K private fun showContributors() { val dialogBinding = DialogInfoRulesLayoutBinding.inflate(layoutInflater) - val dialog = Dialog(requireContext()) - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) - dialog.setCanceledOnTouchOutside(true) - dialog.setContentView(dialogBinding.root) + val builder = MaterialAlertDialogBuilder(requireContext()).setView(dialogBinding.root) val lp = WindowManager.LayoutParams() + val dialog = builder.create() + dialog.show() lp.copyFrom(dialog.window?.attributes) lp.width = WindowManager.LayoutParams.MATCH_PARENT lp.height = WindowManager.LayoutParams.WRAP_CONTENT + + dialog.setCancelable(true) dialog.window?.attributes = lp val heading = dialogBinding.infoRulesDialogRulesTitle diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/CustomDomainFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/CustomDomainFragment.kt index 1c388a0ea..a975336d5 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/CustomDomainFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/CustomDomainFragment.kt @@ -15,10 +15,8 @@ */ package com.celzero.bravedns.ui.fragment -import android.app.Dialog import android.os.Bundle import android.view.View -import android.view.Window import android.view.WindowManager import android.widget.Toast import androidx.appcompat.widget.SearchView @@ -174,11 +172,17 @@ class CustomDomainFragment : * based on it. User can either select the entered domain to be added in whitelist or blocklist. */ private fun showAddDomainDialog() { - val dialog = Dialog(requireContext()) - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) - dialog.setTitle(getString(R.string.cd_dialog_title)) val dBind = DialogAddCustomDomainBinding.inflate(layoutInflater) - dialog.setContentView(dBind.root) + val builder = MaterialAlertDialogBuilder(requireContext()).setView(dBind.root) + val lp = WindowManager.LayoutParams() + val dialog = builder.create() + dialog.show() + lp.copyFrom(dialog.window?.attributes) + lp.width = WindowManager.LayoutParams.MATCH_PARENT + lp.height = WindowManager.LayoutParams.WRAP_CONTENT + + dialog.setCancelable(true) + dialog.window?.attributes = lp var selectedType: DomainRulesManager.DomainType = DomainRulesManager.DomainType.DOMAIN @@ -219,14 +223,6 @@ class CustomDomainFragment : ) } } - dialog.show() - val lp = WindowManager.LayoutParams() - lp.copyFrom(dialog.window?.attributes) - lp.width = WindowManager.LayoutParams.MATCH_PARENT - lp.height = WindowManager.LayoutParams.WRAP_CONTENT - - dialog.setCancelable(true) - dialog.window?.attributes = lp dBind.dacdUrlTitle.text = getString(R.string.cd_dialog_title) dBind.dacdDomainEditText.hint = diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/CustomIpFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/CustomIpFragment.kt index f3ac2537c..86ec22934 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/CustomIpFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/CustomIpFragment.kt @@ -15,10 +15,8 @@ */ package com.celzero.bravedns.ui.fragment -import android.app.Dialog import android.os.Bundle import android.view.View -import android.view.Window import android.view.WindowManager import android.widget.Toast import androidx.appcompat.widget.SearchView @@ -177,13 +175,11 @@ class CustomIpFragment : Fragment(R.layout.fragment_custom_ip), SearchView.OnQue * input, if valid then will add it to the custom ip database table. */ private fun showAddIpDialog() { - val dialog = Dialog(requireContext()) - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) - dialog.setTitle(getString(R.string.ci_dialog_title)) val dBind = DialogAddCustomIpBinding.inflate(layoutInflater) - dialog.setContentView(dBind.root) - dialog.show() + val builder = MaterialAlertDialogBuilder(requireContext()).setView(dBind.root) val lp = WindowManager.LayoutParams() + val dialog = builder.create() + dialog.show() lp.copyFrom(dialog.window?.attributes) lp.width = WindowManager.LayoutParams.MATCH_PARENT lp.height = WindowManager.LayoutParams.WRAP_CONTENT diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsCryptListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsCryptListFragment.kt index a7f566948..bd0ed6741 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsCryptListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsCryptListFragment.kt @@ -15,11 +15,9 @@ */ package com.celzero.bravedns.ui.fragment -import android.app.Dialog import android.content.res.Configuration import android.os.Bundle import android.view.View -import android.view.Window import android.view.WindowManager import android.widget.TextView import androidx.fragment.app.Fragment @@ -40,6 +38,7 @@ import com.celzero.bravedns.ui.dialog.DnsCryptRelaysDialog import com.celzero.bravedns.util.Themes import com.celzero.bravedns.viewmodel.DnsCryptEndpointViewModel import com.celzero.bravedns.viewmodel.DnsCryptRelayEndpointViewModel +import com.google.android.material.dialog.MaterialAlertDialogBuilder import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -109,12 +108,13 @@ class DnsCryptListFragment : Fragment(R.layout.fragment_dns_crypt_list) { private fun showAddDnsCryptDialog() { val dialogBinding = DialogSetDnsCryptBinding.inflate(layoutInflater) - val dialog = Dialog(requireContext()) - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) - dialog.setTitle(getString(R.string.cd_dns_crypt_dialog_title)) - dialog.setContentView(dialogBinding.root) - dialog.show() + val builder = + MaterialAlertDialogBuilder(requireContext()) + .setView(dialogBinding.root) + val lp = WindowManager.LayoutParams() + val dialog = builder.create() + dialog.show() lp.copyFrom(dialog.window?.attributes) lp.width = WindowManager.LayoutParams.MATCH_PARENT lp.height = WindowManager.LayoutParams.WRAP_CONTENT diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt index 22e7f41ac..1d4d3f662 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt @@ -15,11 +15,9 @@ */ package com.celzero.bravedns.ui.fragment -import android.app.Dialog import android.os.Bundle import android.util.Log import android.view.View -import android.view.Window import android.view.WindowManager import android.widget.ArrayAdapter import android.widget.TextView @@ -39,6 +37,7 @@ import com.celzero.bravedns.service.FirewallManager import com.celzero.bravedns.util.Logger import com.celzero.bravedns.util.Utilities import com.celzero.bravedns.viewmodel.DnsProxyEndpointViewModel +import com.google.android.material.dialog.MaterialAlertDialogBuilder import inet.ipaddr.IPAddressString import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -90,19 +89,16 @@ class DnsProxyListFragment : Fragment(R.layout.fragment_dns_proxy_list) { private fun showAddDnsProxyDialog(appNames: List) { val dialogBinding = DialogSetDnsProxyBinding.inflate(layoutInflater) - val dialog = Dialog(requireContext()) - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) - dialog.setTitle(getString(R.string.cd_custom_dns_proxy_title)) - dialog.setContentView(dialogBinding.root) - dialog.show() + val builder = + MaterialAlertDialogBuilder(requireContext()).setView(dialogBinding.root) val lp = WindowManager.LayoutParams() + val dialog = builder.create() + dialog.show() lp.copyFrom(dialog.window?.attributes) lp.width = WindowManager.LayoutParams.MATCH_PARENT lp.height = WindowManager.LayoutParams.WRAP_CONTENT dialog.setCancelable(true) - - // TODO: figure out why window maybe null dialog.window?.attributes = lp val applyURLBtn = dialogBinding.dialogDnsProxyApplyBtn diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/DoTListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/DoTListFragment.kt index 2b8e0122c..1db15b5fe 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/DoTListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/DoTListFragment.kt @@ -15,10 +15,8 @@ */ package com.celzero.bravedns.ui.fragment -import android.app.Dialog import android.os.Bundle import android.view.View -import android.view.Window import android.view.WindowManager import android.widget.TextView import androidx.fragment.app.Fragment @@ -33,6 +31,7 @@ import com.celzero.bravedns.database.DoTEndpoint import com.celzero.bravedns.databinding.DialogSetCustomDohBinding import com.celzero.bravedns.databinding.FragmentDotListBinding import com.celzero.bravedns.viewmodel.DoTEndpointViewModel +import com.google.android.material.dialog.MaterialAlertDialogBuilder import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -75,13 +74,12 @@ class DoTListFragment : Fragment(R.layout.fragment_dot_list) { } private fun showAddDialog() { - val dialog = Dialog(requireContext()) - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) - dialog.setTitle(getString(R.string.cd_custom_doh_dialog_title)) val dialogBinding = DialogSetCustomDohBinding.inflate(layoutInflater) - dialog.setContentView(dialogBinding.root) - dialog.show() + val builder = + MaterialAlertDialogBuilder(requireContext()).setView(dialogBinding.root) val lp = WindowManager.LayoutParams() + val dialog = builder.create() + dialog.show() lp.copyFrom(dialog.window?.attributes) lp.width = WindowManager.LayoutParams.MATCH_PARENT lp.height = WindowManager.LayoutParams.WRAP_CONTENT @@ -104,6 +102,7 @@ class DoTListFragment : Fragment(R.layout.fragment_dot_list) { getString(R.string.lbl_add).replaceFirstChar(Char::titlecase), getString(R.string.lbl_dot) ) + // fetch the count from repository and increment by 1 to show the // next doh name in the dialog io { diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/DohListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/DohListFragment.kt index ec24327b3..e6f9a15aa 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/DohListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/DohListFragment.kt @@ -18,7 +18,6 @@ package com.celzero.bravedns.ui.fragment import android.app.Dialog import android.os.Bundle import android.view.View -import android.view.Window import android.view.WindowManager import android.widget.TextView import androidx.fragment.app.Fragment @@ -33,14 +32,15 @@ import com.celzero.bravedns.database.DoHEndpoint import com.celzero.bravedns.databinding.DialogSetCustomDohBinding import com.celzero.bravedns.databinding.FragmentDohListBinding import com.celzero.bravedns.viewmodel.DoHEndpointViewModel +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import java.net.MalformedURLException +import java.net.URL import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.koin.android.ext.android.get import org.koin.android.ext.android.inject import org.koin.androidx.viewmodel.ext.android.viewModel -import java.net.MalformedURLException -import java.net.URL class DohListFragment : Fragment(R.layout.fragment_doh_list) { private val b by viewBinding(FragmentDohListBinding::bind) @@ -83,19 +83,20 @@ class DohListFragment : Fragment(R.layout.fragment_doh_list) { * point */ private fun showAddCustomDohDialog() { - val dialog = Dialog(requireContext()) - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) - dialog.setTitle(getString(R.string.cd_custom_doh_dialog_title)) val dialogBinding = DialogSetCustomDohBinding.inflate(layoutInflater) - dialog.setContentView(dialogBinding.root) - dialog.show() + val builder = + MaterialAlertDialogBuilder(requireContext()).setView(dialogBinding.root) val lp = WindowManager.LayoutParams() + val dialog = builder.create() + dialog.show() lp.copyFrom(dialog.window?.attributes) lp.width = WindowManager.LayoutParams.MATCH_PARENT lp.height = WindowManager.LayoutParams.WRAP_CONTENT + dialog.setCancelable(true) dialog.window?.attributes = lp + val heading = dialogBinding.dialogCustomUrlTop val applyURLBtn = dialogBinding.dialogCustomUrlOkBtn val cancelURLBtn = dialogBinding.dialogCustomUrlCancelBtn val customName = dialogBinding.dialogCustomNameEditText @@ -103,6 +104,9 @@ class DohListFragment : Fragment(R.layout.fragment_doh_list) { val progressBar = dialogBinding.dialogCustomUrlLoading val errorTxt = dialogBinding.dialogCustomUrlFailureText val checkBox = dialogBinding.dialogSecureCheckbox + + heading.text = getString(R.string.cd_doh_dialog_heading) + // fetch the count from repository and increment by 1 to show the // next doh name in the dialog io { diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/ODoHListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/ODoHListFragment.kt index 85a97a8c5..51d2380c7 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/ODoHListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/ODoHListFragment.kt @@ -15,10 +15,8 @@ */ package com.celzero.bravedns.ui.fragment -import android.app.Dialog import android.os.Bundle import android.view.View -import android.view.Window import android.view.WindowManager import android.widget.TextView import androidx.fragment.app.Fragment @@ -33,14 +31,15 @@ import com.celzero.bravedns.database.ODoHEndpoint import com.celzero.bravedns.databinding.DialogSetCustomOdohBinding import com.celzero.bravedns.databinding.FragmentOdohListBinding import com.celzero.bravedns.viewmodel.ODoHEndpointViewModel +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import java.net.MalformedURLException +import java.net.URL import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.koin.android.ext.android.get import org.koin.android.ext.android.inject import org.koin.androidx.viewmodel.ext.android.viewModel -import java.net.MalformedURLException -import java.net.URL class ODoHListFragment : Fragment(R.layout.fragment_odoh_list) { private val b by viewBinding(FragmentOdohListBinding::bind) @@ -77,13 +76,11 @@ class ODoHListFragment : Fragment(R.layout.fragment_odoh_list) { } private fun showAddDialog() { - val dialog = Dialog(requireContext()) - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) - dialog.setTitle(getString(R.string.cd_custom_doh_dialog_title)) val dialogBinding = DialogSetCustomOdohBinding.inflate(layoutInflater) - dialog.setContentView(dialogBinding.root) - dialog.show() + val builder = MaterialAlertDialogBuilder(requireContext()).setView(dialogBinding.root) val lp = WindowManager.LayoutParams() + val dialog = builder.create() + dialog.show() lp.copyFrom(dialog.window?.attributes) lp.width = WindowManager.LayoutParams.MATCH_PARENT lp.height = WindowManager.LayoutParams.WRAP_CONTENT @@ -101,12 +98,14 @@ class ODoHListFragment : Fragment(R.layout.fragment_odoh_list) { val errorTxt = dialogBinding.dialogCustomUrlFailureText val hintInputLayout = dialogBinding.textInputLayout1 - heading.text = + val title = getString( R.string.two_argument_space, getString(R.string.lbl_add).replaceFirstChar(Char::uppercase), getString(R.string.lbl_odoh) ) + heading.text = title + // fetch the count from repository and increment by 1 to show the // next doh name in the dialog io { diff --git a/app/src/main/java/com/celzero/bravedns/database/RefreshDatabase.kt b/app/src/main/java/com/celzero/bravedns/database/RefreshDatabase.kt index fde91fc19..5370132fe 100644 --- a/app/src/main/java/com/celzero/bravedns/database/RefreshDatabase.kt +++ b/app/src/main/java/com/celzero/bravedns/database/RefreshDatabase.kt @@ -56,13 +56,13 @@ import com.celzero.bravedns.util.Utilities.getActivityPendingIntent import com.celzero.bravedns.util.Utilities.isAtleastO import com.celzero.bravedns.util.Utilities.isAtleastT import com.celzero.bravedns.util.Utilities.isNonApp -import java.util.concurrent.TimeUnit -import kotlin.random.Random import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.launch +import java.util.concurrent.TimeUnit +import kotlin.random.Random class RefreshDatabase internal constructor( From a90f81ca117a7877dfb3b6e2eb23871e597eaf9c Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Mon, 8 Apr 2024 17:58:22 +0530 Subject: [PATCH 02/48] ktfmt code --- .../bravedns/RethinkDnsApplicationPlay.kt | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/app/src/play/java/com/celzero/bravedns/RethinkDnsApplicationPlay.kt b/app/src/play/java/com/celzero/bravedns/RethinkDnsApplicationPlay.kt index c8a282870..029d713c1 100644 --- a/app/src/play/java/com/celzero/bravedns/RethinkDnsApplicationPlay.kt +++ b/app/src/play/java/com/celzero/bravedns/RethinkDnsApplicationPlay.kt @@ -16,27 +16,34 @@ package com.celzero.bravedns import android.app.Application -import com.celzero.bravedns.scheduler.WorkScheduler +import android.content.pm.ApplicationInfo import com.celzero.bravedns.scheduler.ScheduleManager +import com.celzero.bravedns.scheduler.WorkScheduler import com.celzero.bravedns.service.AppUpdater +import org.koin.android.ext.android.get import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.startKoin import org.koin.dsl.module -import org.koin.android.ext.android.get class RethinkDnsApplicationPlay : Application() { + override fun onCreate() { super.onCreate() + startKoin { if (BuildConfig.DEBUG) androidLogger() androidContext(this@RethinkDnsApplicationPlay) koin.loadModules(AppModules) - koin.loadModules(listOf(module { - // New Koin override strategy allow to override any definition by default. - // don't need to specify override = true anymore in module. - single { StoreAppUpdater(androidContext()) } - })) + koin.loadModules( + listOf( + module { + // New Koin override strategy allow to override any definition by default. + // don't need to specify override = true anymore in module. + single { StoreAppUpdater(androidContext()) } + } + ) + ) } get().scheduleAppExitInfoCollectionJob() From ea5355fe7e2186f7ee4bd3a78a7c5be9df9dacc4 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Mon, 8 Apr 2024 17:59:54 +0530 Subject: [PATCH 03/48] try-catch block for app updates in home screen --- .../celzero/bravedns/ui/HomeScreenActivity.kt | 42 +++++++++++++------ 1 file changed, 30 insertions(+), 12 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/ui/HomeScreenActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/HomeScreenActivity.kt index 8430009f5..a57914e8b 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/HomeScreenActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/HomeScreenActivity.kt @@ -77,13 +77,13 @@ import com.celzero.bravedns.util.Utilities.showToastUiCentered import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar +import java.util.Calendar +import java.util.concurrent.Executor +import java.util.concurrent.TimeUnit import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.koin.android.ext.android.get import org.koin.android.ext.android.inject -import java.util.Calendar -import java.util.concurrent.Executor -import java.util.concurrent.TimeUnit class HomeScreenActivity : AppCompatActivity(R.layout.activity_home_screen) { private val b by viewBinding(ActivityHomeScreenBinding::bind) @@ -482,18 +482,36 @@ class HomeScreenActivity : AppCompatActivity(R.layout.activity_home_screen) { } if (isGooglePlayServicesAvailable() && isPlayStoreFlavour()) { - appUpdateManager.checkForAppUpdate( - isInteractive, - this, - installStateUpdatedListener - ) // Might be play updater or web updater - } else { - get() - .checkForAppUpdate( + try { + appUpdateManager.checkForAppUpdate( isInteractive, this, installStateUpdatedListener - ) // Always web updater + ) // Might be play updater or web updater + } catch (e: Exception) { + Log.e(LOG_TAG_APP_UPDATE, "err in app update check: ${e.message}", e) + showDownloadDialog( + AppUpdater.InstallSource.STORE, + getString(R.string.download_update_dialog_failure_title), + getString(R.string.download_update_dialog_failure_message) + ) + } + } else { + try { + get() + .checkForAppUpdate( + isInteractive, + this, + installStateUpdatedListener + ) // Always web updater + } catch (e: Exception) { + Log.e(LOG_TAG_APP_UPDATE, "Error in app (web) update check: ${e.message}", e) + showDownloadDialog( + AppUpdater.InstallSource.OTHER, + getString(R.string.download_update_dialog_failure_title), + getString(R.string.download_update_dialog_failure_message) + ) + } } } From 4c846d523a5cbd415144b885027b832e1af536a1 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Mon, 8 Apr 2024 18:04:39 +0530 Subject: [PATCH 04/48] fix: #1339; startForegroundService with multiple servicetype bump firestack version, new arg in flow to detect dup conns --- app/build.gradle | 4 +- app/src/main/AndroidManifest.xml | 3 +- .../bravedns/service/BraveVPNService.kt | 63 ++++++++++++++++--- 3 files changed, 57 insertions(+), 13 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index c26b5d173..ded32e6f7 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -247,8 +247,8 @@ dependencies { fullImplementation 'com.github.kirich1409:viewbindingpropertydelegate-noreflection:1.5.9' // from: https://jitpack.io/#celzero/firestack - download 'com.github.celzero:firestack:a94a7e78a6@aar' - implementation 'com.github.celzero:firestack:a94a7e78a6@aar' + download 'com.github.celzero:firestack:6ea1f4cbbd@aar' + implementation 'com.github.celzero:firestack:6ea1f4cbbd@aar' // Work manager implementation('androidx.work:work-runtime-ktx:2.9.0') { diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 50924b6e3..3e1dc22e5 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -7,6 +7,7 @@ + diff --git a/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt b/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt index b560b7dd2..48e13582c 100644 --- a/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt +++ b/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt @@ -17,6 +17,8 @@ package com.celzero.bravedns.service import android.app.ActivityManager +import android.app.ForegroundServiceStartNotAllowedException +import android.app.ForegroundServiceTypeException import android.app.KeyguardManager import android.app.Notification import android.app.NotificationChannel @@ -28,6 +30,7 @@ import android.content.Intent import android.content.SharedPreferences import android.content.SharedPreferences.OnSharedPreferenceChangeListener import android.content.pm.PackageManager +import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED import android.net.ConnectivityManager import android.net.NetworkCapabilities @@ -42,6 +45,7 @@ import android.util.Log import android.view.accessibility.AccessibilityManager import android.widget.Toast import androidx.annotation.GuardedBy +import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import androidx.core.app.ServiceCompat import androidx.core.content.ContextCompat @@ -1294,19 +1298,25 @@ class BraveVPNService : // Initialize the value whenever the vpn is started. accessibilityHearbeatTimestamp = INIT_TIME_MS - startOrbotAsyncIfNeeded() - // startForeground should always be called within 5 secs of onStartCommand invocation // https://developer.android.com/guide/components/fg-service-types if (isAtleastU()) { - startForeground( - SERVICE_ID, - updateNotificationBuilder(), - FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED - ) + var ok = startForegroundService(FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED) + if (!ok) { + Log.i(LOG_TAG_VPN, "start service failed, retrying with connected device") + ok = startForegroundService(FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE) + } + if (!ok) { + Log.i(LOG_TAG_VPN, "start service failed, stopping service") + signalStopService(userInitiated = false) // notify and stop + return@ui + } } else { startForeground(SERVICE_ID, updateNotificationBuilder()) } + + startOrbotAsyncIfNeeded() + // this should always be set before ConnectionMonitor is init-d // see restartVpn and updateTun which expect this to be the case persistentState.setVpnEnabled(true) @@ -1359,6 +1369,30 @@ class BraveVPNService : return Service.START_STICKY } + @RequiresApi(VERSION_CODES.UPSIDE_DOWN_CAKE) + private fun startForegroundService(serviceType: Int): Boolean { + try { + ServiceCompat.startForeground( + this, + SERVICE_ID, + updateNotificationBuilder(), + serviceType + ) + return true + } catch (e: ForegroundServiceStartNotAllowedException) { + Log.e(LOG_TAG_VPN, "startForeground failed, start not allowed exception", e) + } catch (e: ForegroundServiceTypeException) { + Log.e(LOG_TAG_VPN, "startForeground failed, service type exception", e) + } catch (e: SecurityException) { + Log.e(LOG_TAG_VPN, "startForeground failed, security exception", e) + } catch (e: IllegalArgumentException) { + Log.e(LOG_TAG_VPN, "startForeground failed, illegal argument", e) + } catch (e: Exception) { + Log.e(LOG_TAG_VPN, "startForeground failed", e) + } + return false + } + private fun mtu(): Int { return underlyingNetworks?.minMtu ?: VPN_INTERFACE_MTU } @@ -1678,8 +1712,6 @@ class BraveVPNService : Log.i(LOG_TAG_VPN, "stopped vpn adapter and vpn service") } - - private fun stopVpnAdapter() { io("stopVpn") { if (vpnAdapter == null) { @@ -2897,6 +2929,7 @@ class BraveVPNService : override fun flow( protocol: Int, _uid: Long, + dup: Boolean, src: String, dest: String, realIps: String, @@ -3005,7 +3038,17 @@ class BraveVPNService : val key = CidKey(cm.connId, uid) trackedCids.add(key) - return@runBlocking persistAndConstructFlowResponse(cm, proxy, connId, uid, isRethink) + // TODO: set dup as true for now (v055e), need to handle dup properly in future + val d = dup || true + // if the connection is Rethink's uid and if the dup is false, then the connections + // are rethink's own connections, so add it in network log as well + if (!d) { + // no need to consider return value as the function is called only for logging + persistAndConstructFlowResponse(cm, proxy, connId, uid) + } + // make the cm obj to null so that the db write will not happen + val c = if (d) cm else null + return@runBlocking persistAndConstructFlowResponse(c, proxy, connId, uid, isRethink) } if (trapVpnDns) { From edb68d70c384f778302b69f17a0df1ffd3785a3f Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Mon, 8 Apr 2024 20:00:13 +0530 Subject: [PATCH 05/48] notification builder setOngoing for persistent notification --- .../celzero/bravedns/service/BraveVPNService.kt | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt b/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt index 48e13582c..51b760007 100644 --- a/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt +++ b/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt @@ -1246,22 +1246,27 @@ class BraveVPNService : } } - // Secret notifications are not shown on the lock screen. No need for this app to show - // there. - // Only available in API >= 21 - builder = builder.setVisibility(NotificationCompat.VISIBILITY_SECRET) - val notification = builder.build() // from docs, Starting in Android 13 (API level 33), users can dismiss the notification // associated with a foreground service by default. To do so, users perform a swipe gesture // on the notification. On previous versions of Android, the notification can't be dismissed // unless the foreground service is either stopped or removed from the foreground. // make it ongoing to prevent that. https://github.com/celzero/rethink-app/issues/1136 if (persistentState.persistentNotification) { - notification.flags = Notification.FLAG_ONGOING_EVENT builder.setOngoing(true) } else { builder.setOngoing(false) } + + // Secret notifications are not shown on the lock screen. No need for this app to show + // there. Only available in API >= 21 + builder = builder.setVisibility(NotificationCompat.VISIBILITY_SECRET) + val notification = builder.build() + + if (persistentState.persistentNotification) { + notification.flags = Notification.FLAG_ONGOING_EVENT + } else { + notification.flags = Notification.FLAG_NO_CLEAR + } return notification } From 09e16d28ed523d09fe8942531a10470d15025e01 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Tue, 9 Apr 2024 19:46:34 +0530 Subject: [PATCH 06/48] add clickable and focusable for all the fab buttons, fix: #1336 --- .../com/celzero/bravedns/ui/activity/WgMainActivity.kt | 2 ++ .../celzero/bravedns/ui/fragment/CustomDomainFragment.kt | 2 ++ .../com/celzero/bravedns/ui/fragment/CustomIpFragment.kt | 3 +++ .../celzero/bravedns/ui/fragment/DnsCryptListFragment.kt | 2 ++ .../celzero/bravedns/ui/fragment/DnsProxyListFragment.kt | 6 +++++- .../com/celzero/bravedns/ui/fragment/DohListFragment.kt | 2 ++ .../com/celzero/bravedns/ui/fragment/ODoHListFragment.kt | 2 ++ .../celzero/bravedns/ui/fragment/RethinkListFragment.kt | 2 ++ app/src/full/res/layout/fragment_custom_domain.xml | 3 +++ app/src/full/res/layout/fragment_custom_ip.xml | 3 +++ app/src/full/res/layout/fragment_dns_crypt_list.xml | 3 +++ app/src/full/res/layout/fragment_dns_proxy_list.xml | 4 +++- app/src/full/res/layout/fragment_doh_list.xml | 4 +++- app/src/full/res/layout/fragment_dot_list.xml | 4 +++- app/src/full/res/layout/fragment_odoh_list.xml | 4 +++- app/src/full/res/layout/fragment_rethink_list.xml | 4 +++- app/src/main/res/layout/activity_wg_detail.xml | 2 ++ app/src/main/res/layout/activity_wireguard_main.xml | 8 ++++++++ 18 files changed, 54 insertions(+), 6 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/WgMainActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/WgMainActivity.kt index 95bd0432c..4602f27ed 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/WgMainActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/WgMainActivity.kt @@ -294,6 +294,8 @@ class WgMainActivity : } private fun setupClickListeners() { + // see CustomIpFragment#setupClickListeners#bringToFront() + b.wgAddFab.bringToFront() b.wgAddFab.setOnClickListener { if (b.createFab.visibility == View.VISIBLE) { collapseFab() diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/CustomDomainFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/CustomDomainFragment.kt index a975336d5..5576ed3b0 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/CustomDomainFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/CustomDomainFragment.kt @@ -119,6 +119,8 @@ class CustomDomainFragment : } private fun setupClickListeners() { + // see CustomIpFragment#setupClickListeners#bringToFront() + b.cdaAddFab.bringToFront() b.cdaAddFab.setOnClickListener { showAddDomainDialog() } b.cdaSearchDeleteIcon.setOnClickListener { showDomainRulesDeleteDialog() } diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/CustomIpFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/CustomIpFragment.kt index 86ec22934..d65c3f1f7 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/CustomIpFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/CustomIpFragment.kt @@ -165,6 +165,9 @@ class CustomIpFragment : Fragment(R.layout.fragment_custom_ip), SearchView.OnQue } private fun setupClickListeners() { + // make fab to bring to front of the view as click listener is not working + // on some device + b.cipAddFab.bringToFront() b.cipAddFab.setOnClickListener { showAddIpDialog() } b.cipSearchDeleteIcon.setOnClickListener { showIpRulesDeleteDialog() } diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsCryptListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsCryptListFragment.kt index bd0ed6741..62cffff1b 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsCryptListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsCryptListFragment.kt @@ -90,6 +90,8 @@ class DnsCryptListFragment : Fragment(R.layout.fragment_dns_crypt_list) { private fun initClickListeners() { b.addRelayBtn.setOnClickListener { openDnsCryptRelaysDialog() } + // see CustomIpFragment#setupClickListeners#bringToFront() + b.dohFabAddServerIcon.bringToFront() b.dohFabAddServerIcon.setOnClickListener { showAddDnsCryptDialog() } } diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt index 1d4d3f662..3850d0532 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt @@ -83,7 +83,11 @@ class DnsProxyListFragment : Fragment(R.layout.fragment_dns_proxy_list) { val appNames: MutableList = ArrayList() appNames.add(getString(R.string.settings_app_list_default_app)) appNames.addAll(FirewallManager.getAllAppNames()) - uiCtx { b.dohFabAddServerIcon.setOnClickListener { showAddDnsProxyDialog(appNames) } } + uiCtx { + // see CustomIpFragment#setupClickListeners#bringToFront() + b.dohFabAddServerIcon.bringToFront() + b.dohFabAddServerIcon.setOnClickListener { showAddDnsProxyDialog(appNames) } + } } } diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/DohListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/DohListFragment.kt index e6f9a15aa..0dbe3b958 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/DohListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/DohListFragment.kt @@ -74,6 +74,8 @@ class DohListFragment : Fragment(R.layout.fragment_doh_list) { } private fun initClickListeners() { + // see CustomIpFragment#setupClickListeners#bringToFront() + b.dohFabAddServerIcon.bringToFront() b.dohFabAddServerIcon.setOnClickListener { showAddCustomDohDialog() } } diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/ODoHListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/ODoHListFragment.kt index 51d2380c7..36ae8b2ed 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/ODoHListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/ODoHListFragment.kt @@ -72,6 +72,8 @@ class ODoHListFragment : Fragment(R.layout.fragment_odoh_list) { } private fun initClickListeners() { + // see CustomIpFragment#setupClickListeners#bringToFront() + b.odohFabAdd.bringToFront() b.odohFabAdd.setOnClickListener { showAddDialog() } } diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkListFragment.kt index 79e488fc8..4010e2d4d 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkListFragment.kt @@ -188,6 +188,8 @@ class RethinkListFragment : Fragment(R.layout.fragment_rethink_list) { } private fun initClickListeners() { + // see CustomIpFragment#setupClickListeners#bringToFront() + b.dohFabAddServerIcon.bringToFront() b.dohFabAddServerIcon.setOnClickListener { val intent = Intent(requireContext(), ConfigureRethinkBasicActivity::class.java) intent.putExtra( diff --git a/app/src/full/res/layout/fragment_custom_domain.xml b/app/src/full/res/layout/fragment_custom_domain.xml index a81d85e15..3e5e9f972 100644 --- a/app/src/full/res/layout/fragment_custom_domain.xml +++ b/app/src/full/res/layout/fragment_custom_domain.xml @@ -114,7 +114,10 @@ android:layout_marginTop="30dp" android:layout_marginEnd="30dp" android:layout_marginBottom="30dp" + android:clickable="true" + android:focusable="true" android:padding="10dp" + android:contentDescription="@string/lbl_create" android:src="@drawable/ic_fab_without_border" app:fabSize="mini" app:layout_behavior="com.google.android.material.behavior.HideBottomViewOnScrollBehavior" diff --git a/app/src/full/res/layout/fragment_custom_ip.xml b/app/src/full/res/layout/fragment_custom_ip.xml index 4f261abf5..1354f0848 100644 --- a/app/src/full/res/layout/fragment_custom_ip.xml +++ b/app/src/full/res/layout/fragment_custom_ip.xml @@ -115,9 +115,12 @@ android:layout_alignParentBottom="true" android:layout_marginStart="30dp" android:layout_marginTop="30dp" + android:clickable="true" + android:focusable="true" android:layout_marginEnd="30dp" android:layout_marginBottom="30dp" android:padding="10dp" + android:contentDescription="@string/lbl_create" android:src="@drawable/ic_fab_without_border" app:fabSize="mini" app:layout_behavior="com.google.android.material.behavior.HideBottomViewOnScrollBehavior" diff --git a/app/src/full/res/layout/fragment_dns_crypt_list.xml b/app/src/full/res/layout/fragment_dns_crypt_list.xml index c8484495f..eab37eb04 100644 --- a/app/src/full/res/layout/fragment_dns_crypt_list.xml +++ b/app/src/full/res/layout/fragment_dns_crypt_list.xml @@ -64,6 +64,9 @@ android:layout_gravity="end|bottom" android:layout_margin="30dp" android:padding="10dp" + android:clickable="true" + android:focusable="true" + android:contentDescription="@string/lbl_create" android:src="@drawable/ic_fab_without_border" app:fabSize="normal" app:layout_behavior="com.google.android.material.behavior.HideBottomViewOnScrollBehavior" diff --git a/app/src/full/res/layout/fragment_dns_proxy_list.xml b/app/src/full/res/layout/fragment_dns_proxy_list.xml index 5f3ab5bfc..651ec1fab 100644 --- a/app/src/full/res/layout/fragment_dns_proxy_list.xml +++ b/app/src/full/res/layout/fragment_dns_proxy_list.xml @@ -21,7 +21,9 @@ android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:layout_margin="30dp" - android:contentDescription="New" + android:clickable="true" + android:focusable="true" + android:contentDescription="@string/lbl_create" android:padding="10dp" android:src="@drawable/ic_fab_without_border" app:fabSize="normal" diff --git a/app/src/full/res/layout/fragment_doh_list.xml b/app/src/full/res/layout/fragment_doh_list.xml index bea1d808b..4274f745a 100644 --- a/app/src/full/res/layout/fragment_doh_list.xml +++ b/app/src/full/res/layout/fragment_doh_list.xml @@ -21,8 +21,10 @@ android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:layout_margin="30dp" - android:contentDescription="New" + android:clickable="true" + android:focusable="true" android:padding="10dp" + android:contentDescription="@string/lbl_create" android:src="@drawable/ic_fab_without_border" app:fabSize="normal" app:layout_behavior="com.google.android.material.behavior.HideBottomViewOnScrollBehavior" diff --git a/app/src/full/res/layout/fragment_dot_list.xml b/app/src/full/res/layout/fragment_dot_list.xml index 6fbf0dad7..181e5530d 100644 --- a/app/src/full/res/layout/fragment_dot_list.xml +++ b/app/src/full/res/layout/fragment_dot_list.xml @@ -21,8 +21,10 @@ android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:layout_margin="30dp" - android:contentDescription="New" + android:clickable="true" + android:focusable="true" android:padding="10dp" + android:contentDescription="@string/lbl_create" android:src="@drawable/ic_fab_without_border" app:fabSize="normal" app:layout_behavior="com.google.android.material.behavior.HideBottomViewOnScrollBehavior" diff --git a/app/src/full/res/layout/fragment_odoh_list.xml b/app/src/full/res/layout/fragment_odoh_list.xml index 8f066764f..9a42b7a96 100644 --- a/app/src/full/res/layout/fragment_odoh_list.xml +++ b/app/src/full/res/layout/fragment_odoh_list.xml @@ -21,8 +21,10 @@ android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:layout_margin="30dp" - android:contentDescription="New" android:padding="10dp" + android:clickable="true" + android:focusable="true" + android:contentDescription="@string/lbl_create" android:src="@drawable/ic_fab_without_border" app:fabSize="normal" app:layout_behavior="com.google.android.material.behavior.HideBottomViewOnScrollBehavior" diff --git a/app/src/full/res/layout/fragment_rethink_list.xml b/app/src/full/res/layout/fragment_rethink_list.xml index 371c69aca..27305f61b 100644 --- a/app/src/full/res/layout/fragment_rethink_list.xml +++ b/app/src/full/res/layout/fragment_rethink_list.xml @@ -172,8 +172,10 @@ android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:layout_margin="20dp" - android:contentDescription="New" + android:clickable="true" + android:focusable="true" android:padding="10dp" + android:contentDescription="@string/lbl_create" android:src="@drawable/ic_fab_without_border" android:visibility="gone" app:fabSize="mini" diff --git a/app/src/main/res/layout/activity_wg_detail.xml b/app/src/main/res/layout/activity_wg_detail.xml index 3c172fd3a..0333dd425 100644 --- a/app/src/main/res/layout/activity_wg_detail.xml +++ b/app/src/main/res/layout/activity_wg_detail.xml @@ -441,6 +441,8 @@ app:icon="@drawable/ic_add" app:iconTint="@android:color/transparent" app:iconTintMode="add" + android:clickable="true" + android:focusable="true" app:layout_behavior="com.google.android.material.behavior.HideBottomViewOnScrollBehavior" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" /> diff --git a/app/src/main/res/layout/activity_wireguard_main.xml b/app/src/main/res/layout/activity_wireguard_main.xml index 5f4360aec..7ad1203f1 100644 --- a/app/src/main/res/layout/activity_wireguard_main.xml +++ b/app/src/main/res/layout/activity_wireguard_main.xml @@ -122,6 +122,8 @@ app:backgroundTint="?attr/chipColorBgNormal" app:fabSize="mini" app:icon="@drawable/ic_add" + android:clickable="true" + android:focusable="true" app:iconTint="@android:color/transparent" app:iconTintMode="add" app:layout_behavior="com.google.android.material.behavior.HideBottomViewOnScrollBehavior" @@ -140,6 +142,8 @@ android:textColor="?attr/primaryTextColor" app:backgroundTint="?attr/chipColorBgNormal" app:fabSize="mini" + android:clickable="true" + android:focusable="true" app:icon="@drawable/ic_qr_code_scanner" app:iconTint="@android:color/transparent" app:iconTintMode="add" @@ -158,6 +162,8 @@ android:textColor="?attr/primaryTextColor" app:backgroundTint="?attr/chipColorBgNormal" app:fabSize="mini" + android:clickable="true" + android:focusable="true" app:icon="@drawable/ic_import_conf" app:iconTint="@android:color/transparent" app:iconTintMode="add" @@ -171,6 +177,8 @@ android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:layout_margin="40dp" + android:clickable="true" + android:focusable="true" android:contentDescription="@string/lbl_create" android:padding="10dp" android:src="@drawable/ic_fab_without_border" From 976277f3a0ee55371cf769883101d3ebcc989e10 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Wed, 10 Apr 2024 17:02:05 +0530 Subject: [PATCH 07/48] ui: fix dialog height & width in dns bottom sheet --- .../bravedns/ui/bottomsheet/DnsBlocklistBottomSheet.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/DnsBlocklistBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/DnsBlocklistBottomSheet.kt index a2384fc91..55135282f 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/DnsBlocklistBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/DnsBlocklistBottomSheet.kt @@ -373,8 +373,8 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { val dialog = builder.create() dialog.show() lp.copyFrom(dialog.window?.attributes) - lp.width = (resources.displayMetrics.widthPixels * 0.75).toInt() - lp.height = (resources.displayMetrics.heightPixels * 0.5).toInt() + lp.width = WindowManager.LayoutParams.MATCH_PARENT + lp.height = WindowManager.LayoutParams.WRAP_CONTENT dialog.setCancelable(true) dialog.window?.attributes = lp From fa48cde7e70ec69b0a8b171fa79d4a537b7f6075 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Wed, 10 Apr 2024 19:44:44 +0530 Subject: [PATCH 08/48] tun: take overlay's mtu into account on nw changes --- .../celzero/bravedns/net/go/GoVpnAdapter.kt | 5 +-- .../bravedns/service/BraveVPNService.kt | 34 +++++++++++++++---- .../com/celzero/bravedns/util/Utilities.kt | 2 ++ 3 files changed, 32 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt b/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt index 366cd800d..d83c53ee8 100644 --- a/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt +++ b/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt @@ -1117,14 +1117,15 @@ class GoVpnAdapter : KoinComponent { } } - fun getActiveProxiesIpVersion(): BraveVPNService.OverlayNetworks { + fun getActiveProxiesIpAndMtu(): BraveVPNService.OverlayNetworks { try { val router = tunnel.proxies.router() val has4 = router.iP4() val has6 = router.iP6() val failOpen = !router.iP4() && !router.iP6() + val mtu = router.mtu().toInt() Log.i(LOG_TAG_VPN, "proxy ip version, has4? $has4, has6? $has6, failOpen? $failOpen") - return BraveVPNService.OverlayNetworks(has4, has6, failOpen) + return BraveVPNService.OverlayNetworks(has4, has6, failOpen, mtu) } catch (e: Exception) { Log.w(LOG_TAG_VPN, "err proxy ip version: ${e.message}") } diff --git a/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt b/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt index 51b760007..eff082762 100644 --- a/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt +++ b/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt @@ -152,6 +152,7 @@ class BraveVPNService : private const val IPV6_PREFIX_LENGTH: Int = 120 const val VPN_INTERFACE_MTU: Int = 1500 + const val MIN_MTU: Int = 1280 // TODO: add routes as normal but do not send fd to netstack const val FAIL_OPEN_ON_NO_NETWORK = true @@ -203,7 +204,8 @@ class BraveVPNService : data class OverlayNetworks( val has4: Boolean = false, val has6: Boolean = false, - val failOpen: Boolean = true + val failOpen: Boolean = true, + val mtu: Int = Int.MAX_VALUE ) data class Networks( @@ -1399,7 +1401,16 @@ class BraveVPNService : } private fun mtu(): Int { - return underlyingNetworks?.minMtu ?: VPN_INTERFACE_MTU + val overlayMtu = overlayNetworks.mtu + val underlyingMtu = underlyingNetworks?.minMtu ?: VPN_INTERFACE_MTU + val minMtu = min(overlayMtu, underlyingMtu) + Log.i(LOG_TAG_VPN, "mtu; proxy: $overlayMtu, underlying: $underlyingMtu, min: $minMtu") + // min mtu should be at least MIN_MTU (1280) + if (minMtu < MIN_MTU) { + Log.w(LOG_TAG_VPN, "mtu less than $MIN_MTU, using $MIN_MTU") + return MIN_MTU + } + return minMtu } private fun startOrbotAsyncIfNeeded() { @@ -1999,7 +2010,14 @@ class BraveVPNService : new = old } - val mtuChanged = old.minMtu != new.minMtu + val underlyingMtuChanged = old.minMtu != new.minMtu + val overlayMtuChanged = overlayNetworks.mtu != aux.mtu + Log.d( + LOG_TAG_VPN, + "old: ${old.minMtu}, new: ${new.minMtu}, oldaux: ${overlayNetworks.mtu} newaux: ${aux.mtu}" + ) + // check if mtu has changed for both underlying and overlay networks + val mtuChanged = underlyingMtuChanged || overlayMtuChanged // val auxHas4 = aux.has4 || aux.failOpen // val auxHas6 = aux.has6 || aux.failOpen @@ -2445,8 +2463,10 @@ class BraveVPNService : // overlay network is changed, if so, restart the vpn val interestingNet = interestingNetworkChanges(aux = nw) val isRoutesChanged = interestingNet.routesChanged + val isMtuChanged = interestingNet.mtuChanged + Log.i(LOG_TAG_VPN, "overlay: routes changed? $isRoutesChanged, mtu changed? $isMtuChanged") overlayNetworks = nw - if (isRoutesChanged) { + if (isRoutesChanged || isMtuChanged) { Log.i(LOG_TAG_VPN, "overlay changed $overlayNetworks, restart vpn") // There may be cases where both overlay and underlay networks have the same routes. // In such scenarios, no restart is required. However, here the routeChange is @@ -2460,7 +2480,7 @@ class BraveVPNService : ) } } else { - Log.i(LOG_TAG_VPN, "routes not changed, no restart needed") + Log.i(LOG_TAG_VPN, "overlay routes or mtu not changed, no restart needed") } } @@ -2842,7 +2862,7 @@ class BraveVPNService : } WireguardManager.setActiveConfigTimestamp(id, elapsedRealtime()) // new proxy added, refresh overlay network pair - val nw: OverlayNetworks? = vpnAdapter?.getActiveProxiesIpVersion() + val nw: OverlayNetworks? = vpnAdapter?.getActiveProxiesIpAndMtu() logd("onProxyAdded for proxy $id: $nw") onOverlayNetworkChanged(nw ?: OverlayNetworks()) } @@ -2854,7 +2874,7 @@ class BraveVPNService : } WireguardManager.removeActiveConfigTimestamp(id) // proxy removed, refresh overlay network pair - val nw: OverlayNetworks? = vpnAdapter?.getActiveProxiesIpVersion() + val nw: OverlayNetworks? = vpnAdapter?.getActiveProxiesIpAndMtu() logd("onProxyRemoved for proxy $id: $nw") onOverlayNetworkChanged(nw ?: OverlayNetworks()) } diff --git a/app/src/main/java/com/celzero/bravedns/util/Utilities.kt b/app/src/main/java/com/celzero/bravedns/util/Utilities.kt index a52b68262..cdebf3dae 100644 --- a/app/src/main/java/com/celzero/bravedns/util/Utilities.kt +++ b/app/src/main/java/com/celzero/bravedns/util/Utilities.kt @@ -295,6 +295,8 @@ object Utilities { Log.w(LOG_TAG_VPN, "toast err: ${e.message}") } catch (e: IOException) { Log.w(LOG_TAG_VPN, "toast err: ${e.message}") + } catch (e: Exception) { + Log.w(LOG_TAG_VPN, "toast err: ${e.message}") } } From 4ac686da409eada4c18c2e6d78d1c973b6d5af67 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Fri, 12 Apr 2024 22:08:29 +0530 Subject: [PATCH 09/48] rmv mutex lock from vpn & related changes - rmv mutex from VpnController - deprecate inOn() - handle exception while cancelling the scope --- .../celzero/bravedns/net/go/GoVpnAdapter.kt | 2 +- .../bravedns/service/BraveVPNService.kt | 155 +++++++----------- .../bravedns/service/ConnectionMonitor.kt | 107 +++++------- .../celzero/bravedns/service/VpnController.kt | 21 +-- 4 files changed, 114 insertions(+), 171 deletions(-) diff --git a/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt b/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt index d83c53ee8..d266ac6d6 100644 --- a/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt +++ b/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt @@ -117,7 +117,7 @@ class GoVpnAdapter : KoinComponent { setDnsAlg() } - fun setPcapMode(pcapFilePath: String) { + suspend fun setPcapMode(pcapFilePath: String) { try { Log.i(LOG_TAG_VPN, "set pcap mode: $pcapFilePath") tunnel.setPcap(pcapFilePath) diff --git a/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt b/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt index eff082762..1bfbe9c15 100644 --- a/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt +++ b/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt @@ -38,13 +38,13 @@ import android.net.VpnService import android.os.Build.VERSION import android.os.Build.VERSION_CODES import android.os.ParcelFileDescriptor +import android.os.Process import android.os.SystemClock.elapsedRealtime import android.system.OsConstants.AF_INET import android.system.OsConstants.AF_INET6 import android.util.Log import android.view.accessibility.AccessibilityManager import android.widget.Toast -import androidx.annotation.GuardedBy import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import androidx.core.app.ServiceCompat @@ -101,9 +101,9 @@ import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.MainScope import kotlinx.coroutines.async +import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import org.koin.android.ext.android.inject import rnet.ServerSummary @@ -124,8 +124,9 @@ import kotlin.random.Random class BraveVPNService : VpnService(), ConnectionMonitor.NetworkListener, Bridge, OnSharedPreferenceChangeListener { - @GuardedBy("vpnController") private var connectionMonitor: ConnectionMonitor? = null - @GuardedBy("vpnController") private var vpnAdapter: GoVpnAdapter? = null + private var connectionMonitor: ConnectionMonitor = ConnectionMonitor(this) + private var vpnAdapter: GoVpnAdapter? = null + private var isVpnStarted = false // always accessed on the main thread companion object { const val SERVICE_ID = 1 // Only has to be unique within this app. @@ -155,6 +156,7 @@ class BraveVPNService : const val MIN_MTU: Int = 1280 // TODO: add routes as normal but do not send fd to netstack + // repopulateTrackedNetworks also fails open see isAnyNwValidated const val FAIL_OPEN_ON_NO_NETWORK = true } @@ -254,7 +256,7 @@ class BraveVPNService : // in case of zero, bind only for wg connections, wireguard tries to bind to // network with zero addresses if ( - (destIp.isZero && who.contains(ProxyManager.ID_WG_BASE)) || + (destIp.isZero && who.startsWith(ProxyManager.ID_WG_BASE)) || destIp.isAnyLocal || destIp.isLoopback ) { @@ -320,6 +322,17 @@ class BraveVPNService : val destPort = dest.second.toIntOrNull() val destAddr = destIp.toInetAddress() + // in case of zero, bind only for wg connections, wireguard tries to bind to + // network with zero addresses + if ( + (destIp.isZero && who.startsWith(ProxyManager.ID_WG_BASE)) || + destIp.isAnyLocal || + destIp.isLoopback + ) { + logd("bind6: invalid destIp: $destIp, who: $who, $addrPort") + return + } + pfd = ParcelFileDescriptor.adoptFd(fid.toInt()) // check if the destination port is DNS port, if so bind to the network where the dns // belongs to, else bind to the available network @@ -1295,13 +1308,15 @@ class BraveVPNService : override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { rethinkUid = getRethinkUid() - Log.i(LOG_TAG_VPN, "onStartCommand, us: $rethinkUid, primary? ${isPrimaryUser()}") + val pid = Process.myPid() + Log.i( + LOG_TAG_VPN, + "onStartCommand, us: $rethinkUid / pid: $pid, primary? ${isPrimaryUser()}" + ) VpnController.onConnectionStateChanged(State.NEW) ui { - var isNewVpn = true - // Initialize the value whenever the vpn is started. accessibilityHearbeatTimestamp = INIT_TIME_MS @@ -1328,18 +1343,16 @@ class BraveVPNService : // see restartVpn and updateTun which expect this to be the case persistentState.setVpnEnabled(true) - VpnController.mutex.withLock { - // if service is up (aka connectionMonitor not null) - // then simply update the existing tunnel - if (connectionMonitor == null) { - connectionMonitor = ConnectionMonitor(this, this) - connectionMonitor?.onVpnStartLocked() - } else { - isNewVpn = false - } + var isNewVpn = false + + if (!isVpnStarted) { + Log.i(LOG_TAG_VPN, "new vpn") + isVpnStarted = true + isNewVpn = true + connectionMonitor.onVpnStart(this) } - if (isNewVpn) { + if (isVpnStarted) { underlyingNetworks = null } @@ -1456,14 +1469,6 @@ class BraveVPNService : private suspend fun updateTun(tunnelOptions: AppConfig.TunnelOptions) { Log.i(LOG_TAG_VPN, "update-tun with new pre-set tunnel options") - VpnController.mutex.withLock { - // Connection monitor can be null if onDestroy() of service - // is called, in that case no need to call updateTun() - if (connectionMonitor == null) { - Log.w(LOG_TAG_VPN, "skip update-tun, connection-monitor missing") - return - } - } if (!persistentState.getVpnEnabled()) { // when persistent-state "thinks" vpn is disabled, stop the service, especially when // we could be here via onStartCommand -> updateTun -> handleVpnAdapterChange while @@ -1714,7 +1719,7 @@ class BraveVPNService : } private suspend fun notifyConnectionMonitor() { - VpnController.mutex.withLock { connectionMonitor?.onUserPreferenceChangedLocked() } + connectionMonitor.onUserPreferenceChanged() } private suspend fun updateDnsAlg() { @@ -1761,10 +1766,6 @@ class BraveVPNService : private suspend fun setPcapMode() { val pcapPath = appConfig.getPcapFilePath() - if (pcapPath.isEmpty()) { - Log.i(LOG_TAG_VPN, "pcap mode disabled") - return - } Log.i(LOG_TAG_VPN, "pcap mode enabled, path: $pcapPath") vpnAdapter?.setPcapMode(pcapPath) } @@ -1785,18 +1786,6 @@ class BraveVPNService : } private suspend fun restartVpn(opts: AppConfig.TunnelOptions, networks: Networks, why: String) { - val tunFd: ParcelFileDescriptor? - var proto = InternetProtocol.IPv46.value() - VpnController.mutex.withLock { - // connectionMonitor = null indicates onStartCommand has not yet been called - if (connectionMonitor == null) { - logAndToastIfNeeded( - "$why, cannot restart-vpn, conn monitor null! Was onStartCommand called?", - Log.ERROR - ) - return - } - } if (!persistentState.getVpnEnabled()) { // when persistent-state "thinks" vpn is disabled, stop the service, especially when // we could be here via onStartCommand -> isNewVpn -> restartVpn while both, @@ -1810,15 +1799,14 @@ class BraveVPNService : } // attempt seamless hand-off as described in VpnService.Builder.establish() docs - val es = establishVpn(networks) - tunFd = es.first - proto = es.second + val tunFd = establishVpn(networks) if (tunFd == null) { logAndToastIfNeeded("$why, cannot restart-vpn, no tun-fd", Log.ERROR) io("noTunRestart") { signalStopService(userInitiated = false) } return } - val ok = makeOrUpdateVpnAdapter(tunFd, opts, proto) + + val ok = makeOrUpdateVpnAdapter(tunFd, opts, vpnProtos) // vpnProtos set in establishVpn() if (!ok) { logAndToastIfNeeded("$why, cannot restart-vpn, no vpn-adapter", Log.ERROR) io("noTunnelRestart") { signalStopService(userInitiated = false) } @@ -1853,15 +1841,10 @@ class BraveVPNService : VpnController.updateProtocol(protos) } - // protected by vpncontroller.mutex fun hasTunnel(): Boolean { return vpnAdapter?.hasTunnel() == true } - fun isOn(): Boolean { - return vpnAdapter != null - } - suspend fun refreshResolvers() { Log.i(LOG_TAG_VPN, "refresh resolvers") vpnAdapter?.refreshResolvers() @@ -1870,16 +1853,16 @@ class BraveVPNService : private suspend fun makeOrUpdateVpnAdapter( tunFd: ParcelFileDescriptor, opts: AppConfig.TunnelOptions, - proto: Long + p: Pair ): Boolean { val ok = true val noTun = false // should eventually call signalStopService(userInitiated=false) - + val protos = InternetProtocol.byProtos(p.first, p.second).value() try { if (vpnAdapter != null) { Log.i(LOG_TAG_VPN, "vpn-adapter exists, use it") // in case, if vpn-adapter exists, update the existing vpn-adapter - if (vpnAdapter?.updateLinkAndRoutes(tunFd, opts, proto) == false) { + if (vpnAdapter?.updateLinkAndRoutes(tunFd, opts, protos) == false) { Log.e(LOG_TAG_VPN, "err update vpn-adapter") return noTun } @@ -2089,31 +2072,17 @@ class BraveVPNService : // first network is considered to be active network val ipv4 = currNet?.ipv4Net?.firstOrNull() val ipv6 = currNet?.ipv6Net?.firstOrNull() - val isv4Active = isNetworkSame(ipv4?.network, active) - val isv6Active = isNetworkSame(ipv6?.network, active) val dns4 = ipv4?.linkProperties?.dnsServers val dns6 = ipv6?.linkProperties?.dnsServers - if (isv4Active && isv6Active) { - val dl = mutableListOf() - dns4?.let { dl.addAll(it) } - dns6?.let { dl.addAll(it) } - Log.i(LOG_TAG_VPN, "dns servers for network: $dl") - dl - } else if (isv4Active) { - Log.i(LOG_TAG_VPN, "dns servers for network: $dns4") - dns4 - } else if (isv6Active) { - Log.i(LOG_TAG_VPN, "dns servers for network: $dns6") - dns6 - } else { - // if active network is not found in the list of networks, then use dns from - // first network - val dl = mutableListOf() - dns4?.let { dl.addAll(it) } - dns6?.let { dl.addAll(it) } - Log.i(LOG_TAG_VPN, "dns servers for network: $dl") - dl - } + // if active network is not found in the list of networks, then use dns from + // first network + val dl = mutableListOf() + // add all the dns servers from the first network, depending on the current + // route, netstack will make use of the dns servers + dns4?.let { dl.addAll(it) } + dns6?.let { dl.addAll(it) } + Log.i(LOG_TAG_VPN, "dns servers for network: $dl") + dl } else { Log.i(LOG_TAG_VPN, "dns servers for network: $dnsServers") dnsServers @@ -2150,18 +2119,13 @@ class BraveVPNService : } private fun determineSystemDns(dnsServers: List?): List { - val dnsList: MutableList = mutableListOf() - val list = dnsServers?.map { it.hostAddress ?: "" }?.filter { it != "" } - if (list.isNullOrEmpty()) { // no dns servers found, return empty list return emptyList() - } else { - dnsList.addAll(list) } - if (DEBUG) Log.d(LOG_TAG_VPN, "System dns: $dnsList") - return dnsList + if (DEBUG) Log.d(LOG_TAG_VPN, "System dns: $list") + return list } private fun isDefaultDnsNone(): Boolean { @@ -2235,18 +2199,18 @@ class BraveVPNService : stopPauseTimer() // reset the underlying networks underlyingNetworks = null + isVpnStarted = false // reset the vpn state unobserveOrbotStartStatus() unobserveAppInfos() persistentState.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) - io("vpnDestroy") { - VpnController.mutex.withLock { - connectionMonitor?.onVpnStop() - connectionMonitor = null - } - } + // onVpnStart is also called from the main thread (ui) + connectionMonitor.onVpnStop() VpnController.onVpnDestroyed() + try { + vpnScope.cancel("vpnDestroy") + } catch (ignored: IllegalStateException) {} Log.w(LOG_TAG_VPN, "Destroying VPN service") @@ -2349,7 +2313,7 @@ class BraveVPNService : return Pair(has4, has6) } - private suspend fun establishVpn(networks: Networks): Pair { + private suspend fun establishVpn(networks: Networks): ParcelFileDescriptor? { try { val mtu = mtu() // get mtu from the underlyingnetworks var builder: VpnService.Builder = newBuilder().setSession("Rethink").setMtu(mtu) @@ -2396,12 +2360,10 @@ class BraveVPNService : builder.allowFamily(AF_INET6) } } - val fd = builder.establish() - return Pair(fd, InternetProtocol.byProtos(has4, has6).value()) + return builder.establish() } catch (e: Exception) { Log.e(LOG_TAG_VPN, e.message, e) - // default to Settings.Ns46 - return Pair(null, InternetProtocol.IPv46.value()) + return null } } @@ -3024,7 +2986,6 @@ class BraveVPNService : val trapVpnDns = isDns(dstPort) && isVpnDns(dstIp) val trapVpnPrivateDns = isVpnDns(dstIp) && isPrivateDns(dstPort) - // always block, since the vpn tunnel doesn't serve dns-over-tls if (trapVpnPrivateDns) { logd("flow: dns-over-tls, returning Ipn.Block, $uid") diff --git a/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt b/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt index b58414a9a..97bcad56d 100644 --- a/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt +++ b/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt @@ -53,7 +53,7 @@ import java.util.concurrent.TimeUnit import kotlin.math.max import kotlin.math.min -class ConnectionMonitor(context: Context, networkListener: NetworkListener) : +class ConnectionMonitor(private val networkListener: NetworkListener) : ConnectivityManager.NetworkCallback(), KoinComponent { private val networkSet: MutableSet = mutableSetOf() @@ -70,26 +70,10 @@ class ConnectionMonitor(context: Context, networkListener: NetworkListener) : // api26: .addTransportType(NetworkCapabilities.TRANSPORT_LOWPAN) .build() - /* - // android validated networks builder - NetworkRequest.Builder() - .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) - .addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) - .apply { if (isAtleastS()) setIncludeOtherUidNetworks(true) } - .build() - - */ - - // An Android handler thread internally operates on a looper - // ref: - // alvinalexander.com/java/jwarehouse/android/core/java/android/app/IntentService.java.shtml - private var handlerThread: HandlerThread private var serviceHandler: NetworkRequestHandler? = null private val persistentState by inject() - private var connectivityManager: ConnectivityManager = - context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) - as ConnectivityManager + private lateinit var connectivityManager: ConnectivityManager companion object { // add active network as underlying vpn network @@ -127,18 +111,6 @@ class ConnectionMonitor(context: Context, networkListener: NetworkListener) : val testReachability: Boolean ) - init { - try { - connectivityManager.registerNetworkCallback(networkRequest, this) - } catch (e: Exception) { - Log.w(LOG_TAG_CONNECTION, "Exception while registering network callback", e) - networkListener.onNetworkRegistrationFailed() - } - this.handlerThread = HandlerThread(NetworkRequestHandler::class.simpleName) - this.handlerThread.start() - this.serviceHandler = NetworkRequestHandler(context, handlerThread.looper, networkListener) - } - interface NetworkListener { fun onNetworkDisconnected(networks: UnderlyingNetworks) @@ -147,17 +119,6 @@ class ConnectionMonitor(context: Context, networkListener: NetworkListener) : fun onNetworkRegistrationFailed() } - fun onVpnStop() { - connectivityManager.unregisterNetworkCallback(this) - destroy() - } - - private fun destroy() { - this.serviceHandler?.removeCallbacksAndMessages(null) - this.handlerThread.quitSafely() - this.serviceHandler = null - } - override fun onAvailable(network: Network) { networkSet.add(network) val cap = connectivityManager.getNetworkCapabilities(network) @@ -196,7 +157,7 @@ class ConnectionMonitor(context: Context, networkListener: NetworkListener) : * Handles user preference changes, ie, when the user elects to see either multiple underlying * networks, or just one (the active network). */ - fun onUserPreferenceChangedLocked() { + fun onUserPreferenceChanged() { if (DEBUG) Log.d(LOG_TAG_CONNECTION, "onUserPreferenceChanged") handleNetworkChange(isForceUpdate = true) } @@ -205,11 +166,38 @@ class ConnectionMonitor(context: Context, networkListener: NetworkListener) : * Force updates the VPN's underlying network based on the preference. Will be initiated when * the VPN start is completed. */ - fun onVpnStartLocked() { + fun onVpnStart(context: Context) { + if (this.serviceHandler != null) { + Log.w(LOG_TAG_CONNECTION, "connection monitor is already running") + return + } + Log.i(LOG_TAG_CONNECTION, "new vpn is created force update the network") + connectivityManager = + context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) + as ConnectivityManager + try { + connectivityManager.registerNetworkCallback(networkRequest, this) + } catch (e: Exception) { + Log.w(LOG_TAG_CONNECTION, "Exception while registering network callback", e) + networkListener.onNetworkRegistrationFailed() + return + } + + val handlerThread = HandlerThread(NetworkRequestHandler::class.simpleName) + handlerThread.start() + this.serviceHandler = + NetworkRequestHandler(connectivityManager, handlerThread.looper, networkListener) handleNetworkChange(isForceUpdate = true) } + fun onVpnStop() { + connectivityManager.unregisterNetworkCallback(this) + this.serviceHandler?.removeCallbacksAndMessages(null) + serviceHandler?.looper?.quitSafely() + this.serviceHandler = null + } + private fun handleNetworkChange( isForceUpdate: Boolean = false, delay: Long = TimeUnit.SECONDS.toMillis(1) @@ -265,10 +253,11 @@ class ConnectionMonitor(context: Context, networkListener: NetworkListener) : // Handles the network messages from the callback from the connectivity manager private class NetworkRequestHandler( - ctx: Context, + val connectivityManager: ConnectivityManager, looper: Looper, val listener: NetworkListener ) : Handler(looper) { + // number of times the reachability check is performed due to failures private var reachabilityCount = 0L private val maxReachabilityCount = 10L @@ -302,10 +291,6 @@ class ConnectionMonitor(context: Context, networkListener: NetworkListener) : var trackedIpv4Networks: LinkedHashSet = linkedSetOf() var trackedIpv6Networks: LinkedHashSet = linkedSetOf() - var connectivityManager: ConnectivityManager = - ctx.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) - as ConnectivityManager - override fun handleMessage(msg: Message) { // isForceUpdate - true if onUserPreferenceChanged is changes, the messages should be // processed forcefully regardless of the current and new networks. @@ -336,7 +321,7 @@ class ConnectionMonitor(context: Context, networkListener: NetworkListener) : Log.i( LOG_TAG_CONNECTION, "Connected network: ${newActiveNetwork?.networkHandle} ${networkType(newActiveNetworkCap) - }, new? $isNewNetwork, force? ${opPrefs.isForceUpdate}, auto? ${opPrefs.testReachability}" + }, new? $isNewNetwork, force? ${opPrefs.isForceUpdate}, test? ${opPrefs.testReachability}" ) if (isNewNetwork || opPrefs.isForceUpdate) { @@ -356,7 +341,7 @@ class ConnectionMonitor(context: Context, networkListener: NetworkListener) : Log.i( LOG_TAG_CONNECTION, - "process message MESSAGE_AVAILABLE_NETWORK, ${currentNetworks}, ${newNetworks}; new? $isNewNetwork, force? ${opPrefs.isForceUpdate}, auto? ${opPrefs.testReachability}" + "process message MESSAGE_AVAILABLE_NETWORK, ${currentNetworks}, ${newNetworks}; new? $isNewNetwork, force? ${opPrefs.isForceUpdate}, test? ${opPrefs.testReachability}" ) if (isNewNetwork || opPrefs.isForceUpdate) { @@ -495,6 +480,9 @@ class ConnectionMonitor(context: Context, networkListener: NetworkListener) : trackedIpv4Networks.clear() trackedIpv6Networks.clear() + // BraveVPNService also fails open, see FAIL_OPEN_ON_NO_NETWORK + val isAnyNwValidated = networks.any { isNwValidated(it.network) } + networks.forEach outer@{ prop -> val network: Network = prop.network @@ -525,7 +513,8 @@ class ConnectionMonitor(context: Context, networkListener: NetworkListener) : } // see #createNetworksSet for why we are using hasInternet - if (hasInternet(network) == true) { + // if no network has been validated, then fail open + if (hasInternet(network) == true && (!isAnyNwValidated || isNwValidated(network))) { var hasDefaultRoute4 = false var hasDefaultRoute6 = false lp.routes.forEach rloop@{ @@ -648,12 +637,8 @@ class ConnectionMonitor(context: Context, networkListener: NetworkListener) : null } // test for internet capability iff opPrefs.testReachability is false - if (/*hasInternet(it) == true &&*/ isVPN(it) == false) { - if (activeProp != null) { - newNetworks.add(activeProp) - } - } else { - // no-op + if (/*hasInternet(it) == true &&*/ activeProp != null && isVPN(it) == false) { + newNetworks.add(activeProp) } } val networks = @@ -681,12 +666,8 @@ class ConnectionMonitor(context: Context, networkListener: NetworkListener) : } // test for internet capability iff opPrefs.testReachability is false - if (/*hasInternet(it) == true &&*/ isVPN(it) == false) { - if (prop != null) { - newNetworks.add(prop) - } - } else { - // no-op + if (/*hasInternet(it) == true &&*/ prop != null && isVPN(it) == false) { + newNetworks.add(prop) } } diff --git a/app/src/main/java/com/celzero/bravedns/service/VpnController.kt b/app/src/main/java/com/celzero/bravedns/service/VpnController.kt index 853cb9708..dc46ed450 100644 --- a/app/src/main/java/com/celzero/bravedns/service/VpnController.kt +++ b/app/src/main/java/com/celzero/bravedns/service/VpnController.kt @@ -34,7 +34,6 @@ import kotlinx.coroutines.cancel import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.consumeEach import kotlinx.coroutines.launch -import kotlinx.coroutines.sync.Mutex import org.koin.core.component.KoinComponent import org.koin.core.component.inject @@ -46,13 +45,12 @@ object VpnController : KoinComponent { private var states: Channel? = null private var protocol: Pair = Pair(false, false) - var controllerScope: CoroutineScope? = null + // usually same as vpnScope from BraveVPNService + var externalScope: CoroutineScope? = null private set private var vpnStartElapsedTime: Long = SystemClock.elapsedRealtime() - val mutex: Mutex = Mutex() - // FIXME: Publish VpnState through this live-data to relieve direct access // into VpnController's state(), isOn(), hasTunnel() etc. var connectionStatus: MutableLiveData = MutableLiveData() @@ -65,13 +63,13 @@ object VpnController : KoinComponent { // TODO: make clients listen on create, start, stop, destroy from vpn-service fun onVpnCreated(b: BraveVPNService) { braveVpnService = b - controllerScope = CoroutineScope(Dispatchers.IO) + externalScope = CoroutineScope(Dispatchers.IO) states = Channel(Channel.CONFLATED) // drop unconsumed states // store app start time, used in HomeScreenBottomSheet vpnStartElapsedTime = SystemClock.elapsedRealtime() - controllerScope!!.launch { + externalScope!!.launch { states!!.consumeEach { state -> // transition from paused connection state only on NEW/NULL when (state) { @@ -94,9 +92,11 @@ object VpnController : KoinComponent { fun onVpnDestroyed() { braveVpnService = null - controllerScope?.cancel("stop") states?.cancel() vpnStartElapsedTime = SystemClock.elapsedRealtime() + try { + externalScope?.cancel("VPNController - onVpnDestroyed") + } catch (ignored: IllegalStateException) {} } fun uptimeMs(): Long { @@ -110,7 +110,7 @@ object VpnController : KoinComponent { } fun onConnectionStateChanged(state: BraveVPNService.State?) { - controllerScope?.launch { states?.send(state) } + externalScope?.launch { states?.send(state) } } private fun updateState(state: BraveVPNService.State?) { @@ -120,7 +120,7 @@ object VpnController : KoinComponent { fun start(context: Context) { // if the tunnel has the go-adapter then there's nothing to do - if (braveVpnService?.isOn() == true) { + if (hasTunnel()) { Log.w(LOG_TAG_VPN, "braveVPNService is already on, resending vpn enabled state") return } @@ -151,8 +151,9 @@ object VpnController : KoinComponent { return VpnState(requested, on, connectionState) } + @Deprecated(message = "use hasTunnel() instead", replaceWith = ReplaceWith("hasTunnel()")) fun isOn(): Boolean { - return braveVpnService?.isOn() == true + return hasTunnel() } suspend fun refresh() { From f98ec3d8494692c632c433f1f86ade0bf84d2b8e Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Sat, 13 Apr 2024 21:49:51 +0530 Subject: [PATCH 10/48] fix: dns proxy add apps package name --- .../ui/fragment/DnsProxyListFragment.kt | 59 +++++++++---------- 1 file changed, 27 insertions(+), 32 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt index 3850d0532..19a78e77f 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt @@ -79,22 +79,25 @@ class DnsProxyListFragment : Fragment(R.layout.fragment_dns_proxy_list) { } private fun initClickListeners() { - io { - val appNames: MutableList = ArrayList() - appNames.add(getString(R.string.settings_app_list_default_app)) - appNames.addAll(FirewallManager.getAllAppNames()) - uiCtx { - // see CustomIpFragment#setupClickListeners#bringToFront() - b.dohFabAddServerIcon.bringToFront() - b.dohFabAddServerIcon.setOnClickListener { showAddDnsProxyDialog(appNames) } + b.dohFabAddServerIcon.bringToFront() + b.dohFabAddServerIcon.setOnClickListener { + io { + val appNames: MutableList = ArrayList() + appNames.add(getString(R.string.settings_app_list_default_app)) + appNames.addAll(FirewallManager.getAllAppNames()) + // fetch the count from repository and increment by 1 to show the + // next doh name in the dialog + val nextIndex = appConfig.getDnsProxyCount().plus(1) + uiCtx { + showAddDnsProxyDialog(appNames, nextIndex) + } } } } - private fun showAddDnsProxyDialog(appNames: List) { + private fun showAddDnsProxyDialog(appNames: List, nextIndex: Int) { val dialogBinding = DialogSetDnsProxyBinding.inflate(layoutInflater) - val builder = - MaterialAlertDialogBuilder(requireContext()).setView(dialogBinding.root) + val builder = MaterialAlertDialogBuilder(requireContext()).setView(dialogBinding.root) val lp = WindowManager.LayoutParams() val dialog = builder.create() dialog.show() @@ -112,21 +115,8 @@ class DnsProxyListFragment : Fragment(R.layout.fragment_dns_proxy_list) { val ipAddressEditText = dialogBinding.dialogDnsProxyEditIp val portEditText = dialogBinding.dialogDnsProxyEditPort val errorTxt = dialogBinding.dialogDnsProxyErrorText - - // fetch the count from repository and increment by 1 to show the - // next doh name in the dialog - io { - val nextIndex = appConfig.getDnsProxyCount().plus(1) - uiCtx { - proxyNameEditText.setText( - getString(R.string.cd_custom_dns_proxy_name, nextIndex.toString()), - TextView.BufferType.EDITABLE - ) - } - } - proxyNameEditText.setText( - getString(R.string.cd_custom_dns_proxy_name_default), + getString(R.string.cd_custom_dns_proxy_name, nextIndex.toString()), TextView.BufferType.EDITABLE ) ipAddressEditText.setText( @@ -145,8 +135,7 @@ class DnsProxyListFragment : Fragment(R.layout.fragment_dns_proxy_list) { val mode = getString(R.string.cd_dns_proxy_mode_external) val ip = ipAddressEditText.text.toString() - val appName = getString(R.string.cd_custom_dns_proxy_default_app) - + val appName = appNameSpinner.selectedItem.toString() if (IPAddressString(ip).isIPAddress) { isIpValid = true } else { @@ -172,9 +161,8 @@ class DnsProxyListFragment : Fragment(R.layout.fragment_dns_proxy_list) { } if (isPortValid && isIpValid) { - // Do the DNS Proxy setting there if (DEBUG) Log.d(Logger.LOG_TAG_UI, "new value inserted into DNSProxy") - insertDNSProxyEndpointDB(mode, name, appName, ip, port) + io { insertDNSProxyEndpointDB(mode, name, appName, ip, port) } dialog.dismiss() } else { Log.i(Logger.LOG_TAG_UI, "cannot insert invalid dns-proxy IPs: $name, $appName") @@ -185,7 +173,7 @@ class DnsProxyListFragment : Fragment(R.layout.fragment_dns_proxy_list) { dialog.show() } - private fun insertDNSProxyEndpointDB( + private suspend fun insertDNSProxyEndpointDB( mode: String, name: String, appName: String?, @@ -195,6 +183,12 @@ class DnsProxyListFragment : Fragment(R.layout.fragment_dns_proxy_list) { if (appName == null) return io { + val packageName = + if (appName == getString(R.string.settings_app_list_default_app)) { + "" + } else { + FirewallManager.getPackageNameByAppName(appName) ?: "" + } var proxyName = name if (proxyName.isBlank()) { proxyName = @@ -207,7 +201,7 @@ class DnsProxyListFragment : Fragment(R.layout.fragment_dns_proxy_list) { id = 0, proxyName, mode, - appName, + packageName, ip, port, isSelected = false, @@ -216,7 +210,8 @@ class DnsProxyListFragment : Fragment(R.layout.fragment_dns_proxy_list) { latency = 0 ) appConfig.insertDnsproxyEndpoint(dnsProxyEndpoint) - if (DEBUG) Log.d(Logger.LOG_TAG_UI, "Insert into DNSProxy database- $appName, $port") + if (DEBUG) + Log.d(Logger.LOG_TAG_UI, "Insert into DNSProxy database: $packageName, $port") } } From 056623ca74c6a3c8742dacca282b2937e56b0dd4 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Sat, 13 Apr 2024 21:54:19 +0530 Subject: [PATCH 11/48] ui: fix padding issue in network settings screen --- app/src/full/res/layout/activity_tunnel_settings.xml | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/app/src/full/res/layout/activity_tunnel_settings.xml b/app/src/full/res/layout/activity_tunnel_settings.xml index efeb02de5..1d1a89649 100644 --- a/app/src/full/res/layout/activity_tunnel_settings.xml +++ b/app/src/full/res/layout/activity_tunnel_settings.xml @@ -61,7 +61,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="?android:attr/selectableItemBackground" - android:paddingTop="20dp" + android:paddingTop="15dp" android:paddingBottom="15dp"> + android:paddingBottom="15dp"> @@ -355,6 +355,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="?android:attr/selectableItemBackground" + android:paddingTop="15dp" android:paddingBottom="15dp"> + android:paddingBottom="15dp"> + android:paddingBottom="15dp"> Date: Sat, 13 Apr 2024 21:56:06 +0530 Subject: [PATCH 12/48] minor ui: correct description value in rethink dns list screen --- .../java/com/celzero/bravedns/adapter/RethinkEndpointAdapter.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/full/java/com/celzero/bravedns/adapter/RethinkEndpointAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/RethinkEndpointAdapter.kt index abc36a76d..e225e06b9 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/RethinkEndpointAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/RethinkEndpointAdapter.kt @@ -125,7 +125,7 @@ class RethinkEndpointAdapter(private val context: Context, private val appConfig } private fun keepSelectedStatusUpdated(endpoint: RethinkDnsEndpoint) { - ui { + statusCheckJob = ui { while (true) { updateBlocklistStatusText(endpoint) delay(ONE_SEC) From c515f746cf536b3c7652f6dbb74c67fd198a03e4 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Thu, 18 Apr 2024 18:28:08 +0530 Subject: [PATCH 13/48] ui: show rxtx in wireguard profile --- .../bravedns/adapter/OneWgConfigAdapter.kt | 48 ++++++++++++----- .../bravedns/adapter/WgConfigAdapter.kt | 51 ++++++++++++++----- .../layout/list_item_wg_general_interface.xml | 42 +++++++++++---- .../res/layout/list_item_wg_one_interface.xml | 32 ++++++++++-- 4 files changed, 129 insertions(+), 44 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/adapter/OneWgConfigAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/OneWgConfigAdapter.kt index cf10af51a..875c962e9 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/OneWgConfigAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/OneWgConfigAdapter.kt @@ -31,6 +31,7 @@ import androidx.paging.PagingDataAdapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import backend.Backend +import backend.Stats import com.celzero.bravedns.R import com.celzero.bravedns.database.WgConfigFiles import com.celzero.bravedns.databinding.ListItemWgOneInterfaceBinding @@ -173,25 +174,26 @@ class OneWgConfigAdapter(private val context: Context, private val listener: Dns val statusId = VpnController.getProxyStatusById(id) val pair = VpnController.getSupportedIpVersion(id) val c = WireguardManager.getConfigById(config.id) + val stats = VpnController.getProxyStats(id) val isSplitTunnel = if (c?.getPeers()?.isNotEmpty() == true) { VpnController.isSplitTunnelProxy(id, pair) } else { false } - updateStatusUi(config, statusId) + updateStatusUi(config, statusId, stats) updateProtocolChip(pair) updateSplitTunnelChip(isSplitTunnel) } - private fun updateStatusUi(config: WgConfigFiles, statusId: Long?) { + private fun updateStatusUi(config: WgConfigFiles, statusId: Long?, stats: Stats?) { if (config.isActive) { b.interfaceDetailCard.strokeColor = fetchColor(context, R.color.accentGood) b.interfaceDetailCard.strokeWidth = 2 b.oneWgCheck.isChecked = true b.interfaceAppsCount.visibility = View.VISIBLE b.interfaceAppsCount.text = context.getString(R.string.one_wg_apps_added) - var status = "" + val status: String if (statusId != null) { val resId = UIUtils.getProxyStatusStringRes(statusId) // change the color based on the status @@ -215,10 +217,11 @@ class OneWgConfigAdapter(private val context: Context, private val listener: Dns context.getString(R.string.status_waiting).replaceFirstChar(Char::titlecase) } b.interfaceStatus.text = status - b.interfaceActiveUptime.visibility = View.VISIBLE - val time = getUpTime(config.id) + 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, getUpTime(config.id)) + val t = context.getString(R.string.logs_card_duration, time) b.interfaceActiveUptime.text = context.getString( R.string.two_argument_space, @@ -228,29 +231,46 @@ class OneWgConfigAdapter(private val context: Context, private val listener: Dns } else { b.interfaceActiveUptime.text = context.getString(R.string.lbl_active) } + b.interfaceActiveRxTx.text = rxtx } else { b.interfaceDetailCard.strokeWidth = 0 b.interfaceAppsCount.visibility = View.GONE b.oneWgCheck.isChecked = false - b.interfaceActiveUptime.visibility = View.GONE + b.interfaceActiveLayout.visibility = View.GONE b.interfaceStatus.text = context.getString(R.string.lbl_disabled).replaceFirstChar(Char::titlecase) } } - private fun getUpTime(id: Int): CharSequence { - val startTime = WireguardManager.getActiveConfigTimestamp(id) ?: return "" + private fun getUpTime(stats: Stats?): CharSequence { + if (stats == null) { + return "" + } val now = System.currentTimeMillis() - val uptimeMs = SystemClock.elapsedRealtime() - startTime // returns a string describing 'time' as a time relative to 'now' return DateUtils.getRelativeTimeSpanString( - now - uptimeMs, now, + stats.since, DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE ) } + private fun getRxTx(stats: Stats?): String { + if (stats == null) return "" + val rx = + context.getString( + R.string.symbol_upload, + Utilities.humanReadableByteCount(stats.rx, true) + ) + val tx = + context.getString( + R.string.symbol_download, + Utilities.humanReadableByteCount(stats.tx, true) + ) + return context.getString(R.string.two_argument_space, rx, tx) + } + fun setupClickListeners(config: WgConfigFiles) { b.interfaceDetailCard.setOnClickListener { launchConfigDetail(config.id) } @@ -258,10 +278,10 @@ class OneWgConfigAdapter(private val context: Context, private val listener: Dns val isChecked = b.oneWgCheck.isChecked io { if (isChecked) { - if (WireguardManager.canEnableConfig(config)) { + if (WireguardManager.canEnableConfig(config.toImmutable())) { config.oneWireGuard = true WireguardManager.updateOneWireGuardConfig(config.id, owg = true) - WireguardManager.enableConfig(config) + WireguardManager.enableConfig(config.toImmutable()) uiCtx { listener.onDnsStatusChanged() } } else { uiCtx { @@ -277,7 +297,7 @@ class OneWgConfigAdapter(private val context: Context, private val listener: Dns config.oneWireGuard = false b.oneWgCheck.isChecked = false WireguardManager.updateOneWireGuardConfig(config.id, owg = false) - WireguardManager.disableConfig(config) + WireguardManager.disableConfig(config.toImmutable()) uiCtx { listener.onDnsStatusChanged() } } } diff --git a/app/src/full/java/com/celzero/bravedns/adapter/WgConfigAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/WgConfigAdapter.kt index 6e740f090..685a520dc 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/WgConfigAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/WgConfigAdapter.kt @@ -30,6 +30,7 @@ import androidx.paging.PagingDataAdapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import backend.Backend +import backend.Stats import com.celzero.bravedns.R import com.celzero.bravedns.database.WgConfigFiles import com.celzero.bravedns.databinding.ListItemWgGeneralInterfaceBinding @@ -40,11 +41,11 @@ import com.celzero.bravedns.ui.activity.WgConfigDetailActivity import com.celzero.bravedns.ui.activity.WgConfigEditorActivity.Companion.INTENT_EXTRA_WG_ID import com.celzero.bravedns.util.UIUtils import com.celzero.bravedns.util.Utilities +import java.util.concurrent.ConcurrentHashMap import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch -import java.util.concurrent.ConcurrentHashMap class WgConfigAdapter(private val context: Context) : PagingDataAdapter(DIFF_CALLBACK) { @@ -207,6 +208,7 @@ class WgConfigAdapter(private val context: Context) : val statusId = VpnController.getProxyStatusById(id) val pair = VpnController.getSupportedIpVersion(id) val c = WireguardManager.getConfigById(config.id) + val stats = VpnController.getProxyStats(id) val isSplitTunnel = if (c?.getPeers()?.isNotEmpty() == true) { VpnController.isSplitTunnelProxy(id, pair) @@ -225,7 +227,7 @@ class WgConfigAdapter(private val context: Context) : cancelAllJobs() return } - updateStatusUi(config, statusId) + updateStatusUi(config, statusId, stats) updateUi(config, appsCount) updateProtocolChip(pair) updateSplitTunnelChip(isSplitTunnel) @@ -270,17 +272,18 @@ class WgConfigAdapter(private val context: Context) : } } - private fun updateStatusUi(config: WgConfigFiles, statusId: Long?) { + private fun updateStatusUi(config: WgConfigFiles, statusId: Long?, stats: Stats?) { if (config.isActive) { b.interfaceSwitch.isChecked = true b.interfaceDetailCard.strokeWidth = 2 b.interfaceStatus.visibility = View.VISIBLE b.interfaceConfigStatus.visibility = View.VISIBLE - var status = "" - b.interfaceActiveUptime.visibility = View.VISIBLE - val time = getUpTime(config.id) + val status: String + b.interfaceActiveLayout.visibility = View.VISIBLE + val time = getUpTime(stats) + val rxtx = getRxTx(stats) if (time.isNotEmpty()) { - val t = context.getString(R.string.logs_card_duration, getUpTime(config.id)) + val t = context.getString(R.string.logs_card_duration, time) b.interfaceActiveUptime.text = context.getString( R.string.two_argument_space, @@ -290,6 +293,7 @@ class WgConfigAdapter(private val context: Context) : } else { b.interfaceActiveUptime.text = context.getString(R.string.lbl_active) } + b.interfaceActiveRxTx.text = rxtx if (statusId != null) { val resId = UIUtils.getProxyStatusStringRes(statusId) // change the color based on the status @@ -313,7 +317,7 @@ class WgConfigAdapter(private val context: Context) : } b.interfaceStatus.text = status } else { - b.interfaceActiveUptime.visibility = View.GONE + b.interfaceActiveLayout.visibility = View.GONE b.interfaceDetailCard.strokeColor = UIUtils.fetchColor(context, R.attr.background) b.interfaceDetailCard.strokeWidth = 0 b.interfaceSwitch.isChecked = false @@ -325,8 +329,26 @@ class WgConfigAdapter(private val context: Context) : } } - private fun getUpTime(id: Int): CharSequence { - val startTime = WireguardManager.getActiveConfigTimestamp(id) ?: return "" + private fun getRxTx(stats: Stats?): String { + if (stats == null) return "" + val rx = + context.getString( + R.string.symbol_upload, + Utilities.humanReadableByteCount(stats.rx, true) + ) + val tx = + context.getString( + R.string.symbol_download, + Utilities.humanReadableByteCount(stats.tx, true) + ) + return context.getString(R.string.two_argument_space, rx, tx) + } + + private fun getUpTime(stats: Stats?): CharSequence { + var startTime = 0L + if (stats != null) { + startTime = stats.since + } val now = System.currentTimeMillis() val uptimeMs = SystemClock.elapsedRealtime() - startTime // returns a string describing 'time' as a time relative to 'now' @@ -343,9 +365,10 @@ class WgConfigAdapter(private val context: Context) : b.interfaceSwitch.setOnCheckedChangeListener(null) b.interfaceSwitch.setOnClickListener { + val cfg = config.toImmutable() if (b.interfaceSwitch.isChecked) { - if (WireguardManager.canEnableConfig(config)) { - WireguardManager.enableConfig(config) + if (WireguardManager.canEnableConfig(cfg)) { + WireguardManager.enableConfig(cfg) } else { Utilities.showToastUiCentered( context, @@ -355,8 +378,8 @@ class WgConfigAdapter(private val context: Context) : b.interfaceSwitch.isChecked = false } } else { - if (WireguardManager.canDisableConfig(config)) { - WireguardManager.disableConfig(config) + if (WireguardManager.canDisableConfig(cfg)) { + WireguardManager.disableConfig(cfg) } else { Utilities.showToastUiCentered( context, diff --git a/app/src/main/res/layout/list_item_wg_general_interface.xml b/app/src/main/res/layout/list_item_wg_general_interface.xml index 126d5de09..98a00c574 100644 --- a/app/src/main/res/layout/list_item_wg_general_interface.xml +++ b/app/src/main/res/layout/list_item_wg_general_interface.xml @@ -34,8 +34,7 @@ android:layout_alignParentStart="true" android:layout_centerVertical="true" android:layout_toStartOf="@id/interface_switch" - android:orientation="vertical" - android:padding="5dp"> + android:orientation="vertical"> - + android:visibility="gone"> + + + + + @@ -166,7 +186,7 @@ android:layout_centerVertical="true" android:clickable="true" android:focusable="true" - android:padding="8dp" + android:padding="5dp" android:textColor="@color/colorPrimary" android:textSize="16sp" /> diff --git a/app/src/main/res/layout/list_item_wg_one_interface.xml b/app/src/main/res/layout/list_item_wg_one_interface.xml index 18ba6d5af..3a74363f4 100644 --- a/app/src/main/res/layout/list_item_wg_one_interface.xml +++ b/app/src/main/res/layout/list_item_wg_one_interface.xml @@ -131,15 +131,37 @@ android:textColor="?attr/primaryLightColorText" android:textSize="@dimen/default_font_text_view" /> - + android:visibility="gone"> + + + + + From 72c6501d576eeacaa6dee956ab1b6fe530ddc4f7 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Thu, 18 Apr 2024 18:42:56 +0530 Subject: [PATCH 14/48] ui: show rxtx in wireguard profile --- .../java/com/celzero/bravedns/adapter/WgConfigAdapter.kt | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/adapter/WgConfigAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/WgConfigAdapter.kt index 685a520dc..3a4c38866 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/WgConfigAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/WgConfigAdapter.kt @@ -17,7 +17,6 @@ package com.celzero.bravedns.adapter import android.content.Context import android.content.Intent -import android.os.SystemClock import android.text.format.DateUtils import android.view.LayoutInflater import android.view.View @@ -345,16 +344,14 @@ class WgConfigAdapter(private val context: Context) : } private fun getUpTime(stats: Stats?): CharSequence { - var startTime = 0L - if (stats != null) { - startTime = stats.since + if (stats == null) { + return "" } val now = System.currentTimeMillis() - val uptimeMs = SystemClock.elapsedRealtime() - startTime // returns a string describing 'time' as a time relative to 'now' return DateUtils.getRelativeTimeSpanString( - now - uptimeMs, now, + stats.since, DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE ) From 0d7e43c61d3bc6855f19c68bead55130d13a6a8e Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Thu, 18 Apr 2024 18:47:39 +0530 Subject: [PATCH 15/48] ui: wireguard screen changes, show dns search domains in dns edit text --- .../bravedns/adapter/WgIncludeAppsAdapter.kt | 19 +- .../ui/activity/WgConfigEditorActivity.kt | 11 +- .../bravedns/ui/dialog/WgIncludeAppsDialog.kt | 2 +- .../res/layout/activity_wg_config_editor.xml | 53 ++- .../main/res/layout/dialog_wg_add_peer.xml | 371 ++++++++++-------- .../res/layout/list_item_wg_include_apps.xml | 120 +++--- .../res/layout/wg_apps_include_dialog.xml | 4 +- 7 files changed, 327 insertions(+), 253 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/adapter/WgIncludeAppsAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/WgIncludeAppsAdapter.kt index d98967ac3..61c1ac12d 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/WgIncludeAppsAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/WgIncludeAppsAdapter.kt @@ -36,6 +36,7 @@ import com.celzero.bravedns.databinding.ListItemWgIncludeAppsBinding import com.celzero.bravedns.service.FirewallManager import com.celzero.bravedns.service.ProxyManager import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_PROXY +import com.celzero.bravedns.util.UIUtils import com.celzero.bravedns.util.Utilities.getDefaultIcon import com.celzero.bravedns.util.Utilities.getIcon import com.google.android.material.dialog.MaterialAlertDialogBuilder @@ -99,16 +100,18 @@ class WgIncludeAppsAdapter( b.wgIncludeAppAppDescTv.text = "" b.wgIncludeAppAppDescTv.visibility = View.GONE b.wgIncludeAppListCheckbox.isChecked = false + setCardBackground(false) } else if (mapping.proxyId != proxyId) { - b.wgIncludeAppAppDescTv.text = context.getString(R.string.wireguard_apps_proxy_map_desc, mapping.proxyName) b.wgIncludeAppAppDescTv.visibility = View.VISIBLE b.wgIncludeAppListCheckbox.isChecked = false + setCardBackground(false) } else { b.wgIncludeAppAppDescTv.text = "" b.wgIncludeAppAppDescTv.visibility = View.GONE b.wgIncludeAppListCheckbox.isChecked = mapping.proxyId == proxyId + setCardBackground(true) } val isIncluded = mapping.proxyId == proxyId && mapping.proxyId != "" @@ -117,7 +120,7 @@ class WgIncludeAppsAdapter( } private fun setupClickListeners(mapping: ProxyApplicationMapping, isIncluded: Boolean) { - b.wgIncludeAppListContainer.setOnClickListener { + b.wgIncludeCard.setOnClickListener { Log.i(LOG_TAG_PROXY, "wgIncludeAppListContainer- ${mapping.appName}, $isIncluded") updateInterfaceDetails(mapping, !isIncluded) } @@ -137,6 +140,16 @@ class WgIncludeAppsAdapter( .into(b.wgIncludeAppListApkIconIv) } + + private fun setCardBackground(isSelected: Boolean) { + if (isSelected) { + b.wgIncludeCard.setCardBackgroundColor(UIUtils.fetchColor(context, R.attr.selectedCardBg)) + } else { + b.wgIncludeCard.setCardBackgroundColor(UIUtils.fetchColor(context, R.attr.background)) + } + } + + private fun updateInterfaceDetails(mapping: ProxyApplicationMapping, include: Boolean) { io { val appUidList = FirewallManager.getAppNamesByUid(mapping.uid) @@ -156,7 +169,7 @@ class WgIncludeAppsAdapter( ProxyManager.updateProxyIdForApp(mapping.uid, proxyId, proxyName) Log.i(LOG_TAG_PROXY, "Included apps: ${mapping.uid}, $proxyId, $proxyName") } else { - ProxyManager.removeProxyIdForApp(mapping.uid) + ProxyManager.setNoProxyForApp(mapping.uid) uiCtx { b.wgIncludeAppListCheckbox.isChecked = false } Log.i(LOG_TAG_PROXY, "Removed apps: ${mapping.uid}, $proxyId, $proxyName") } diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigEditorActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigEditorActivity.kt index 718448f91..ca865076e 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigEditorActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigEditorActivity.kt @@ -94,13 +94,14 @@ class WgConfigEditorActivity : AppCompatActivity(R.layout.activity_wg_config_edi b.privateKeyText.setText(wgInterface?.getKeyPair()?.getPrivateKey()?.base64()) b.publicKeyText.setText(wgInterface?.getKeyPair()?.getPublicKey()?.base64()) - if (wgInterface?.dnsServers?.isEmpty() != true) { - b.dnsServersText.setText( - wgInterface?.dnsServers?.joinToString { it.hostAddress?.toString() ?: "" } - ) + var dns = wgInterface?.dnsServers?.joinToString { it.hostAddress?.toString() ?: "" } + val searchDomains = wgInterface?.dnsSearchDomains?.joinToString { it } + dns = if (!searchDomains.isNullOrEmpty()) { + "$dns,$searchDomains" } else { - b.dnsServersText.setText(wgInterface?.dnsSearchDomains?.joinToString { it }) + dns } + b.dnsServersText.setText(dns) if (wgInterface?.getAddresses()?.isEmpty() != true) { b.addressesLabelText.setText( wgInterface?.getAddresses()?.joinToString { it.toString() } diff --git a/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt b/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt index ef404854a..75a61a29e 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt @@ -263,7 +263,7 @@ class WgIncludeAppsDialog( ProxyManager.setProxyIdForAllApps(proxyId, proxyName) } else { Log.i(LOG_TAG_PROXY, "Removing all apps from proxy $proxyId, $proxyName") - ProxyManager.removeProxyForAllApps() + ProxyManager.setNoProxyForAllApps() } } } diff --git a/app/src/main/res/layout/activity_wg_config_editor.xml b/app/src/main/res/layout/activity_wg_config_editor.xml index eb5b5dde7..e18149d72 100644 --- a/app/src/main/res/layout/activity_wg_config_editor.xml +++ b/app/src/main/res/layout/activity_wg_config_editor.xml @@ -3,34 +3,37 @@ xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" - android:background="?attr/background" - android:paddingStart="5dp" - android:paddingEnd="5dp"> + android:background="?attr/background"> - + android:layout_height="match_parent" + android:layout_margin="8dp" + android:elevation="8dp" + android:focusableInTouchMode="true" + app:cardBackgroundColor="?attr/background" + app:cardCornerRadius="16dp"> - + android:layout_height="match_parent" + android:orientation="vertical" + android:paddingStart="5dp" + android:paddingEnd="5dp"> + android:layout_height="wrap_content"> @@ -42,6 +45,7 @@ android:layout_height="wrap_content" android:layout_margin="4dp" android:hint="@string/cd_dns_crypt_dialog_name" + android:paddingTop="15dp" app:boxCornerRadiusBottomEnd="8dp" app:boxCornerRadiusBottomStart="8dp" app:boxCornerRadiusTopEnd="8dp" @@ -65,6 +69,7 @@ android:layout_height="wrap_content" android:layout_margin="4dp" android:hint="@string/lbl_private_key" + android:paddingTop="15dp" app:boxCornerRadiusBottomEnd="8dp" app:boxCornerRadiusBottomStart="8dp" app:boxCornerRadiusTopEnd="8dp" @@ -91,6 +96,7 @@ android:layout_height="wrap_content" android:layout_margin="4dp" android:hint="@string/lbl_public_key" + android:paddingTop="15dp" app:boxCornerRadiusBottomEnd="8dp" app:boxCornerRadiusBottomStart="8dp" app:boxCornerRadiusTopEnd="8dp" @@ -119,6 +125,7 @@ android:layout_height="wrap_content" android:layout_margin="4dp" android:hint="@string/lbl_addresses" + android:paddingTop="15dp" app:boxCornerRadiusBottomEnd="8dp" app:boxCornerRadiusBottomStart="8dp" app:boxCornerRadiusTopEnd="8dp" @@ -144,6 +151,7 @@ android:layout_height="wrap_content" android:layout_margin="4dp" android:hint="@string/lbl_listen_port" + android:paddingTop="15dp" app:boxCornerRadiusBottomEnd="8dp" app:boxCornerRadiusBottomStart="8dp" app:boxCornerRadiusTopEnd="8dp" @@ -171,6 +179,7 @@ android:layout_height="wrap_content" android:layout_margin="4dp" android:hint="@string/lbl_dns_servers" + android:paddingTop="15dp" app:boxCornerRadiusBottomEnd="8dp" app:boxCornerRadiusBottomStart="8dp" app:boxCornerRadiusTopEnd="8dp" @@ -204,6 +213,7 @@ android:layout_height="wrap_content" android:layout_margin="4dp" android:hint="@string/lbl_mtu" + android:paddingTop="15dp" app:boxCornerRadiusBottomEnd="8dp" app:boxCornerRadiusBottomStart="8dp" app:boxCornerRadiusTopEnd="8dp" @@ -226,10 +236,17 @@ + + - - - - + + \ No newline at end of file diff --git a/app/src/main/res/layout/dialog_wg_add_peer.xml b/app/src/main/res/layout/dialog_wg_add_peer.xml index 8b9eb7b45..e1e0d1458 100644 --- a/app/src/main/res/layout/dialog_wg_add_peer.xml +++ b/app/src/main/res/layout/dialog_wg_add_peer.xml @@ -3,177 +3,210 @@ xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" - android:background="?attr/background" - android:paddingStart="5dp" - android:paddingEnd="5dp"> - - - - - - - - - - - - - - - - - - - - - - - - + + - - - - - - - - - + android:layout_margin="8dp" + android:elevation="8dp" + android:focusableInTouchMode="true" + app:cardBackgroundColor="?attr/background" + app:cardCornerRadius="16dp"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/list_item_wg_include_apps.xml b/app/src/main/res/layout/list_item_wg_include_apps.xml index 02bf1453a..935ea37f9 100644 --- a/app/src/main/res/layout/list_item_wg_include_apps.xml +++ b/app/src/main/res/layout/list_item_wg_include_apps.xml @@ -1,75 +1,85 @@ + android:layout_height="wrap_content"> - + app:cardBackgroundColor="?attr/background" + app:cardCornerRadius="2dp" + app:cardElevation="2dp" + app:cardUseCompatPadding="true"> - - - + android:layout_marginStart="5dp" + android:paddingTop="5dp" + android:paddingBottom="5dp"> - + android:layout_marginTop="5dp" + android:layout_marginEnd="5dp" + android:layout_marginBottom="5dp" + android:maxWidth="40dp" + android:maxHeight="40dp" + tools:src="?attr/primaryTextColor" /> - + android:layout_centerVertical="true" + android:layout_marginStart="10dp" + android:layout_toStartOf="@id/wg_include_app_list_checkbox" + android:layout_toEndOf="@id/wg_include_app_list_apk_icon_iv" + android:orientation="vertical"> - + + - + + + + - + + diff --git a/app/src/main/res/layout/wg_apps_include_dialog.xml b/app/src/main/res/layout/wg_apps_include_dialog.xml index fc25f745e..0621d1837 100644 --- a/app/src/main/res/layout/wg_apps_include_dialog.xml +++ b/app/src/main/res/layout/wg_apps_include_dialog.xml @@ -126,7 +126,9 @@ android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@id/wg_include_app_dialog_ok_button" - android:layout_below="@id/wg_include_app_select_all" /> + android:layout_below="@id/wg_include_app_select_all" + android:clickable="true" + android:focusable="true" /> Date: Thu, 18 Apr 2024 19:16:30 +0530 Subject: [PATCH 16/48] v055f: tunnel changes - handle wireguard handshake and refresh wg - changes in usage of data class/entity class as key in collections - handle app selected in dns proxy config - make rethink max as DoH - use livedata to detect dnscrypt relay changes - rename/rmv variables and methods --- .../celzero/bravedns/service/ProxyManager.kt | 144 +++--- .../bravedns/service/WireguardManager.kt | 241 +++++----- .../com/celzero/bravedns/data/AppConfig.kt | 3 + .../bravedns/data/ConnTrackerMetaData.kt | 1 + .../bravedns/data/ConnectionSummary.kt | 1 + .../java/com/celzero/bravedns/data/FileTag.kt | 1 + .../database/ProxyAppMappingRepository.kt | 16 +- .../database/ProxyApplicationMappingDAO.kt | 2 +- .../bravedns/database/RefreshDatabase.kt | 17 +- .../bravedns/database/WgConfigFiles.kt | 45 +- .../celzero/bravedns/net/go/GoVpnAdapter.kt | 89 +++- .../bravedns/service/BraveVPNService.kt | 420 +++++++++++------- .../bravedns/service/ConnectionMonitor.kt | 3 +- .../bravedns/service/FirewallManager.kt | 2 +- .../bravedns/service/PersistentState.kt | 10 +- .../celzero/bravedns/service/VpnController.kt | 5 + .../com/celzero/bravedns/wireguard/Config.kt | 12 +- 17 files changed, 639 insertions(+), 373 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/service/ProxyManager.kt b/app/src/full/java/com/celzero/bravedns/service/ProxyManager.kt index d7dbffdbe..790879355 100644 --- a/app/src/full/java/com/celzero/bravedns/service/ProxyManager.kt +++ b/app/src/full/java/com/celzero/bravedns/service/ProxyManager.kt @@ -18,7 +18,6 @@ package com.celzero.bravedns.service import android.util.Log import backend.Backend import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG -import com.celzero.bravedns.data.AppConfig import com.celzero.bravedns.database.AppInfo import com.celzero.bravedns.database.ProxyAppMappingRepository import com.celzero.bravedns.database.ProxyApplicationMapping @@ -30,7 +29,6 @@ import java.util.concurrent.CopyOnWriteArraySet object ProxyManager : KoinComponent { private val db: ProxyAppMappingRepository by inject() - private val appConfig: AppConfig by inject() const val ID_ORBOT_BASE = "ORBOT" const val ID_WG_BASE = "wg" @@ -44,7 +42,7 @@ object ProxyManager : KoinComponent { // we are using ProxyAppMapTuple instead of ProxyApplicationMapping for the pamSet as the equals // and hash method implementation is overridden and cannot be used for the pamSet - data class ProxyAppMapTuple(val uid: Int, val packageName: String, var proxyId: String) + data class ProxyAppMapTuple(val uid: Int, val packageName: String, val proxyId: String) // TODO: consider adding other proxy modes (e.g, Wireguard, Rethink, etc.) enum class ProxyMode(val value: Int) { @@ -83,12 +81,13 @@ object ProxyManager : KoinComponent { } } - private var pamSet = CopyOnWriteArraySet() + private val pamSet = CopyOnWriteArraySet() suspend fun load(): Int { val a = db.getApps() - val tuple = a.map { ProxyAppMapTuple(it.uid, it.packageName, it.proxyId) } - pamSet = CopyOnWriteArraySet(tuple) + val entries = a.map { ProxyAppMapTuple(it.uid, it.packageName, it.proxyId) } + pamSet.clear() + pamSet.addAll(entries) return a.size } @@ -97,43 +96,29 @@ object ProxyManager : KoinComponent { return m?.proxyId ?: ID_NONE } - suspend fun updateProxyIdForApp(uid: Int, proxyId: String, proxyName: String) { - val m = pamSet.filter { it.uid == uid } - if (!isValidProxyPrefix(proxyId)) { - Log.e(LOG_TAG_PROXY, "Invalid config id: $proxyId") + // get the proxy id for the app, if not found return the default proxy id. + // proxyId cannot be empty. + suspend fun updateProxyIdForApp(uid: Int, nonEmptyProxyId: String, proxyName: String) { + if (!isValidProxyPrefix(nonEmptyProxyId)) { + Log.e(LOG_TAG_PROXY, "cannot update $nonEmptyProxyId; setNoProxyForApp instead?") return } + val m = pamSet.filter { it.uid == uid } // returns a reference to underlying data-class if (m.isNotEmpty()) { - m.forEach { - if (DEBUG) Log.d(LOG_TAG_PROXY, "add $proxyId for ${it.packageName} / uid $uid") - it.proxyId = proxyId - } - db.updateProxyIdForApp(uid, proxyId, proxyName) + val n = m.map { ProxyAppMapTuple(it.uid, it.packageName, nonEmptyProxyId)} + // in-place updates in Set does not remove dups on conflicts: pl.kotl.in/hEHOgk3V0 + // that is, m.forEach { it.proxyName = nonEmptyProxyId } will not de-dup an existing + // entry with the same uid+package-name+proxy-id, and instead will retain both entries. + pamSet.removeAll(m.toSet()) + pamSet.addAll(n) + db.updateProxyIdForApp(uid, nonEmptyProxyId, proxyName) } else { Log.e(LOG_TAG_PROXY, "updateProxyIdForApp: map not found for uid $uid") } } - fun isProxyActive(proxyId: String): Boolean { - return if (proxyId.contains(ID_NONE)) { - false - } else if (proxyId.contains(ID_ORBOT_BASE)) { - appConfig.isOrbotProxyEnabled() - } else if (proxyId.contains(ID_WG_BASE)) { - WireguardManager.isConfigActive(proxyId) - } else if (proxyId.contains(ID_TCP_BASE)) { - TcpProxyHelper.isTcpProxyEnabled() - } else if (proxyId.contains(ID_S5_BASE)) { - appConfig.isCustomSocks5Enabled() - } else if (proxyId.contains(ID_HTTP_BASE)) { - appConfig.isCustomHttpProxyEnabled() - } else { - false - } - } - - fun getProxyMapping(): MutableSet { + fun trackedApps(): MutableSet { return pamSet.map { FirewallManager.AppInfoTuple(it.uid, it.packageName) }.toMutableSet() } @@ -143,12 +128,15 @@ object ProxyManager : KoinComponent { Log.e(LOG_TAG_PROXY, "Invalid proxy id: $proxyId") return } - pamSet.forEach { it.proxyId = proxyId } + val m = pamSet.map { ProxyAppMapTuple(it.uid, it.packageName, proxyId) } + pamSet.clear() + pamSet.addAll(m) db.updateProxyForAllApps(proxyId, proxyName) Log.i(LOG_TAG_PROXY, "added all apps to proxy: $proxyId") } suspend fun updateProxyNameForProxyId(proxyId: String, proxyName: String) { + // pamSet does not store proxy-name, so nothing to update there db.updateProxyNameForProxyId(proxyId, proxyName) } @@ -158,64 +146,75 @@ object ProxyManager : KoinComponent { Log.e(LOG_TAG_PROXY, "Invalid proxy id: $proxyId") return } - pamSet.filter { it.proxyId == "" }.forEach { it.proxyId = proxyId } + val m = pamSet.filter { it.proxyId == "" }.toSet() + val n = m.map { ProxyAppMapTuple(it.uid, it.packageName, proxyId) } + pamSet.removeAll(m) + pamSet.addAll(n) db.updateProxyForUnselectedApps(proxyId, proxyName) Log.i(LOG_TAG_PROXY, "added unselected apps to interface: $proxyId") } - suspend fun removeProxyIdForApp(uid: Int) { - val m = pamSet.filter { it.uid == uid } + suspend fun setNoProxyForApp(uid: Int) { + val noProxy = "" + val m = pamSet.filter { it.uid == uid }.toSet() if (m.isNotEmpty()) { - m.forEach { it.proxyId = "" } + val n = m.map { ProxyAppMapTuple(it.uid, it.packageName, noProxy) } + pamSet.removeAll(m) + pamSet.addAll(n) // update the id as empty string to remove the proxy - db.updateProxyIdForApp(uid, "", "") + db.updateProxyIdForApp(uid, noProxy, noProxy) } else { - Log.e(LOG_TAG_PROXY, "app config mapping is null for uid $uid on removeProxyIdForApp") + Log.e(LOG_TAG_PROXY, "app config mapping is null for uid $uid on setNoProxyForApp") } } - suspend fun removeProxyForAllApps() { + suspend fun setNoProxyForAllApps() { + val noProxy = "" Log.i(LOG_TAG_PROXY, "Removing all apps from proxy") - pamSet.forEach { it.proxyId = "" } - db.updateProxyForAllApps("", "") + val m = pamSet.filter { it.proxyId != noProxy }.toSet() + val n = m.map { ProxyAppMapTuple(it.uid, it.packageName, noProxy) } + pamSet.removeAll(m) + pamSet.addAll(n) + db.updateProxyForAllApps(noProxy, noProxy) } - suspend fun removeProxyForAllApps(proxyId: String) { + suspend fun removeProxyId(proxyId: String) { Log.i(LOG_TAG_PROXY, "Removing all apps from proxy with id: $proxyId") - pamSet.filter { it.proxyId == proxyId }.forEach { it.proxyId = "" } + val noProxy = "" + val m = pamSet.filter { it.proxyId == proxyId }.toSet() + val n = m.map { ProxyAppMapTuple(it.uid, it.packageName, noProxy) } + pamSet.removeAll(m) + pamSet.addAll(n) db.removeAllAppsForProxy(proxyId) } - suspend fun deleteMappings(m: Collection) { + suspend fun deleteApps(m: Collection) { m.forEach { deleteApp(it) } } - suspend fun addMappings(m: Collection) { + suspend fun addApps(m: Collection) { m.forEach { addNewApp(it) } } suspend fun purgeDupsBeforeRefresh() { val visited = mutableSetOf() - val printList = mutableListOf() val dups = mutableSetOf() pamSet .map { FirewallManager.AppInfoTuple(it.uid, it.packageName) } .forEach { - printList.add(it) if (visited.contains(it)) dups.add(it) else visited.add(it) } // duplicates are unexpected; but since refreshDatabase only deals in uid+package-name // and proxy-mapper primary keys on uid+package-name+proxy-id, there have been cases // of duplicate entries in the proxy-mapper. Purge all entries that have same - // uid+package-name - // pair. Note that, doing so also removes entry for an app even if it is currently - // installed. + // uid+package-name pair. Note that, doing so also removes entry for an app even if it is + // currently installed. // This is okay, given we do not expect any dups. Also: This fn must be called before // refreshDatabase so that any entries removed are added back as "new mappings" via // addNewApp if (dups.size > 0) { Log.w(LOG_TAG_PROXY, "delete dup pxms: $dups") - deleteMappings(dups) + deleteApps(dups) } else { // no dups found Log.i(LOG_TAG_PROXY, "no dups found") @@ -233,24 +232,9 @@ object ProxyManager : KoinComponent { true, proxyName ) - db.insert(pam) val pamTuple = ProxyAppMapTuple(appInfo.uid, appInfo.packageName, proxyId) pamSet.add(pamTuple) - } - - suspend fun deleteApp(appInfo: AppInfo) { - val pam = - ProxyApplicationMapping( - appInfo.uid, - appInfo.packageName, - appInfo.appName, - "", - false, - "" - ) - db.delete(pam) - deleteFromCache(pam) - if (DEBUG) Log.d(LOG_TAG_PROXY, "Deleting app for proxy: ${pam.appName}, ${pam.uid}") + db.insert(pam) } private fun deleteFromCache(pam: ProxyApplicationMapping) { @@ -261,17 +245,25 @@ object ProxyManager : KoinComponent { } } + suspend fun deleteApp(appInfo: AppInfo) { + return deleteApp(appInfo.uid, appInfo.packageName) + } + suspend fun deleteApp(appInfoTuple: FirewallManager.AppInfoTuple) { + return deleteApp(appInfoTuple.uid, appInfoTuple.packageName) + } + + suspend fun deleteApp(uid: Int, packageName: String) { val pam = - ProxyApplicationMapping(appInfoTuple.uid, appInfoTuple.packageName, "", "", false, "") - db.delete(pam) + ProxyApplicationMapping(uid, packageName, "", "", false, "") deleteFromCache(pam) + db.deleteApp(pam) if (DEBUG) Log.d(LOG_TAG_PROXY, "Deleting app for mapping: ${pam.appName}, ${pam.uid}") } suspend fun clear() { - db.deleteAll() pamSet.clear() + db.deleteAll() } fun isAnyAppSelected(proxyId: String): Boolean { @@ -293,8 +285,12 @@ object ProxyManager : KoinComponent { suspend fun removeWgProxies() { // remove all the wg proxies from the app config mappings, during restore process + val noProxy = "" + val m = pamSet.filter { it.proxyId.startsWith(ID_WG_BASE) }.toSet() + val n = m.map { ProxyAppMapTuple(it.uid, it.packageName, noProxy) } + pamSet.removeAll(m) + pamSet.addAll(n) db.removeAllWgProxies() - pamSet.filter { it.proxyId.startsWith(ID_WG_BASE) }.forEach { it.proxyId = "" } } fun isIpnProxy(ipnProxyId: String): Boolean { diff --git a/app/src/full/java/com/celzero/bravedns/service/WireguardManager.kt b/app/src/full/java/com/celzero/bravedns/service/WireguardManager.kt index 2c67b43f2..35913bf20 100644 --- a/app/src/full/java/com/celzero/bravedns/service/WireguardManager.kt +++ b/app/src/full/java/com/celzero/bravedns/service/WireguardManager.kt @@ -24,6 +24,7 @@ import com.celzero.bravedns.customdownloader.IWireguardWarp import com.celzero.bravedns.customdownloader.RetrofitManager import com.celzero.bravedns.data.AppConfig import com.celzero.bravedns.database.WgConfigFiles +import com.celzero.bravedns.database.WgConfigFilesImmutable import com.celzero.bravedns.database.WgConfigFilesRepository import com.celzero.bravedns.util.Constants.Companion.WIREGUARD_FOLDER_NAME import com.celzero.bravedns.util.Logger @@ -32,7 +33,12 @@ import com.celzero.bravedns.wireguard.BadConfigException import com.celzero.bravedns.wireguard.Config import com.celzero.bravedns.wireguard.Peer import com.celzero.bravedns.wireguard.WgInterface -import inet.ipaddr.IPAddressString +import java.io.ByteArrayInputStream +import java.io.File +import java.io.InputStream +import java.nio.charset.StandardCharsets +import java.util.Locale +import java.util.concurrent.CopyOnWriteArraySet import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -40,12 +46,6 @@ import org.json.JSONObject import org.koin.core.component.KoinComponent import org.koin.core.component.inject import retrofit2.converter.gson.GsonConverterFactory -import java.io.ByteArrayInputStream -import java.io.File -import java.io.InputStream -import java.nio.charset.StandardCharsets -import java.util.Locale -import java.util.concurrent.CopyOnWriteArraySet object WireguardManager : KoinComponent { @@ -54,7 +54,7 @@ object WireguardManager : KoinComponent { private val appConfig: AppConfig by inject() // contains db values of wg configs (db stores path of the config file) - private var mappings: CopyOnWriteArraySet = CopyOnWriteArraySet() + private var mappings: CopyOnWriteArraySet = CopyOnWriteArraySet() // contains parsed wg configs private var configs: CopyOnWriteArraySet = CopyOnWriteArraySet() @@ -64,10 +64,6 @@ object WireguardManager : KoinComponent { // warp response json keys private const val JSON_RESPONSE_WORKS = "works" private const val JSON_RESPONSE_REASON = "reason" - private const val JSON_RESPONSE_QUOTA = "quota" - - // map to store the active wireguard configs timestamp for the active time calculation - private val activeConfigTimestamps = HashMap() // warp primary and secondary config names, ids and file names const val SEC_WARP_NAME = "SEC_WARP" @@ -87,16 +83,22 @@ object WireguardManager : KoinComponent { if (configs.isNotEmpty()) { Log.i(LOG_TAG_PROXY, "configs already loaded; refreshing...") } - mappings = CopyOnWriteArraySet(db.getWgConfigs()) + val m = db.getWgConfigs().map { it.toImmutable() } + mappings = CopyOnWriteArraySet(m) mappings.forEach { val path = it.configPath val config = EncryptedFileManager.readWireguardConfig(applicationContext, path) ?: return@forEach if (configs.none { i -> i.getId() == it.id }) { - config.setId(it.id) - config.setName(it.name) + val c = + Config.Builder() + .setId(it.id) + .setName(it.name) + .setInterface(config.getInterface()) + .addPeers(config.getPeers()) + .build() if (DEBUG) Log.d(LOG_TAG_PROXY, "read wg config: ${it.id}, ${it.name}") - configs.add(config) + configs.add(c) } } return configs.size @@ -115,7 +117,7 @@ object WireguardManager : KoinComponent { return config } - fun getConfigFilesById(id: Int): WgConfigFiles? { + fun getConfigFilesById(id: Int): WgConfigFilesImmutable? { val config = mappings.find { it.id == id } if (config == null) { Log.e(LOG_TAG_PROXY, "getConfigFilesById: wg not found: $id, ${configs.size}") @@ -163,14 +165,14 @@ object WireguardManager : KoinComponent { } fun getSecWarpConfig(): Config? { - return configs.firstOrNull { it.getId() == SEC_WARP_ID } + return configs.find { it.getId() == SEC_WARP_ID } } fun isSecWarpAvailable(): Boolean { return configs.any { it.getId() == SEC_WARP_ID } } - fun enableConfig(unmapped: WgConfigFiles) { + fun enableConfig(unmapped: WgConfigFilesImmutable) { val map = mappings.find { it.id == unmapped.id } if (map == null) { Log.e(LOG_TAG_PROXY, "enableConfig: wg not found, id: ${unmapped.id}, ${mappings.size}") @@ -185,8 +187,22 @@ object WireguardManager : KoinComponent { } // enable the config, update to db, cache and tunnel - map.isActive = true // also update mappings: https://pl.kotl.in/g0mVapn4x - io { db.update(map) } + mappings.remove(map) + val newMap = + WgConfigFilesImmutable( + map.id, + map.name, + map.configPath, + map.serverResponse, + true, // also update mappings: https://pl.kotl.in/g0mVapn4x + map.isCatchAll, + map.isLockdown, + map.oneWireGuard, + map.isDeletable + ) + mappings.add(newMap) + val dbMap = WgConfigFiles.fromImmutable(newMap) + io { db.update(dbMap) } val proxyType = AppConfig.ProxyType.WIREGUARD val proxyProvider = AppConfig.ProxyProvider.WIREGUARD appConfig.addProxy(proxyType, proxyProvider) @@ -195,7 +211,7 @@ object WireguardManager : KoinComponent { return } - fun canEnableConfig(map: WgConfigFiles): Boolean { + fun canEnableConfig(map: WgConfigFilesImmutable): Boolean { val canEnable = appConfig.canEnableProxy() && appConfig.canEnableWireguardProxy() if (!canEnable) { return false @@ -212,7 +228,7 @@ object WireguardManager : KoinComponent { return true } - fun canDisableConfig(map: WgConfigFiles): Boolean { + fun canDisableConfig(map: WgConfigFilesImmutable): Boolean { // do not allow to disable the proxy if it is catch-all return !map.isCatchAll } @@ -243,9 +259,9 @@ object WireguardManager : KoinComponent { } } - fun disableConfig(unmapped: WgConfigFiles) { - val map = mappings.find { it.id == unmapped.id } - if (map == null) { + fun disableConfig(unmapped: WgConfigFilesImmutable) { + val m = mappings.find { it.id == unmapped.id } + if (m == null) { Log.e( LOG_TAG_PROXY, "disableConfig: wg not found, id: ${unmapped.id}, ${mappings.size}" @@ -253,26 +269,39 @@ object WireguardManager : KoinComponent { return } - val config = configs.find { it.getId() == map.id } + val config = configs.find { it.getId() == unmapped.id } // no need to enable config if it is sec warp if (config == null || config.getId() == SEC_WARP_ID) { - Log.w(LOG_TAG_PROXY, "Config not found or is SEC_WARP: ${map.id}") + Log.w(LOG_TAG_PROXY, "Config not found or is SEC_WARP: ${unmapped.id}") return } // disable the config, update to db, cache and tunnel // also update mappings https://pl.kotl.in/g0mVapn4x - map.isActive = false // confirms with db.disableConfig query - map.oneWireGuard = false // confirms with db.disableConfig query - io { db.disableConfig(map.id) } + mappings.remove(m) + val newMap = + WgConfigFilesImmutable( + m.id, + m.name, + m.configPath, + m.serverResponse, + false, // confirms with db.disableConfig query + m.isCatchAll, + m.isLockdown, + false, // confirms with db.disableConfig query + m.isDeletable + ) + mappings.add(newMap) + + io { db.disableConfig(newMap.id) } if (mappings.none { it.isActive }) { val proxyType = AppConfig.ProxyType.WIREGUARD val proxyProvider = AppConfig.ProxyProvider.WIREGUARD appConfig.removeProxy(proxyType, proxyProvider) } // directly remove the proxy from the tunnel, instead of calling updateTun - VpnController.removeWireGuardProxy(map.id) - Log.i(LOG_TAG_PROXY, "disable wg config: ${map.id}, ${map.name}") + VpnController.removeWireGuardProxy(newMap.id) + Log.i(LOG_TAG_PROXY, "disable wg config: ${newMap.id}, ${newMap.name}") return } @@ -299,9 +328,14 @@ object WireguardManager : KoinComponent { configs .find { it.getId() == WARP_ID || it.getId() == SEC_WARP_ID } ?.let { configs.remove(it) } - config.setId(id) - if (id == WARP_ID) config.setName(WARP_NAME) else config.setName(SEC_WARP_NAME) - configs.add(config) + val c = + Config.Builder() + .setId(id) + .setName(if (id == WARP_ID) WARP_NAME else SEC_WARP_NAME) + .setInterface(config.getInterface()) + .addPeers(config.getPeers()) + .build() + configs.add(c) writeConfigAndUpdateDb(config, jsonObject.toString()) } @@ -364,7 +398,7 @@ object WireguardManager : KoinComponent { } } - fun getConfigIdForApp(uid: Int): WgConfigFiles? { + fun getConfigIdForApp(uid: Int): WgConfigFilesImmutable? { val configId = ProxyManager.getProxyIdForApp(uid) if (configId == "" || !configId.contains(ProxyManager.ID_WG_BASE)) { if (DEBUG) Log.d(LOG_TAG_PROXY, "app config mapping not found for uid: $uid") @@ -433,9 +467,14 @@ object WireguardManager : KoinComponent { lastAddedConfigId += 1 val id = lastAddedConfigId val name = config.getName().ifEmpty { "${Backend.WG}$id" } - config.setName(name) - config.setId(id) - writeConfigAndUpdateDb(config) + val cfg = + Config.Builder() + .setId(id) + .setName(name) + .setInterface(config.getInterface()) + .addPeers(config.getPeers()) + .build() + writeConfigAndUpdateDb(cfg) if (DEBUG) Log.d(LOG_TAG_PROXY, "add config: ${config.getId()}, ${config.getName()}") return config } @@ -530,7 +569,7 @@ object WireguardManager : KoinComponent { // delete the config from the database db.deleteConfig(id) val proxyId = ProxyManager.ID_WG_BASE + id - ProxyManager.removeProxyForAllApps(proxyId) + ProxyManager.removeProxyId(proxyId) mappings.remove(mappings.find { it.id == id }) configs.remove(config) } @@ -543,9 +582,23 @@ object WireguardManager : KoinComponent { Log.e(LOG_TAG_PROXY, "updateLockdownConfig: wg not found, id: $id, ${configs.size}") return } - Log.i(LOG_TAG_PROXY, "updating lockdown for config: $id, ${config.getName()}") + Log.i(LOG_TAG_PROXY, "updating lockdown for config: $id, ${config.getPeers()}") db.updateLockdownConfig(id, isLockdown) - map?.isLockdown = isLockdown + val m = mappings.find { it.id == id } ?: return + mappings.remove(m) + mappings.add( + WgConfigFilesImmutable( + id, + config.getName(), + m.configPath, + m.serverResponse, + m.isActive, + m.isCatchAll, + isLockdown, // just updating lockdown field + m.oneWireGuard, + m.isDeletable + ) + ) if (map?.isActive == true) { VpnController.addWireGuardProxy(id = ProxyManager.ID_WG_BASE + config.getId()) } @@ -559,22 +612,48 @@ object WireguardManager : KoinComponent { } Log.i(LOG_TAG_PROXY, "updating catch all for config: $id, ${config.getName()}") db.updateCatchAllConfig(id, isEnabled) - val map = mappings.find { it.id == id } ?: return - map.isCatchAll = isEnabled // confirms with db.updateCatchAllConfig query - map.oneWireGuard = false // confirms with db.updateCatchAllConfig query - enableConfig(map) // catch all should be always enabled + val m = mappings.find { it.id == id } ?: return + mappings.remove(m) + val newMap = + WgConfigFilesImmutable( + id, + config.getName(), + m.configPath, + m.serverResponse, + m.isActive, + isEnabled, // just updating catch all field + m.isLockdown, + m.oneWireGuard, + m.isDeletable + ) + mappings.add(newMap) + + enableConfig(newMap) // catch all should be always enabled } suspend fun updateOneWireGuardConfig(id: Int, owg: Boolean) { val config = configs.find { it.getId() == id } - val map = mappings.find { it.id == id } if (config == null) { Log.e(LOG_TAG_PROXY, "update one wg: id($id) not found, size: ${configs.size}") return } Log.i(LOG_TAG_PROXY, "update one wg, id: $id, ${config.getName()} to $owg") db.updateOneWireGuardConfig(id, owg) - map?.oneWireGuard = owg + val m = mappings.find { it.id == id } ?: return + mappings.remove(m) + mappings.add( + WgConfigFilesImmutable( + id, + config.getName(), + m.configPath, + m.serverResponse, + m.isActive, + m.isCatchAll, + m.isLockdown, + owg, // updating just one wireguard field + m.isDeletable + ) + ) } suspend fun addPeer(id: Int, peer: Peer) { @@ -666,7 +745,7 @@ object WireguardManager : KoinComponent { file.serverResponse = serverResponse db.update(file) } - addOrUpdateConfigFileMapping(cfg, file, path, serverResponse) + addOrUpdateConfigFileMapping(cfg, file?.toImmutable(), path, serverResponse) addOrUpdateConfig(cfg) if (file?.isActive == true) { VpnController.addWireGuardProxy(id = ProxyManager.ID_WG_BASE + cfg.getId()) @@ -685,13 +764,13 @@ object WireguardManager : KoinComponent { private fun addOrUpdateConfigFileMapping( cfg: Config, - file: WgConfigFiles?, + file: WgConfigFilesImmutable?, path: String, serverResponse: String ) { if (file == null) { val wgf = - WgConfigFiles( + WgConfigFilesImmutable( cfg.getId(), cfg.getName(), path, @@ -699,7 +778,8 @@ object WireguardManager : KoinComponent { isActive = false, isCatchAll = false, isLockdown = false, - oneWireGuard = false + oneWireGuard = false, + isDeletable = true ) mappings.add(wgf) } else { @@ -748,61 +828,6 @@ object WireguardManager : KoinComponent { return mappings.find { it.isCatchAll && it.isActive }?.id } - fun canRouteIp(configId: Int?, ip: String?): Boolean { - val destAddr = IPAddressString(ip) - - if (destAddr.isZero()) { - Log.w(LOG_TAG_PROXY, "canRouteIp: unsupported wildcard ip: $ip") - return false - } - - if (configId == null || ip == null) { - Log.e(LOG_TAG_PROXY, "canRouteIp: configId or ip is null") - return false - } - - val config = configs.find { it.getId() == configId } - if (config == null) { - Log.e(LOG_TAG_PROXY, "canRouteIp: wg not found, id: $configId, ${configs.size}") - return false - } - // if no allowed ips are present, then allow all (case: no peers added) - val allowedIps = config.getPeers()?.map { it.getAllowedIps() }?.flatten() ?: return true - if (DEBUG) Log.d(LOG_TAG_PROXY, "canRouteIp: $allowedIps, dest: $destAddr") - - allowedIps.forEach { - val addr = IPAddressString(it.toString()) - if (DEBUG) - Log.d( - LOG_TAG_PROXY, - "canRouteIp: a: $addr, d: $destAddr, c:${addr.contains(destAddr)}" - ) - // if the destination ip is present in the allowed ip, then allow - if (addr.contains(destAddr)) { - return true - } - } - return false - } - - fun getActiveConfigTimestamp(configId: Int): Long? { - return activeConfigTimestamps[configId] - } - - fun setActiveConfigTimestamp(configId: String, timestamp: Long) { - val id = convertStringIdToId(configId) - activeConfigTimestamps[id] = timestamp - } - - fun removeActiveConfigTimestamp(configId: String) { - val id = convertStringIdToId(configId) - activeConfigTimestamps.remove(id) - } - - fun clearActiveConfigTimestamps() { - activeConfigTimestamps.clear() - } - private fun io(f: suspend () -> Unit) { CoroutineScope(Dispatchers.IO).launch { f() } } diff --git a/app/src/main/java/com/celzero/bravedns/data/AppConfig.kt b/app/src/main/java/com/celzero/bravedns/data/AppConfig.kt index 2c2ca5fe4..e440977ec 100644 --- a/app/src/main/java/com/celzero/bravedns/data/AppConfig.kt +++ b/app/src/main/java/com/celzero/bravedns/data/AppConfig.kt @@ -712,6 +712,9 @@ internal constructor( suspend fun handleDnsrelayChanges(endpoint: DnsCryptRelayEndpoint) { dnsCryptRelayEndpointRepository.update(endpoint) + persistentState.dnsCryptRelays.postValue( + PersistentState.DnsCryptRelayDetails(endpoint, endpoint.isSelected) + ) } suspend fun removeDnscryptRelay(stamp: String) { diff --git a/app/src/main/java/com/celzero/bravedns/data/ConnTrackerMetaData.kt b/app/src/main/java/com/celzero/bravedns/data/ConnTrackerMetaData.kt index f245c3cd3..67ddc3ac5 100644 --- a/app/src/main/java/com/celzero/bravedns/data/ConnTrackerMetaData.kt +++ b/app/src/main/java/com/celzero/bravedns/data/ConnTrackerMetaData.kt @@ -17,6 +17,7 @@ package com.celzero.bravedns.data import java.io.Serializable +// do not use it as key in the map or set, as it is mutable data class ConnTrackerMetaData( val uid: Int, val usrId: Int, diff --git a/app/src/main/java/com/celzero/bravedns/data/ConnectionSummary.kt b/app/src/main/java/com/celzero/bravedns/data/ConnectionSummary.kt index 3efd9018a..42fa01338 100644 --- a/app/src/main/java/com/celzero/bravedns/data/ConnectionSummary.kt +++ b/app/src/main/java/com/celzero/bravedns/data/ConnectionSummary.kt @@ -17,6 +17,7 @@ package com.celzero.bravedns.data import java.io.Serializable +// do not use as key in map or set, as some fields are mutable data class ConnectionSummary( val uid: String, val pid: String, diff --git a/app/src/main/java/com/celzero/bravedns/data/FileTag.kt b/app/src/main/java/com/celzero/bravedns/data/FileTag.kt index e4ee0c3f9..f97758a07 100644 --- a/app/src/main/java/com/celzero/bravedns/data/FileTag.kt +++ b/app/src/main/java/com/celzero/bravedns/data/FileTag.kt @@ -52,6 +52,7 @@ import java.lang.reflect.Type "discards":0*/ // data class to handle filetags for both local and remote blocklist (filetag.json) +// do not use as key in map or set, as some fields are mutable data class FileTag( val value: Int, val uname: String, diff --git a/app/src/main/java/com/celzero/bravedns/database/ProxyAppMappingRepository.kt b/app/src/main/java/com/celzero/bravedns/database/ProxyAppMappingRepository.kt index 2ad34f6fa..6ac540d57 100644 --- a/app/src/main/java/com/celzero/bravedns/database/ProxyAppMappingRepository.kt +++ b/app/src/main/java/com/celzero/bravedns/database/ProxyAppMappingRepository.kt @@ -19,20 +19,20 @@ class ProxyAppMappingRepository( private val proxyApplicationMappingDAO: ProxyApplicationMappingDAO ) { - suspend fun update(wgMapping: ProxyApplicationMapping) { - proxyApplicationMappingDAO.update(wgMapping) + suspend fun update(pam: ProxyApplicationMapping) { + proxyApplicationMappingDAO.update(pam) } - suspend fun insert(wgMapping: ProxyApplicationMapping): Long { - return proxyApplicationMappingDAO.insert(wgMapping) + suspend fun insert(pam: ProxyApplicationMapping): Long { + return proxyApplicationMappingDAO.insert(pam) } - suspend fun insertAll(wgMapping: List): LongArray { - return proxyApplicationMappingDAO.insertAll(wgMapping) + suspend fun insertAll(pams: List): LongArray { + return proxyApplicationMappingDAO.insertAll(pams) } - suspend fun delete(wgMapping: ProxyApplicationMapping) { - proxyApplicationMappingDAO.deleteByPackageName(wgMapping.uid, wgMapping.packageName) + suspend fun deleteApp(pam: ProxyApplicationMapping) { + proxyApplicationMappingDAO.deleteApp(pam.uid, pam.packageName) } suspend fun deleteAll() { diff --git a/app/src/main/java/com/celzero/bravedns/database/ProxyApplicationMappingDAO.kt b/app/src/main/java/com/celzero/bravedns/database/ProxyApplicationMappingDAO.kt index cba41cc96..245da1928 100644 --- a/app/src/main/java/com/celzero/bravedns/database/ProxyApplicationMappingDAO.kt +++ b/app/src/main/java/com/celzero/bravedns/database/ProxyApplicationMappingDAO.kt @@ -38,7 +38,7 @@ interface ProxyApplicationMappingDAO { @Delete fun delete(wgMapping: ProxyApplicationMapping) @Query("delete from ProxyApplicationMapping where uid = :uid and packageName = :packageName") - fun deleteByPackageName(uid: Int, packageName: String) + fun deleteApp(uid: Int, packageName: String) @Query("delete from ProxyApplicationMapping") fun deleteAll() diff --git a/app/src/main/java/com/celzero/bravedns/database/RefreshDatabase.kt b/app/src/main/java/com/celzero/bravedns/database/RefreshDatabase.kt index 5370132fe..7b46308fd 100644 --- a/app/src/main/java/com/celzero/bravedns/database/RefreshDatabase.kt +++ b/app/src/main/java/com/celzero/bravedns/database/RefreshDatabase.kt @@ -383,8 +383,8 @@ internal constructor( trackedApps: Set, emptyAll: Boolean ) { - // trackedApps is empty, the installed apps are yet to be added to the database - // so no need to refresh the proxy mapping when the tracked apps are empty + // trackedApps is empty, the installed apps are yet to be added to the database; and so, + // there's no need to refresh these mappings as apps tracked by FirewallManager is empty if (trackedApps.isEmpty()) { Log.i(LOG_TAG_APP_DB, "refreshProxyMapping: trackedApps is empty") return @@ -402,12 +402,12 @@ internal constructor( ProxyManager.purgeDupsBeforeRefresh() // remove the apps from proxy mapping which are not tracked by app info repository - val pxm = ProxyManager.getProxyMapping() + val pxm = ProxyManager.trackedApps() val del = findPackagesToDelete(pxm, trackedApps) val add = findPackagesToAdd(pxm, trackedApps).map { FirewallManager.getAppInfoByUid(it.uid) } - ProxyManager.deleteMappings(del) - ProxyManager.addMappings(add) + ProxyManager.deleteApps(del) + ProxyManager.addApps(add) Log.i( "AppDatabase", "refreshing proxy mapping, size: ${pxm.size}, trackedApps: ${trackedApps.size}" @@ -553,11 +553,12 @@ internal constructor( // no need to notify if the vpn is not on if (!VpnController.isOn()) return - if (app.packageName.isEmpty()) { - app.packageName = FirewallManager.getPackageNameByUid(app.uid) ?: "" + var pkgName = app.packageName + if (pkgName.isEmpty()) { + pkgName = FirewallManager.getPackageNameByUid(app.uid) ?: "" } - val appInfo = Utilities.getApplicationInfo(ctx, app.packageName) + val appInfo = Utilities.getApplicationInfo(ctx, pkgName) val appName = if (appInfo == null) { app.uid diff --git a/app/src/main/java/com/celzero/bravedns/database/WgConfigFiles.kt b/app/src/main/java/com/celzero/bravedns/database/WgConfigFiles.kt index 6ef41a2eb..507de02fa 100644 --- a/app/src/main/java/com/celzero/bravedns/database/WgConfigFiles.kt +++ b/app/src/main/java/com/celzero/bravedns/database/WgConfigFiles.kt @@ -19,6 +19,18 @@ import androidx.room.Entity import androidx.room.Ignore import androidx.room.PrimaryKey +data class WgConfigFilesImmutable( + val id: Int, + val name: String, + val configPath: String, + val serverResponse: String, + val isActive: Boolean, + val isCatchAll: Boolean, + val isLockdown: Boolean, + val oneWireGuard: Boolean, + val isDeletable: Boolean +) + @Entity(tableName = "WgConfigFiles") class WgConfigFiles { @PrimaryKey(autoGenerate = true) var id: Int = 0 @@ -69,7 +81,8 @@ class WgConfigFiles { isActive: Boolean, isCatchAll: Boolean, isLockdown: Boolean, - oneWireGuard: Boolean + oneWireGuard: Boolean, + isDeletable: Boolean ) { this.name = name this.configPath = configPath @@ -78,5 +91,35 @@ class WgConfigFiles { this.isCatchAll = isCatchAll this.isLockdown = isLockdown this.oneWireGuard = oneWireGuard + this.isDeletable = isDeletable + } + + fun toImmutable(): WgConfigFilesImmutable { + return WgConfigFilesImmutable( + id, + name, + configPath, + serverResponse, + isActive, + isCatchAll, + isLockdown, + oneWireGuard, + isDeletable + ) + } + + companion object { + fun fromImmutable(data: WgConfigFilesImmutable): WgConfigFiles { + return WgConfigFiles( + data.id, + data.name, + data.configPath, + data.serverResponse, + data.isActive, + data.isCatchAll, + data.isLockdown, + data.oneWireGuard + ) + } } } diff --git a/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt b/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt index d266ac6d6..62d492a11 100644 --- a/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt +++ b/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt @@ -27,6 +27,7 @@ import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.data.AppConfig import com.celzero.bravedns.data.AppConfig.Companion.FALLBACK_DNS import com.celzero.bravedns.data.AppConfig.TunnelOptions +import com.celzero.bravedns.database.DnsCryptRelayEndpoint import com.celzero.bravedns.database.ProxyEndpoint import com.celzero.bravedns.service.BraveVPNService import com.celzero.bravedns.service.PersistentState @@ -40,6 +41,7 @@ import com.celzero.bravedns.util.Constants.Companion.MAX_ENDPOINT import com.celzero.bravedns.util.Constants.Companion.ONDEVICE_BLOCKLIST_FILE_TAG import com.celzero.bravedns.util.Constants.Companion.REMOTE_BLOCKLIST_DOWNLOAD_FOLDER_NAME import com.celzero.bravedns.util.Constants.Companion.RETHINKDNS_DOMAIN +import com.celzero.bravedns.util.Constants.Companion.RETHINK_BASE_URL_MAX import com.celzero.bravedns.util.Constants.Companion.RETHINK_BASE_URL_SKY import com.celzero.bravedns.util.Constants.Companion.UNSPECIFIED_IP_IPV4 import com.celzero.bravedns.util.Constants.Companion.UNSPECIFIED_IP_IPV6 @@ -275,6 +277,7 @@ class GoVpnAdapter : KoinComponent { } catch (e: Exception) { Log.e(LOG_TAG_VPN, "connect-tunnel: dns crypt failure for $id", e) getResolver()?.remove(id) + removeDnscryptRelaysIfAny() showDnscryptConnectionFailureToast() } } @@ -298,9 +301,10 @@ class GoVpnAdapter : KoinComponent { private suspend fun addRdnsTransport(id: String, url: String) { try { + val useDot = false val ips: String = getIpString(context, url) val convertedUrl = getRdnsUrl(url) ?: return - if (url.contains(RETHINK_BASE_URL_SKY)) { + if (url.contains(RETHINK_BASE_URL_SKY) || !useDot) { Intra.addDoHTransport(tunnel, id, convertedUrl, ips) Log.i(LOG_TAG_VPN, "new doh (rdns): $id, url: $convertedUrl, ips: $ips") } else { @@ -314,7 +318,7 @@ class GoVpnAdapter : KoinComponent { } } - private fun getRdnsUrl(url: String): String? { + private fun getRdnsUrl(url: String, useDot: Boolean = false): String? { val tls = "tls://" val default = "dns-query" // do not proceed if rethinkdns.com is not available @@ -324,22 +328,26 @@ class GoVpnAdapter : KoinComponent { // if url is SKY, convert it to doh format, DOH format https://sky.rethikdns.com/stamp // for blockfree, the url is https://max.rethinkdns.com/dns-query - if (url == Constants.BLOCK_FREE_DNS_MAX) { + if (url == Constants.BLOCK_FREE_DNS_MAX && useDot) { return "$tls$MAX_ENDPOINT.$RETHINKDNS_DOMAIN" - } else if (url == Constants.BLOCK_FREE_DNS_SKY) { + } else if (url == Constants.BLOCK_FREE_DNS_SKY || url == Constants.BLOCK_FREE_DNS_MAX) { return url } else { // no-op, pass-through } val stamp = getRdnsStamp(url) - return if (url.contains(MAX_ENDPOINT)) { + return if (url.contains(MAX_ENDPOINT) && useDot) { // if the stamp is empty or "dns-query", then remove it if (stamp.isEmpty() || stamp == default) { return "$tls$MAX_ENDPOINT.$RETHINKDNS_DOMAIN" } "$tls$stamp.$MAX_ENDPOINT.$RETHINKDNS_DOMAIN" } else { - "$RETHINK_BASE_URL_SKY$stamp" + if (url.contains(MAX_ENDPOINT)) { + return "$RETHINK_BASE_URL_MAX$stamp" + } else { + return "$RETHINK_BASE_URL_SKY$stamp" + } } } @@ -451,6 +459,51 @@ class GoVpnAdapter : KoinComponent { } } + private suspend fun removeDnscryptRelaysIfAny() { + val routes: String = appConfig.getDnscryptRelayServers() + routes.split(",").forEach { + if (it.isBlank()) return@forEach + + Log.i(LOG_TAG_VPN, "remove dnscrypt relay: $it") + try { + // remove from appConfig, as this is not from ui, but from the tunnel start up + appConfig.removeDnscryptRelay(it) + getResolver()?.remove(it) + } catch (ex: Exception) { + Log.e(LOG_TAG_VPN, "connect-tunnel: dnscrypt rmv failure", ex) + } + } + } + + suspend fun addDnscryptRelay(relay: DnsCryptRelayEndpoint) { + if (!tunnel.isConnected) { + Log.i(LOG_TAG_VPN, "Tunnel NOT connected, skip add dnscrypt relay") + return + } + try { + Intra.addDNSCryptRelay(tunnel, relay.dnsCryptRelayURL) + Log.i(LOG_TAG_VPN, "new dnscrypt relay: ${relay.dnsCryptRelayURL}") + } catch (e: Exception) { + Log.e(LOG_TAG_VPN, "connect-tunnel: dnscrypt add failure", e) + appConfig.removeDnscryptRelay(relay.dnsCryptRelayURL) + getResolver()?.remove(relay.dnsCryptRelayURL) + } + } + + suspend fun removeDnscryptRelay(relay: DnsCryptRelayEndpoint) { + if (!tunnel.isConnected) { + Log.i(LOG_TAG_VPN, "Tunnel NOT connected, skip remove dnscrypt relay") + return + } + try { + // no need to remove from appConfig, as it is already removed + getResolver()?.remove(relay.dnsCryptRelayURL) + Log.i(LOG_TAG_VPN, "remove dnscrypt relay: ${relay.dnsCryptRelayURL}") + } catch (e: Exception) { + Log.e(LOG_TAG_VPN, "connect-tunnel: dnscrypt rmv failure", e) + } + } + /** * TODO - Move these code to common place and set the tunnel mode and other parameters. Return * the tunnel to the adapter. @@ -713,6 +766,30 @@ class GoVpnAdapter : KoinComponent { } } + fun refreshProxy(id: String) { + if (!tunnel.isConnected) { + Log.i(LOG_TAG_VPN, "Tunnel NOT connected, skip refreshing proxy") + return + } + try { + val res = getProxies()?.getProxy(id)?.refresh() + Log.i(LOG_TAG_VPN, "refresh proxy($id): $res") + } catch (e: Exception) { + Log.e(LOG_TAG_VPN, "error refreshing proxy($id): ${e.message}", e) + } + } + + fun getProxyStats(id: String): backend.Stats? { + return try { + val stats = getProxies()?.getProxy(id)?.router()?.stat() + Log.i(LOG_TAG_VPN, "proxy stats($id): $stats") + stats + } catch (e: Exception) { + Log.e(LOG_TAG_VPN, "error getting proxy stats($id): ${e.message}", e) + null + } + } + fun getDnsStatus(id: String): Long? { try { val transport = getResolver()?.get(id) diff --git a/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt b/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt index 1bfbe9c15..56f85ec7f 100644 --- a/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt +++ b/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt @@ -33,6 +33,7 @@ import android.content.pm.PackageManager import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED import android.net.ConnectivityManager +import android.net.Network import android.net.NetworkCapabilities import android.net.VpnService import android.os.Build.VERSION @@ -53,6 +54,7 @@ import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import backend.Backend import backend.RDNS +import backend.Stats import com.celzero.bravedns.R import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.data.AppConfig @@ -96,18 +98,6 @@ import inet.ipaddr.HostName import inet.ipaddr.IPAddressString import intra.Bridge import intra.SocketSummary -import kotlinx.coroutines.CoroutineName -import kotlinx.coroutines.Deferred -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.MainScope -import kotlinx.coroutines.async -import kotlinx.coroutines.cancel -import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withContext -import org.koin.android.ext.android.inject -import rnet.ServerSummary -import rnet.Tab import java.io.IOException import java.net.InetAddress import java.net.SocketException @@ -120,6 +110,18 @@ import java.util.concurrent.atomic.AtomicBoolean import kotlin.math.abs import kotlin.math.min import kotlin.random.Random +import kotlinx.coroutines.CoroutineName +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.MainScope +import kotlinx.coroutines.async +import kotlinx.coroutines.cancel +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withContext +import org.koin.android.ext.android.inject +import rnet.ServerSummary +import rnet.Tab class BraveVPNService : VpnService(), ConnectionMonitor.NetworkListener, Bridge, OnSharedPreferenceChangeListener { @@ -160,6 +162,10 @@ class BraveVPNService : const val FAIL_OPEN_ON_NO_NETWORK = true } + // handshake expiry time for proxy connections + private val wgHandshakeTimeout = TimeUnit.MINUTES.toMillis(3L) + private val checkpointInterval = TimeUnit.MINUTES.toMillis(1L) + private var isLockDownPrevious: Boolean = false private val vpnScope = MainScope() @@ -185,6 +191,7 @@ class BraveVPNService : private lateinit var appInfoObserver: Observer> private lateinit var orbotStartStatusObserver: Observer + private lateinit var dnscryptRelayObserver: Observer private var rethinkUid: Int = INVALID_UID @@ -192,10 +199,13 @@ class BraveVPNService : // as active connections. removed when the connection is closed (onSummary) private var trackedCids = Collections.newSetFromMap(ConcurrentHashMap()) + // store proxyids and their handshake times, refresh proxy when handshake time is expired + private val wgHandShakeCheckpoints: ConcurrentHashMap = ConcurrentHashMap() + // data class to store the connection summary data class CidKey(val cid: String, val uid: Int) - private var excludedApps: MutableSet = mutableSetOf() + private var excludedApps: MutableSet = ConcurrentHashMap.newKeySet() // post underlying networks as live data @Volatile var underlyingNetworks: ConnectionMonitor.UnderlyingNetworks? = null @@ -231,91 +241,35 @@ class BraveVPNService : } override fun bind4(who: String, addrPort: String, fid: Long) { - val rinr = persistentState.routeRethinkInRethink - val curnet = underlyingNetworks - logd("bind4: $who, $fid, rinr? $rinr") - if (rinr && who != Backend.Exit) { - // do not proceed if rethink within rethink is enabled and proxyId(who) is not exit - return - } - - this.protect(fid.toInt()) - // binding to the underlying network is not working. - // no need to bind if use active network is true - if (curnet?.useActive == true) { - logd("bind4: use active network is true") - return - } - - var pfd: ParcelFileDescriptor? = null - try { - // split the addrPort to get the IP address and convert it to InetAddress - val dest = IpRulesManager.splitHostPort(addrPort) - val destIp = IPAddressString(dest.first).address - val destPort = dest.second.toIntOrNull() - // in case of zero, bind only for wg connections, wireguard tries to bind to - // network with zero addresses - if ( - (destIp.isZero && who.startsWith(ProxyManager.ID_WG_BASE)) || - destIp.isAnyLocal || - destIp.isLoopback - ) { - logd("bind4: invalid destIp: $destIp, who: $who, $addrPort") - return - } - val destAddr = destIp.toInetAddress() - pfd = ParcelFileDescriptor.adoptFd(fid.toInt()) - // check if the destination port is DNS port, if so bind to the network where the dns - // belongs to, else bind to the available network - val net = if (KnownPorts.isDns(destPort)) curnet?.dnsServers?.get(destAddr) else null - if (net != null) { - try { - logd("bind4: $who, $addrPort, $fid, ${net.networkHandle}") - net.bindSocket(pfd!!.fileDescriptor) - return - } catch (e: IOException) { - Log.e(LOG_TAG_VPN, "err bind4 for fid: $fid, ${e.message}, $e") - } - } else { - curnet?.ipv4Net?.forEach { - try { - it.network.bindSocket(pfd!!.fileDescriptor) - logd( - "bind4: $who, $addrPort, ${it.network.networkHandle}, ${it.networkType}" - ) - return - } catch (e: IOException) { - Log.e(LOG_TAG_VPN, "err bind4 for fid: $fid, ${e.message}, $e") - } - } - } - } finally { - pfd?.detachFd() - } - - logd("bind4: no network to bind, ${curnet?.dnsServers?.keys}, who: $who, $addrPort") + return bindAny(who, addrPort, fid, underlyingNetworks?.ipv4Net ?: emptyList()) } override fun bind6(who: String, addrPort: String, fid: Long) { + return bindAny(who, addrPort, fid, underlyingNetworks?.ipv6Net ?: emptyList()) + } + + private fun bindAny( + who: String, + addrPort: String, + fid: Long, + nws: List + ) { val rinr = persistentState.routeRethinkInRethink val curnet = underlyingNetworks - logd("bind6: $who, $fid, rinr? $rinr") + + logd("bind: $who, $fid, rinr? $rinr") if (rinr && who != Backend.Exit) { // do not proceed if rethink within rethink is enabled and proxyId(who) is not exit return } this.protect(fid.toInt()) - // who is not used, but kept for future use - // binding to the underlying network is not working. - // no need to bind if use active network is true - if (curnet?.useActive == true) { - logd("bind6: use active network is true") - return - } var pfd: ParcelFileDescriptor? = null try { + + pfd = ParcelFileDescriptor.adoptFd(fid.toInt()) + // split the addrPort to get the IP address and convert it to InetAddress val dest = IpRulesManager.splitHostPort(addrPort) val destIp = IPAddressString(dest.first).address @@ -329,37 +283,47 @@ class BraveVPNService : destIp.isAnyLocal || destIp.isLoopback ) { - logd("bind6: invalid destIp: $destIp, who: $who, $addrPort") + logd("bind: invalid destIp: $destIp, who: $who, $addrPort") return } - pfd = ParcelFileDescriptor.adoptFd(fid.toInt()) // check if the destination port is DNS port, if so bind to the network where the dns // belongs to, else bind to the available network val net = if (KnownPorts.isDns(destPort)) curnet?.dnsServers?.get(destAddr) else null if (net != null) { - try { - logd("bind6: $who, $addrPort, $fid, ${net.networkHandle}") - net.bindSocket(pfd!!.fileDescriptor) + bindToNw(net, pfd) + logd("bind: dns: $who, $addrPort, $fid, ${net.networkHandle}") + return + } + + // who is not used, but kept for future use + // binding to the underlying network is not working. + // no need to bind if use active network is true + if (curnet?.useActive == true) { + logd("bind: use active network is true") + return + } + + nws.forEach { + if (bindToNw(it.network, pfd)) { + logd("bind: $who, $addrPort, $fid, ${it.network.networkHandle}") return - } catch (e: IOException) { - Log.e(LOG_TAG_VPN, "err bind6 for fid: $fid, ${e.message}, $e") - } - } else { - curnet?.ipv6Net?.forEach { - try { - it.network.bindSocket(pfd!!.fileDescriptor) - logd("bind6: $who, ${it.network.networkHandle}, ${it.networkType}") - return - } catch (e: IOException) { - Log.e(LOG_TAG_VPN, "err bind6 for fid: $fid, ${e.message}, $e") - } } } } finally { pfd?.detachFd() } - logd("bind6: no network to bind, ${curnet?.dnsServers?.keys}, who: $who, $addrPort") + logd("bind: no network to bind, ${curnet?.dnsServers?.keys}, who: $who, $addrPort") + } + + private fun bindToNw(net: Network, pfd: ParcelFileDescriptor): Boolean { + return try { + net.bindSocket(pfd.fileDescriptor) + true + } catch (e: IOException) { + Log.e(LOG_TAG_VPN, "err bindToNw, ${e.message}, $e") + false + } } override fun protect(who: String?, fd: Long) { @@ -391,7 +355,8 @@ class BraveVPNService : /** Checks if incoming connection is blocked by any user-set firewall rule */ private suspend fun firewall( connInfo: ConnTrackerMetaData, - anyRealIpBlocked: Boolean = false + anyRealIpBlocked: Boolean = false, + isSplApp: Boolean ): FirewallRuleset { try { logd("firewall: $connInfo") @@ -537,6 +502,14 @@ class BraveVPNService : // no-op; pass-through } + // apps which are used to forward dns proxy, socks5 or https proxy are handled as spl + // no need to handle universal rules for these apps + if (isSplApp) { + logd("firewall: special app, $uid, ${connInfo.query}") + // placeholder rule (RULE0) for special app rules + return FirewallRuleset.RULE0 + } + val isMetered = isConnectionMetered(connInfo.destIP) // block all metered connections (Universal firewall setting) if (persistentState.getBlockMeteredConnections() && isMetered) { @@ -1087,7 +1060,7 @@ class BraveVPNService : connTracer = ConnectionTracer(this) VpnController.onVpnCreated(this) - io("loggers") { netLogTracker.startLogger(vpnScope) } + io("loggers") { netLogTracker.restart(vpnScope) } notificationManager = this.getSystemService(NOTIFICATION_SERVICE) as NotificationManager activityManager = this.getSystemService(ACTIVITY_SERVICE) as ActivityManager @@ -1107,7 +1080,21 @@ class BraveVPNService : persistentState.sharedPreferences.registerOnSharedPreferenceChangeListener(this) orbotStartStatusObserver = makeOrbotStartStatusObserver() persistentState.orbotConnectionStatus.observeForever(orbotStartStatusObserver) - Log.i(LOG_TAG_VPN, "observe pref and app list changes") + dnscryptRelayObserver = makeDnscryptRelayObserver() + persistentState.dnsCryptRelays.observeForever(dnscryptRelayObserver) + Log.i(LOG_TAG_VPN, "observe pref, dnscrypt relay, app list changes") + } + + private fun makeDnscryptRelayObserver(): Observer { + return Observer { t -> + io("dnscryptRelay") { + if (t.added) { + vpnAdapter?.addDnscryptRelay(t.relay) + } else { + vpnAdapter?.removeDnscryptRelay(t.relay) + } + } + } } private fun makeAppInfoObserver(): Observer> { @@ -1446,6 +1433,12 @@ class BraveVPNService : } } + private fun unobserveDnsRelay() { + if (this::dnscryptRelayObserver.isInitialized) { + persistentState.dnsCryptRelays.removeObserver(dnscryptRelayObserver) + } + } + private fun registerAccessibilityServiceState() { accessibilityListener = AccessibilityManager.AccessibilityStateChangeListener { b -> @@ -1566,10 +1559,6 @@ class BraveVPNService : PersistentState.PREVENT_DNS_LEAKS -> { io("preventDnsLeaks") { setTunMode() } } - PersistentState.DNS_RELAYS -> { - // FIXME: add relay using vpnAdapter; no update needed - io("updateDnscrypt") { addTransport() } - } PersistentState.ALLOW_BYPASS -> { io("allowBypass") { restartVpnWithNewAppConfig(reason = "allowBypass") } } @@ -2203,6 +2192,7 @@ class BraveVPNService : unobserveOrbotStartStatus() unobserveAppInfos() + unobserveDnsRelay() persistentState.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) // onVpnStart is also called from the main thread (ui) @@ -2673,7 +2663,7 @@ class BraveVPNService : } // function to decide which transport id to return on Dns only mode - private fun getTransportIdForDnsMode(fqdn: String): backend.DNSOpts { + private suspend fun getTransportIdForDnsMode(fqdn: String): backend.DNSOpts { val tid = determineDnsTransportId() // check for global domain rules @@ -2726,12 +2716,14 @@ class BraveVPNService : } } - private fun makeNsOpts(tid: String, bypassLocalBlocklists: Boolean = false): backend.DNSOpts { - val pid = proxyIdForOnQuery() + private suspend fun makeNsOpts( + tid: String, + bypassLocalBlocklists: Boolean = false + ): backend.DNSOpts { val opts = backend.DNSOpts() opts.ipcsv = "" // as of now, no suggested ips opts.tidcsv = appendDnsCacheIfNeeded(tid) - opts.pid = pid + opts.pid = proxyIdForOnQuery() opts.noblock = bypassLocalBlocklists return opts } @@ -2767,12 +2759,24 @@ class BraveVPNService : return persistentState.enableDnsCache && userPreferredId != Backend.BlockAll } - private fun proxyIdForOnQuery(): String { + private suspend fun proxyIdForOnQuery(): String { + // proxies are used only in dns-firewall mode + if (!appConfig.getBraveMode().isDnsFirewallMode()) { + return Backend.Base + } + // user setting to disable proxy dns if (!persistentState.proxyDns) { return Backend.Base } + if (appConfig.isDnsProxyActive()) { + val endpoint = appConfig.getSelectedDnsProxyDetails() + if (!endpoint?.proxyAppName.isNullOrEmpty()) { + return Backend.Base + } + } + return if (appConfig.isCustomSocks5Enabled()) { ProxyManager.ID_S5_BASE } else if (appConfig.isCustomHttpProxyEnabled()) { @@ -2812,9 +2816,8 @@ class BraveVPNService : } override fun onProxiesStopped() { - // proxies stopped will happen only when the vpn is stopped so, no need to restart the vpn - // just clear the active config timestamps - WireguardManager.clearActiveConfigTimestamps() + // clear the proxy handshake times + wgHandShakeCheckpoints.clear() } override fun onProxyAdded(id: String) { @@ -2822,7 +2825,7 @@ class BraveVPNService : // only wireguard proxies are considered for overlay network return } - WireguardManager.setActiveConfigTimestamp(id, elapsedRealtime()) + wgHandShakeCheckpoints[id] = elapsedRealtime() // new proxy added, refresh overlay network pair val nw: OverlayNetworks? = vpnAdapter?.getActiveProxiesIpAndMtu() logd("onProxyAdded for proxy $id: $nw") @@ -2834,7 +2837,7 @@ class BraveVPNService : // only wireguard proxies are considered for overlay network return } - WireguardManager.removeActiveConfigTimestamp(id) + wgHandShakeCheckpoints.remove(id) // proxy removed, refresh overlay network pair val nw: OverlayNetworks? = vpnAdapter?.getActiveProxiesIpAndMtu() logd("onProxyRemoved for proxy $id: $nw") @@ -2925,9 +2928,8 @@ class BraveVPNService : blocklists: String ): intra.Mark = runBlocking { // runBlocking blocks the current thread until all coroutines within it are complete - // runBlocking block to ensure that we can call a suspending function from a non-suspending - // context and obtain the result. - logd("flow: $_uid, $src, $dest, $realIps, $d, $blocklists") + // an call a suspending function from a non-suspending context and obtain the result. + logd("flow: $_uid, $dup, $src, $dest, $realIps, $d, $blocklists") handleVpnLockdownStateAsync() val first = HostName(src) @@ -2961,7 +2963,7 @@ class BraveVPNService : // if `d` is blocked, then at least one of the real ips is unspecified val anyRealIpBlocked = !ips.none { isUnspecifiedIp(it.trim()) } - val connTyp = + val connType = if (isConnectionMetered(realDestIp)) { ConnectionTracker.ConnType.METERED } else { @@ -2981,11 +2983,14 @@ class BraveVPNService : blocklists, domains.firstOrNull(), connId, - connTyp + connType ) val trapVpnDns = isDns(dstPort) && isVpnDns(dstIp) val trapVpnPrivateDns = isVpnDns(dstIp) && isPrivateDns(dstPort) + // app is considered as spl when it is selected to forward dns proxy, socks5 or http proxy + val isSplApp = isSpecialApp(uid) + // always block, since the vpn tunnel doesn't serve dns-over-tls if (trapVpnPrivateDns) { logd("flow: dns-over-tls, returning Ipn.Block, $uid") @@ -3042,7 +3047,7 @@ class BraveVPNService : return@runBlocking persistAndConstructFlowResponse(null, Backend.Base, connId, uid) } - processFirewallRequest(cm, anyRealIpBlocked, blocklists) + processFirewallRequest(cm, anyRealIpBlocked, blocklists, isSplApp) if (cm.isBlocked) { // return Ipn.Block, no need to check for other rules @@ -3055,14 +3060,77 @@ class BraveVPNService : val key = CidKey(cm.connId, uid) trackedCids.add(key) - return@runBlocking determineProxyDetails(cm) + return@runBlocking determineProxyDetails(cm, isSplApp) + } + + private suspend fun isSpecialApp(uid: Int): Boolean { + if (!appConfig.getBraveMode().isDnsFirewallMode()) { + return false + } + // check if the app is selected to forward dns proxy, orbot, socks5, http proxy + if ( + !appConfig.isCustomSocks5Enabled() && + !appConfig.isCustomHttpProxyEnabled() && + !appConfig.isDnsProxyActive() && + !appConfig.isOrbotProxyEnabled() + ) { + return false + } + + if (appConfig.isOrbotProxyEnabled()) { + val endpoint = appConfig.getConnectedOrbotProxy() + val packageName = FirewallManager.getPackageNameByUid(uid) + if (endpoint?.proxyAppName == packageName) { + logd("flow: orbot enabled for $packageName, handling as spl app") + return true + } + } + + if (appConfig.isCustomSocks5Enabled()) { + val endpoint = appConfig.getSocks5ProxyDetails() + val packageName = FirewallManager.getPackageNameByUid(uid) + // do not block the app if the app is set to forward the traffic via socks5 proxy + if (endpoint.proxyAppName == packageName) { + logd("flow: socks5 enabled for $packageName, handling as spl app") + return true + } + } + + if (appConfig.isCustomHttpProxyEnabled()) { + val endpoint = appConfig.getHttpProxyDetails() + val packageName = FirewallManager.getPackageNameByUid(uid) + // do not block the app if the app is set to forward the traffic via http proxy + if (endpoint.proxyAppName == packageName) { + logd("flow: http proxy enabled for $packageName, handling as spl app") + return true + } + } + + if (appConfig.isDnsProxyActive()) { + val endpoint = appConfig.getSelectedDnsProxyDetails() ?: return false + val packageName = FirewallManager.getPackageNameByUid(uid) ?: return false + // do not block the app if the app is set to forward the traffic via dns proxy + if (endpoint.proxyAppName == packageName) { + logd("flow: dns proxy enabled for $packageName, handling as spl app") + return true + } + } + + return false } private suspend fun determineProxyDetails( connTracker: ConnTrackerMetaData, - connId: String = connTracker.connId, - uid: Int = connTracker.uid + isSplApp: Boolean ): intra.Mark { + val baseOrExit = + if (isSplApp) { + Backend.Exit + } else { + Backend.Base + } + val connId = connTracker.connId + val uid = connTracker.uid // check for one-wireguard, if enabled, return wireguard proxy for all connections val oneWgId = WireguardManager.getOneWireGuardProxyId() if (oneWgId != null && oneWgId != WireguardManager.INVALID_CONF_ID) { @@ -3070,6 +3138,7 @@ class BraveVPNService : // regardless of whether this proxyId exists in go, use it to avoid leaks val canRoute = vpnAdapter?.canRouteIp(proxyId, connTracker.destIP, true) return if (canRoute == true) { + handleProxyHandshake(proxyId) logd("flow: one-wg is enabled, returning $proxyId, $connId, $uid") persistAndConstructFlowResponse(connTracker, proxyId, connId, uid) } else { @@ -3077,7 +3146,7 @@ class BraveVPNService : // will be dropped, in those cases, return base (connection will be forwarded to // base proxy) logd("flow: one-wg is enabled, but no route; ret:Ipn.Base, $connId, $uid") - persistAndConstructFlowResponse(connTracker, Backend.Base, connId, uid) + persistAndConstructFlowResponse(connTracker, baseOrExit, connId, uid) } } @@ -3088,33 +3157,24 @@ class BraveVPNService : // avoid leaks if (wgConfig.isActive || wgConfig.isLockdown || wgConfig.isCatchAll) { val canRoute = vpnAdapter?.canRouteIp(proxyId, connTracker.destIP, true) - if (canRoute == true) { + return if (canRoute == true) { + handleProxyHandshake(proxyId) logd("flow: wg is active/lockdown/catch-all; $proxyId, $connId, $uid") - return persistAndConstructFlowResponse(connTracker, proxyId, connId, uid) + persistAndConstructFlowResponse(connTracker, proxyId, connId, uid) } else { logd("flow: wg is active/lockdown/catch-all, but no route, $connId, $uid") - return persistAndConstructFlowResponse(connTracker, Backend.Base, connId, uid) + persistAndConstructFlowResponse(connTracker, baseOrExit, connId, uid) } } else { // fall-through, no lockdown/catch-all/active wg found, so proceed with other checks } } - // no need to check for other proxies if the protocol is not TCP or UDP - // fixme: is this even needed? - if ( - connTracker.protocol != Protocol.TCP.protocolType && - connTracker.protocol != Protocol.UDP.protocolType - ) { - logd("flow: protocol is not TCP or UDP, returning Ipn.Base, $connId, $uid") - return persistAndConstructFlowResponse(connTracker, Backend.Base, connId, uid) - } - // carry out this check after wireguard, because wireguard has catchAll and lockdown // if no proxy is enabled, return Ipn.Base if (!appConfig.isProxyEnabled()) { logd("flow: no proxy enabled, returning Ipn.Base, $connId, $uid") - return persistAndConstructFlowResponse(connTracker, Backend.Base, connId, uid) + return persistAndConstructFlowResponse(connTracker, baseOrExit, connId, uid) } // comment out tcp proxy for v055 release @@ -3153,8 +3213,6 @@ class BraveVPNService : val packageName = FirewallManager.getPackageNameByUid(uid) if (endpoint?.proxyAppName == packageName) { logd("flow: orbot exit for $packageName, $connId, $uid") - connTracker.isBlocked = false // do not block orbot, in case of orbot proxy - connTracker.blockedByRule = FirewallRuleset.RULE0.id return persistAndConstructFlowResponse(connTracker, Backend.Exit, connId, uid) } @@ -3181,8 +3239,6 @@ class BraveVPNService : // do not block the app if the app is set to forward the traffic via socks5 proxy if (endpoint.proxyAppName == packageName) { logd("flow: socks5 exit for $packageName, $connId, $uid") - connTracker.isBlocked = false - connTracker.blockedByRule = FirewallRuleset.RULE0.id return persistAndConstructFlowResponse(connTracker, Backend.Exit, connId, uid) } @@ -3201,8 +3257,6 @@ class BraveVPNService : // do not block the app if the app is set to forward the traffic via http proxy if (endpoint.proxyAppName == packageName) { logd("flow: http exit for $packageName, $connId, $uid") - connTracker.isBlocked = false - connTracker.blockedByRule = FirewallRuleset.RULE0.id return persistAndConstructFlowResponse(connTracker, Backend.Exit, connId, uid) } @@ -3215,8 +3269,53 @@ class BraveVPNService : ) } - logd("flow: no proxies, Ipn.Base, $connId, $uid") - return persistAndConstructFlowResponse(connTracker, Backend.Base, connId, uid) + if (appConfig.isDnsProxyActive()) { + val endpoint = appConfig.getSelectedDnsProxyDetails() + val packageName = FirewallManager.getPackageNameByUid(uid) + // do not block the app if the app is set to forward the traffic via dns proxy + if (endpoint?.proxyAppName == packageName) { + logd("flow: dns proxy enabled for $packageName, return exit, $connId, $uid") + return persistAndConstructFlowResponse(connTracker, Backend.Exit, connId, uid) + } + } + + logd("flow: no proxies, $baseOrExit, $connId, $uid") + return persistAndConstructFlowResponse(connTracker, baseOrExit, connId, uid) + } + + private fun handleProxyHandshake(id: String) { + if (!id.startsWith(ProxyManager.ID_WG_BASE)) { + // only wireguard proxies are considered for handshakes + return + } + + val realtime = elapsedRealtime() + val latestCheckpoint = wgHandShakeCheckpoints[id] ?: return + val cpInterval = realtime - latestCheckpoint + val cpIntervalSecs = TimeUnit.MILLISECONDS.toSeconds(cpInterval) + if (cpInterval < this.checkpointInterval) { + logd("flow: handshake skipping check for $id, $cpIntervalSecs") + return + } + val stats = vpnAdapter?.getProxyStats(id) ?: return + val lastHandShake = stats.lastOK + logd("flow: handshake check for $id, $lastHandShake, interval: $cpIntervalSecs") + if (lastHandShake <= 0) { + logd("flow: handshake is not established for $id, $lastHandShake, returning") + return + } + val currTimeMs = System.currentTimeMillis() + val durationMs = currTimeMs - lastHandShake + val durationSecs = TimeUnit.MILLISECONDS.toSeconds(durationMs) + // if the last handshake is older than the timeout, refresh the proxy + if (durationMs > wgHandshakeTimeout) { + wgHandShakeCheckpoints[id] = realtime + Log.i(LOG_TAG_VPN, "flow: handshake timeout for $id, $durationSecs, refreshing") + io("proxyHandshake") { vpnAdapter?.refreshProxy(id) } + } else { + Log.i(LOG_TAG_VPN, "flow: handshake is within timeout for $id, $durationSecs") + wgHandShakeCheckpoints[id] = realtime + } } fun hasCid(connId: String, uid: Int): Boolean { @@ -3281,7 +3380,10 @@ class BraveVPNService : mark.uid = uid.toString() } if (cm == null) { - logd("flow: returning mark: $mark for connId: $connId, uid: $uid, cm: null") + Log.i( + LOG_TAG_VPN, + "flow: returning mark: $mark for connId: $connId, uid: $uid, cm: null" + ) } else { Log.i( LOG_TAG_VPN, @@ -3294,9 +3396,10 @@ class BraveVPNService : private suspend fun processFirewallRequest( metadata: ConnTrackerMetaData, anyRealIpBlocked: Boolean = false, - blocklists: String = "" + blocklists: String = "", + isSplApp: Boolean ) { - val rule = firewall(metadata, anyRealIpBlocked) + val rule = firewall(metadata, anyRealIpBlocked, isSplApp) metadata.blockedByRule = rule.id metadata.blocklists = blocklists @@ -3359,6 +3462,15 @@ class BraveVPNService : } } + fun getProxyStats(id: String): Stats? { + return if (vpnAdapter != null) { + vpnAdapter?.getProxyStats(id) + } else { + Log.w(LOG_TAG_VPN, "error while fetching proxy stats: vpnAdapter is null") + null + } + } + fun getSupportedIpVersion(id: String): Pair? { return if (vpnAdapter != null) { vpnAdapter?.getSupportedIpVersion(id) diff --git a/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt b/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt index 97bcad56d..e334ce1e2 100644 --- a/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt +++ b/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt @@ -49,6 +49,7 @@ import java.net.InetAddress import java.net.InetSocketAddress import java.net.Socket import java.util.Collections +import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit import kotlin.math.max import kotlin.math.min @@ -56,7 +57,7 @@ import kotlin.math.min class ConnectionMonitor(private val networkListener: NetworkListener) : ConnectivityManager.NetworkCallback(), KoinComponent { - private val networkSet: MutableSet = mutableSetOf() + private val networkSet: MutableSet = ConcurrentHashMap.newKeySet() // add cellular, wifi, bluetooth, ethernet, vpn, wifi aware, low pan private val networkRequest: NetworkRequest = diff --git a/app/src/main/java/com/celzero/bravedns/service/FirewallManager.kt b/app/src/main/java/com/celzero/bravedns/service/FirewallManager.kt index 45cca6750..c8b53ccce 100644 --- a/app/src/main/java/com/celzero/bravedns/service/FirewallManager.kt +++ b/app/src/main/java/com/celzero/bravedns/service/FirewallManager.kt @@ -245,7 +245,7 @@ object FirewallManager : KoinComponent { io { load() } } - data class AppInfoTuple(val uid: Int, var packageName: String) + data class AppInfoTuple(val uid: Int, val packageName: String) suspend fun isUidFirewalled(uid: Int): Boolean { return connectionStatus(uid) != ConnectionStatus.ALLOW diff --git a/app/src/main/java/com/celzero/bravedns/service/PersistentState.kt b/app/src/main/java/com/celzero/bravedns/service/PersistentState.kt index e4fd264bd..5913cb9ea 100644 --- a/app/src/main/java/com/celzero/bravedns/service/PersistentState.kt +++ b/app/src/main/java/com/celzero/bravedns/service/PersistentState.kt @@ -19,6 +19,7 @@ import android.content.Context import androidx.lifecycle.MutableLiveData import com.celzero.bravedns.R import com.celzero.bravedns.data.AppConfig +import com.celzero.bravedns.database.DnsCryptRelayEndpoint import com.celzero.bravedns.util.Constants.Companion.INIT_TIME_MS import com.celzero.bravedns.util.Constants.Companion.INVALID_PORT import com.celzero.bravedns.util.InternetProtocol @@ -44,7 +45,6 @@ class PersistentState(context: Context) : SimpleKrate(context), KoinComponent { const val NETWORK = "add_all_networks_to_vpn" const val NOTIFICATION_ACTION = "notification_action" const val DNS_CHANGE = "connected_dns_name" - const val DNS_RELAYS = "dnscrypt_relay" const val INTERNET_PROTOCOL = "internet_protocol" const val PROTOCOL_TRANSLATION = "protocol_translation" const val DEFAULT_DNS_SERVER = "default_dns_query" @@ -283,6 +283,14 @@ class PersistentState(context: Context) : SimpleKrate(context), KoinComponent { var universalRulesCount: MutableLiveData = MutableLiveData() var proxyStatus: MutableLiveData = MutableLiveData() + // data class to store dnscrypt relay details + data class DnsCryptRelayDetails( + val relay: DnsCryptRelayEndpoint, + val added: Boolean + ) + + var dnsCryptRelays: MutableLiveData = MutableLiveData() + var remoteBlocklistCount: MutableLiveData = MutableLiveData() fun setMedianLatency(median: Long) { diff --git a/app/src/main/java/com/celzero/bravedns/service/VpnController.kt b/app/src/main/java/com/celzero/bravedns/service/VpnController.kt index dc46ed450..95547bcc9 100644 --- a/app/src/main/java/com/celzero/bravedns/service/VpnController.kt +++ b/app/src/main/java/com/celzero/bravedns/service/VpnController.kt @@ -23,6 +23,7 @@ import android.util.Log import androidx.core.content.ContextCompat import androidx.lifecycle.MutableLiveData import backend.RDNS +import backend.Stats import com.celzero.bravedns.R import com.celzero.bravedns.service.BraveVPNService.Companion.FAIL_OPEN_ON_NO_NETWORK import com.celzero.bravedns.util.Constants.Companion.INVALID_UID @@ -211,6 +212,10 @@ object VpnController : KoinComponent { return braveVpnService?.getProxyStatusById(id) } + fun getProxyStats(id: String): Stats? { + return braveVpnService?.getProxyStats(id) ?: null + } + fun getSupportedIpVersion(id: String): Pair { return braveVpnService?.getSupportedIpVersion(id) ?: Pair(false, false) } diff --git a/app/src/main/java/com/celzero/bravedns/wireguard/Config.kt b/app/src/main/java/com/celzero/bravedns/wireguard/Config.kt index 6a12ba483..44cc165e5 100644 --- a/app/src/main/java/com/celzero/bravedns/wireguard/Config.kt +++ b/app/src/main/java/com/celzero/bravedns/wireguard/Config.kt @@ -33,8 +33,8 @@ import java.util.* */ @NonNullForAll class Config private constructor(builder: Builder) { - private var id: Int - private var name: String + private val id: Int + private val name: String /** * Returns the interface section of the configuration. * @@ -76,10 +76,6 @@ class Config private constructor(builder: Builder) { return peers } - fun setId(id: Int) { - this.id = id - } - fun getId(): Int { return id } @@ -88,10 +84,6 @@ class Config private constructor(builder: Builder) { return name } - fun setName(name: String) { - this.name = name - } - override fun hashCode(): Int { return 31 * wgInterface.hashCode() + peers.hashCode() } From 9460e826c63543b9dc6f9cb1bfcb9ce58d957b7e Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Thu, 18 Apr 2024 19:18:20 +0530 Subject: [PATCH 17/48] bump firestack version --- app/build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index ded32e6f7..d8021f1d2 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -247,8 +247,8 @@ dependencies { fullImplementation 'com.github.kirich1409:viewbindingpropertydelegate-noreflection:1.5.9' // from: https://jitpack.io/#celzero/firestack - download 'com.github.celzero:firestack:6ea1f4cbbd@aar' - implementation 'com.github.celzero:firestack:6ea1f4cbbd@aar' + download 'com.github.celzero:firestack:a945ad8429@aar' + implementation 'com.github.celzero:firestack:a945ad8429@aar' // Work manager implementation('androidx.work:work-runtime-ktx:2.9.0') { From 120a0a66e421c6245a248aa76b265a21ccf8c2d2 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Thu, 18 Apr 2024 19:19:09 +0530 Subject: [PATCH 18/48] bug fix: restart logger on vpn service creation --- .../celzero/bravedns/service/NetLogTracker.kt | 54 ++++++++++--------- .../celzero/bravedns/util/NetLogBatcher.kt | 4 +- 2 files changed, 31 insertions(+), 27 deletions(-) diff --git a/app/src/main/java/com/celzero/bravedns/service/NetLogTracker.kt b/app/src/main/java/com/celzero/bravedns/service/NetLogTracker.kt index ac6e27fdc..6aa4ef547 100644 --- a/app/src/main/java/com/celzero/bravedns/service/NetLogTracker.kt +++ b/app/src/main/java/com/celzero/bravedns/service/NetLogTracker.kt @@ -49,32 +49,34 @@ internal constructor( private var scope: CoroutineScope? = null - private var dnsLogTracker: DnsLogTracker = + private var dnsdb: DnsLogTracker = DnsLogTracker(dnsLogRepository, persistentState, context) - private var ipTracker: IPTracker = + private var ipdb: IPTracker = IPTracker(connectionTrackerRepository, rethinkLogRepository, context) - private var dnsNetLogBatcher: NetLogBatcher = - NetLogBatcher("dns", dnsLogTracker::insertBatch) - private var ipNetLogBatcher: NetLogBatcher = - NetLogBatcher("ip", ipTracker::insertBatch, ipTracker::updateBatch) - private var rethinkLogBatcher: NetLogBatcher = - NetLogBatcher("rinr", ipTracker::insertRethinkBatch, ipTracker::updateRethinkBatch) + private var dnsBatcher: NetLogBatcher? = null + private var ipBatcher: NetLogBatcher? = null + private var rinrBatcher: NetLogBatcher? = null - suspend fun startLogger(s: CoroutineScope) { + suspend fun restart(s: CoroutineScope) { this.scope = s - dnsNetLogBatcher.begin(s) - ipNetLogBatcher.begin(s) - rethinkLogBatcher.begin(s) + // create new batchers on every new scope as their lifecycle is tied to the scope + this.dnsBatcher = NetLogBatcher("dns", dnsdb::insertBatch) + this.ipBatcher = NetLogBatcher("ip", ipdb::insertBatch, ipdb::updateBatch) + this.rinrBatcher = NetLogBatcher("rinr", ipdb::insertRethinkBatch, ipdb::updateRethinkBatch) + + dnsBatcher!!.begin(s) + ipBatcher!!.begin(s) + rinrBatcher!!.begin(s) } fun writeIpLog(info: ConnTrackerMetaData) { if (!persistentState.logsEnabled) return io("writeIpLog") { - val connTracker = ipTracker.makeConnectionTracker(info) - ipNetLogBatcher.add(connTracker) + val connTracker = ipdb.makeConnectionTracker(info) + ipBatcher?.add(connTracker) } } @@ -82,57 +84,57 @@ internal constructor( if (!persistentState.logsEnabled) return io("writeRethinkLog") { - val rlog = ipTracker.makeRethinkLogs(info) ?: return@io - rethinkLogBatcher.add(rlog) + val rlog = ipdb.makeRethinkLogs(info) ?: return@io + rinrBatcher?.add(rlog) } } fun updateIpSummary(summary: ConnectionSummary) { if (!persistentState.logsEnabled) return - io("writeIpSummary") { + io("updateIpSmm") { val s = if (DEBUG && summary.targetIp?.isNotEmpty() == true) { - ipTracker.makeSummaryWithTarget(summary) + ipdb.makeSummaryWithTarget(summary) } else { summary } - ipNetLogBatcher.update(s) + ipBatcher?.update(s) } } fun updateRethinkSummary(summary: ConnectionSummary) { if (!persistentState.logsEnabled) return - io("writeRethinkSummary") { + io("updateRethinkSmm") { val s = if (DEBUG && summary.targetIp?.isNotEmpty() == true) { - ipTracker.makeSummaryWithTarget(summary) + ipdb.makeSummaryWithTarget(summary) } else { summary } - rethinkLogBatcher.update(s) + rinrBatcher?.update(s) } } // now, this method is doing multiple things which should be removed. // fixme: should intend to only write the logs to database. fun processDnsLog(summary: DNSSummary) { - val transaction = dnsLogTracker.processOnResponse(summary) + val transaction = dnsdb.processOnResponse(summary) transaction.responseCalendar = Calendar.getInstance() // refresh latency from GoVpnAdapter io("refreshDnsLatency") { dnsLatencyTracker.refreshLatencyIfNeeded(transaction) } // TODO: This method should be part of BraveVPNService - dnsLogTracker.updateVpnConnectionState(transaction) + dnsdb.updateVpnConnectionState(transaction) if (!persistentState.logsEnabled) return - val dnsLog = dnsLogTracker.makeDnsLogObj(transaction) - io("dnsLogger") { dnsNetLogBatcher.add(dnsLog) } + val dnsLog = dnsdb.makeDnsLogObj(transaction) + io("writeDnsLog") { dnsBatcher?.add(dnsLog) } } private fun io(s: String, f: suspend () -> Unit) = diff --git a/app/src/main/java/com/celzero/bravedns/util/NetLogBatcher.kt b/app/src/main/java/com/celzero/bravedns/util/NetLogBatcher.kt index 9ae789bc0..7b7206ab9 100644 --- a/app/src/main/java/com/celzero/bravedns/util/NetLogBatcher.kt +++ b/app/src/main/java/com/celzero/bravedns/util/NetLogBatcher.kt @@ -74,6 +74,7 @@ class NetLogBatcher( private var updates = mutableListOf() fun begin(scope: CoroutineScope) { + Log.i(LOG_BATCH_LOGGER, "begin") // launch suspend fns sig and consume asynchronously scope.async { sig() } scope.async { consumeAdd() } @@ -92,6 +93,7 @@ class NetLogBatcher( signal.close() buffersCh.close() updatesCh.close() + Log.i(LOG_BATCH_LOGGER, "end") } } } @@ -124,7 +126,7 @@ class NetLogBatcher( lsn = (lsn + 1) } - suspend fun add(payload: T) = + suspend fun add(payload: T) = withContext(looper + nprod) { batches.add(payload) // if the batch size is met, dispatch it to the consumer From c03a337397e2b986bffb415df9791c7db41f1594 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Fri, 19 Apr 2024 17:39:14 +0530 Subject: [PATCH 19/48] restore: rmv wireguard if enabled in restored database --- .../main/java/com/celzero/bravedns/backup/RestoreAgent.kt | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/src/main/java/com/celzero/bravedns/backup/RestoreAgent.kt b/app/src/main/java/com/celzero/bravedns/backup/RestoreAgent.kt index 0ce530093..0e953feb2 100644 --- a/app/src/main/java/com/celzero/bravedns/backup/RestoreAgent.kt +++ b/app/src/main/java/com/celzero/bravedns/backup/RestoreAgent.kt @@ -32,6 +32,7 @@ import com.celzero.bravedns.backup.BackupHelper.Companion.deleteResidue import com.celzero.bravedns.backup.BackupHelper.Companion.getTempDir import com.celzero.bravedns.backup.BackupHelper.Companion.stopVpn import com.celzero.bravedns.backup.BackupHelper.Companion.unzip +import com.celzero.bravedns.data.AppConfig import com.celzero.bravedns.database.AppDatabase import com.celzero.bravedns.database.LogDatabase import com.celzero.bravedns.service.PersistentState @@ -51,6 +52,7 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : private val logDatabase by inject() private val appDatabase by inject() + private val appConfig by inject() private val persistentState by inject() companion object { @@ -281,6 +283,10 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : } private fun wireGuardCleanup() { + if (appConfig.isWireGuardEnabled()) { + Log.i(LOG_TAG_BACKUP_RESTORE, "wireGuard is enabled, reset the wireguard entries") + appConfig.removeAllProxies() + } // delete WireGuard related entries from database Log.i(LOG_TAG_BACKUP_RESTORE, "wireguard cleanup process") WireguardManager.restoreProcessDeleteWireGuardEntries() From 7dc4518f0a68ab2abb6f453b6e13b42d112de937 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Sat, 20 Apr 2024 16:14:12 +0530 Subject: [PATCH 20/48] prompt user for battery optimization and restrict bg usage --- .../LocalBlocklistCoordinator.kt | 3 +- .../ui/fragment/HomeScreenFragment.kt | 91 +++++++++++++++++-- .../java/com/celzero/bravedns/util/UIUtils.kt | 11 +-- 3 files changed, 89 insertions(+), 16 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/customdownloader/LocalBlocklistCoordinator.kt b/app/src/full/java/com/celzero/bravedns/customdownloader/LocalBlocklistCoordinator.kt index 0df103ddb..a7fe4f47b 100644 --- a/app/src/full/java/com/celzero/bravedns/customdownloader/LocalBlocklistCoordinator.kt +++ b/app/src/full/java/com/celzero/bravedns/customdownloader/LocalBlocklistCoordinator.kt @@ -55,6 +55,7 @@ import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.util.concurrent.CancellationException +import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParameters) : @@ -62,7 +63,7 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame val persistentState by inject() val appConfig by inject() - private var downloadStatuses: MutableMap = hashMapOf() + private var downloadStatuses: ConcurrentHashMap = ConcurrentHashMap() // download request status enum class DownloadStatus { diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt index a1f69c1b6..20c34789d 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt @@ -29,7 +29,9 @@ import android.net.TrafficStats import android.net.VpnService import android.os.Build import android.os.Bundle +import android.os.PowerManager import android.os.SystemClock +import android.provider.Settings import android.text.format.DateUtils import android.util.Log import android.util.TypedValue @@ -72,20 +74,21 @@ import com.celzero.bravedns.util.UIUtils.openVpnProfile import com.celzero.bravedns.util.UIUtils.updateHtmlEncodedText import com.celzero.bravedns.util.Utilities.delay import com.celzero.bravedns.util.Utilities.getPrivateDnsMode +import com.celzero.bravedns.util.Utilities.isAtleastN import com.celzero.bravedns.util.Utilities.isOtherVpnHasAlwaysOn import com.celzero.bravedns.util.Utilities.isPrivateDnsActive import com.celzero.bravedns.util.Utilities.showToastUiCentered import com.facebook.shimmer.Shimmer import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar +import java.util.* +import java.util.concurrent.TimeUnit import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.koin.android.ext.android.inject -import java.util.* -import java.util.concurrent.TimeUnit class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { private val b by viewBinding(FragmentHomeScreenBinding::bind) @@ -710,11 +713,6 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { } private fun handleMainScreenBtnClickEvent() { - - if (handleAlwaysOnVpn()) { - return - } - b.fhsDnsOnOffBtn.isEnabled = false delay(TimeUnit.MILLISECONDS.toMillis(500), lifecycleScope) { if (isAdded) { @@ -722,6 +720,19 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { } } + // prompt user to disable battery optimization and restrict background data + if (isRestrictBackgroundActive(requireContext()) && !isVpnActivated) { + showRestrictBgActiveDialog() + } else if (batteryOptimizationActive(requireContext()) && !isVpnActivated) { + showBatteryOptimizationDialog() + } + + handleVpnActivation() + } + + private fun handleVpnActivation() { + if (handleAlwaysOnVpn()) return + if (isVpnActivated) { stopVpnService() } else { @@ -729,6 +740,70 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { } } + private fun batteryOptimizationActive(context: Context): Boolean { + val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager + if (DEBUG) + Log.d( + LOG_TAG_UI, + "ignore battery optimization: ${powerManager.isIgnoringBatteryOptimizations(context.packageName)}" + ) + return !powerManager.isIgnoringBatteryOptimizations(context.packageName) + } + + private fun showBatteryOptimizationDialog() { + if (!isAtleastN()) return + + val builder = MaterialAlertDialogBuilder(requireContext()) + builder.setTitle(R.string.battery_optimization_dialog_heading) + builder.setMessage(R.string.battery_optimization_dialog_message) + builder.setCancelable(false) + builder.setPositiveButton(R.string.lbl_proceed) { _, _ -> + openNetworkSettings( + requireContext(), + Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS + ) + } + + builder.setNegativeButton(R.string.lbl_dismiss) { _, _ -> + // no-op + } + builder.create().show() + } + + private fun isRestrictBackgroundActive(context: Context): Boolean { + if (!isAtleastN()) return false + + val connectivityManager = + context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + if (DEBUG) + Log.d( + LOG_TAG_UI, + "restrict background status: ${connectivityManager.restrictBackgroundStatus}" + ) + return connectivityManager.restrictBackgroundStatus == + ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED + } + + private fun showRestrictBgActiveDialog() { + if (!isAtleastN()) return + + val builder = MaterialAlertDialogBuilder(requireContext()) + builder.setTitle(R.string.restrict_bg_dialog_heading) + builder.setMessage(R.string.restrict_bg_dialog_message) + builder.setCancelable(false) + builder.setPositiveButton(R.string.lbl_proceed) { _, _ -> + openNetworkSettings( + requireContext(), + Settings.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS + ) + } + + builder.setNegativeButton(R.string.lbl_dismiss) { _, _ -> + // no-op + } + builder.create().show() + } + private fun showAlwaysOnStopDialog() { val builder = MaterialAlertDialogBuilder(requireContext()) @@ -929,7 +1004,7 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { builder.setMessage(R.string.private_dns_dialog_desc) builder.setCancelable(false) builder.setPositiveButton(R.string.private_dns_dialog_positive) { _, _ -> - openNetworkSettings(requireContext()) + openNetworkSettings(requireContext(), Settings.ACTION_WIRELESS_SETTINGS) } builder.setNegativeButton(R.string.lbl_dismiss) { _, _ -> diff --git a/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt b/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt index f4e985152..4c1c999d4 100644 --- a/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt +++ b/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt @@ -166,17 +166,14 @@ object UIUtils { } } - fun openNetworkSettings(context: Context) { + fun openNetworkSettings(context: Context, settings: String) { try { - val intent = Intent(Settings.ACTION_WIRELESS_SETTINGS) + val intent = Intent(settings) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK context.startActivity(intent) } catch (e: ActivityNotFoundException) { - Utilities.showToastUiCentered( - context, - context.getString(R.string.private_dns_error), - Toast.LENGTH_SHORT - ) + val msg = context.getString(R.string.intent_launch_error, settings) + Utilities.showToastUiCentered(context, msg, Toast.LENGTH_SHORT) Log.w(Logger.LOG_TAG_VPN, "Failure opening network setting screen: ${e.message}", e) } } From 379587e77def651570d2cd81d5d0a62d25d5c8d1 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Sat, 20 Apr 2024 16:14:52 +0530 Subject: [PATCH 21/48] ui: show dns as selected when vpn is not active --- .../bravedns/adapter/DnsCryptEndpointAdapter.kt | 4 +++- .../celzero/bravedns/adapter/DoTEndpointAdapter.kt | 5 ++++- .../celzero/bravedns/adapter/DohEndpointAdapter.kt | 4 +++- .../bravedns/adapter/ODoHEndpointAdapter.kt | 5 ++++- .../bravedns/adapter/RethinkEndpointAdapter.kt | 14 +++++++++++++- 5 files changed, 27 insertions(+), 5 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/adapter/DnsCryptEndpointAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/DnsCryptEndpointAdapter.kt index 2959a5f9f..13d4ed6d6 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/DnsCryptEndpointAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/DnsCryptEndpointAdapter.kt @@ -117,8 +117,10 @@ class DnsCryptEndpointAdapter(private val context: Context, private val appConfi b.dnsCryptEndpointListUrlName.text = endpoint.dnsCryptName b.dnsCryptEndpointListActionImage.isChecked = endpoint.isSelected - if (endpoint.isSelected) { + if (endpoint.isSelected && VpnController.hasTunnel()) { keepSelectedStatusUpdated() + } else if (endpoint.isSelected) { + b.dnsCryptEndpointListUrlExplanation.text = context.getString(R.string.rt_filter_parent_selected) } else { b.dnsCryptEndpointListUrlExplanation.text = "" } diff --git a/app/src/full/java/com/celzero/bravedns/adapter/DoTEndpointAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/DoTEndpointAdapter.kt index 7fb3522fc..4dcba76c9 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/DoTEndpointAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/DoTEndpointAdapter.kt @@ -113,8 +113,11 @@ class DoTEndpointAdapter(private val context: Context, private val appConfig: Ap ) } b.endpointCheck.isChecked = endpoint.isSelected - if (endpoint.isSelected) { + + if (endpoint.isSelected && VpnController.hasTunnel()) { keepSelectedStatusUpdated() + } else if (endpoint.isSelected) { + b.endpointDesc.text = context.getString(R.string.rt_filter_parent_selected) } else { b.endpointDesc.text = "" } diff --git a/app/src/full/java/com/celzero/bravedns/adapter/DohEndpointAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/DohEndpointAdapter.kt index 2645abb00..4cab696b0 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/DohEndpointAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/DohEndpointAdapter.kt @@ -113,8 +113,10 @@ class DohEndpointAdapter(private val context: Context, private val appConfig: Ap ) } b.endpointCheck.isChecked = endpoint.isSelected - if (endpoint.isSelected) { + if (endpoint.isSelected && VpnController.hasTunnel()) { keepSelectedStatusUpdated() + } else if (endpoint.isSelected) { + b.endpointDesc.text = context.getString(R.string.rt_filter_parent_selected) } else { b.endpointDesc.text = "" } diff --git a/app/src/full/java/com/celzero/bravedns/adapter/ODoHEndpointAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/ODoHEndpointAdapter.kt index 0f1ee21a4..1069330a0 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/ODoHEndpointAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/ODoHEndpointAdapter.kt @@ -104,8 +104,11 @@ class ODoHEndpointAdapter(private val context: Context, private val appConfig: A private fun displayDetails(endpoint: ODoHEndpoint) { b.endpointName.text = endpoint.name b.endpointCheck.isChecked = endpoint.isSelected - if (endpoint.isSelected) { + + if (endpoint.isSelected && VpnController.hasTunnel()) { keepSelectedStatusUpdated() + } else if (endpoint.isSelected) { + b.endpointDesc.text = context.getString(R.string.rt_filter_parent_selected) } else { b.endpointDesc.text = "" } diff --git a/app/src/full/java/com/celzero/bravedns/adapter/RethinkEndpointAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/RethinkEndpointAdapter.kt index e225e06b9..2666929bb 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/RethinkEndpointAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/RethinkEndpointAdapter.kt @@ -117,8 +117,10 @@ class RethinkEndpointAdapter(private val context: Context, private val appConfig // Shows either the info/delete icon for the DoH entries. showIcon(endpoint) - if (endpoint.isActive) { + if (endpoint.isActive && VpnController.hasTunnel()) { keepSelectedStatusUpdated(endpoint) + } else if (endpoint.isActive) { + b.rethinkEndpointListUrlExplanation.text = context.getString(R.string.rt_filter_parent_selected) } else { b.rethinkEndpointListUrlExplanation.text = "" } @@ -227,6 +229,16 @@ class RethinkEndpointAdapter(private val context: Context, private val appConfig } private fun openEditConfiguration(endpoint: RethinkDnsEndpoint) { + + if (!VpnController.hasTunnel()) { + Utilities.showToastUiCentered( + context, + context.getString(R.string.ssv_toast_start_rethink), + Toast.LENGTH_SHORT + ) + return + } + val intent = Intent(context, ConfigureRethinkBasicActivity::class.java) intent.putExtra( ConfigureRethinkBasicActivity.RETHINK_BLOCKLIST_TYPE, From bae0f5d61fcd9904a74a29b92f828fe08eac3b19 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Sat, 20 Apr 2024 16:15:24 +0530 Subject: [PATCH 22/48] notif action: do not enable dns mode on proxy active --- .../bravedns/receiver/NotificationActionReceiver.kt | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/receiver/NotificationActionReceiver.kt b/app/src/full/java/com/celzero/bravedns/receiver/NotificationActionReceiver.kt index 283d42736..b449cf8d5 100644 --- a/app/src/full/java/com/celzero/bravedns/receiver/NotificationActionReceiver.kt +++ b/app/src/full/java/com/celzero/bravedns/receiver/NotificationActionReceiver.kt @@ -63,7 +63,7 @@ class NotificationActionReceiver : BroadcastReceiver(), KoinComponent { stopVpn(context) } Constants.NOTIF_ACTION_DNS_VPN -> { - dnsMode() + dnsMode(context) } Constants.NOTIF_ACTION_DNS_FIREWALL_VPN -> { dnsFirewallMode() @@ -115,11 +115,17 @@ class NotificationActionReceiver : BroadcastReceiver(), KoinComponent { VpnController.resumeApp() } - private fun dnsMode() { + private fun dnsMode(context: Context) { + if (appConfig.isProxyEnabled()) { + Utilities.showToastUiCentered(context, context.getString(R.string.settings_lock_down_proxy_desc), Toast.LENGTH_SHORT) + return + } io { appConfig.changeBraveMode(AppConfig.BraveMode.DNS.mode) } } private fun dnsFirewallMode() { + if (appConfig.getBraveMode().isDnsFirewallMode()) return + io { appConfig.changeBraveMode(AppConfig.BraveMode.DNS_FIREWALL.mode) } } From d727d291dee4d714ab42c3c7021d39fd0638befa Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Sat, 20 Apr 2024 16:15:52 +0530 Subject: [PATCH 23/48] ui: show dns search domain if available --- .../bravedns/ui/activity/WgConfigDetailActivity.kt | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigDetailActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigDetailActivity.kt index eb7a7ad89..7afe3fd83 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigDetailActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigDetailActivity.kt @@ -192,8 +192,15 @@ class WgConfigDetailActivity : AppCompatActivity(R.layout.activity_wg_detail) { if (wgType.isOneWg()) { b.dnsServersLabel.visibility = View.VISIBLE b.dnsServersText.visibility = View.VISIBLE - b.dnsServersText.text = - wgInterface?.dnsServers?.joinToString { it.hostAddress?.toString() ?: "" } + var dns = wgInterface?.dnsServers?.joinToString { it.hostAddress?.toString() ?: "" } + val searchDomains = wgInterface?.dnsSearchDomains?.joinToString { it } + dns = + if (!searchDomains.isNullOrEmpty()) { + "$dns,$searchDomains" + } else { + dns + } + b.dnsServersText.text = dns } else { b.dnsServersLabel.visibility = View.GONE b.dnsServersText.visibility = View.GONE From 498a422a3f55beba1ef7d4952ee7f42b89129e2d Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Sat, 20 Apr 2024 16:17:37 +0530 Subject: [PATCH 24/48] do not allow user to configure blocklist until vpn is active --- .../ui/bottomsheet/LocalBlocklistsBottomSheet.kt | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/LocalBlocklistsBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/LocalBlocklistsBottomSheet.kt index 15a709b8e..ab3c6a720 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/LocalBlocklistsBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/LocalBlocklistsBottomSheet.kt @@ -38,6 +38,7 @@ import com.celzero.bravedns.download.AppDownloadManager import com.celzero.bravedns.download.DownloadConstants import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.service.RethinkBlocklistManager +import com.celzero.bravedns.service.VpnController import com.celzero.bravedns.ui.activity.ConfigureRethinkBasicActivity import com.celzero.bravedns.ui.fragment.DnsSettingsFragment import com.celzero.bravedns.util.Constants @@ -450,6 +451,15 @@ class LocalBlocklistsBottomSheet : BottomSheetDialogFragment() { } private fun invokeRethinkActivity() { + if (VpnController.hasTunnel()) { + Utilities.showToastUiCentered( + requireContext(), + getString(R.string.ssv_toast_start_rethink), + Toast.LENGTH_SHORT + ) + return + } + this.dismiss() val intent = Intent(requireContext(), ConfigureRethinkBasicActivity::class.java) intent.putExtra( From 08c28eddbf4bad69efab136085962f74b0140c5e Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Sat, 20 Apr 2024 19:54:49 +0530 Subject: [PATCH 25/48] log: use log defined in Logger instead of android util --- .../celzero/bravedns/NonStoreAppUpdater.kt | 9 +- .../celzero/bravedns/RethinkDnsApplication.kt | 5 +- .../bravedns/adapter/AppWiseDomainsAdapter.kt | 5 +- .../bravedns/adapter/AppWiseIpsAdapter.kt | 5 +- .../adapter/ConnectionTrackerAdapter.kt | 7 +- .../bravedns/adapter/CustomDomainAdapter.kt | 5 +- .../bravedns/adapter/CustomIpAdapter.kt | 5 +- .../bravedns/adapter/DnsQueryAdapter.kt | 14 +- .../bravedns/adapter/DoTEndpointAdapter.kt | 13 +- .../bravedns/adapter/DohEndpointAdapter.kt | 13 +- .../adapter/DomainRulesBtmSheetAdapter.kt | 7 +- .../bravedns/adapter/ODoHEndpointAdapter.kt | 13 +- .../bravedns/adapter/OneWgConfigAdapter.kt | 1 - .../adapter/RethinkEndpointAdapter.kt | 16 +- .../bravedns/adapter/RethinkLogAdapter.kt | 5 +- .../adapter/SummaryStatisticsAdapter.kt | 8 +- .../bravedns/adapter/WgIncludeAppsAdapter.kt | 13 +- .../LocalBlocklistCoordinator.kt | 54 ++-- .../RemoteBlocklistCoordinator.kt | 21 +- .../customdownloader/RetrofitManager.kt | 16 +- .../bravedns/download/AppDownloadManager.kt | 34 ++- .../download/BlocklistDownloadHelper.kt | 57 ++-- .../bravedns/download/DownloadWatcher.kt | 30 ++- .../bravedns/download/FileHandleWorker.kt | 37 ++- .../receiver/BraveAutoStartReceiver.kt | 13 +- .../receiver/NotificationActionReceiver.kt | 5 +- .../scheduler/BlocklistUpdateCheckJob.kt | 5 +- .../bravedns/scheduler/BugReportCollector.kt | 16 +- .../bravedns/scheduler/BugReportZipper.kt | 11 +- .../bravedns/scheduler/PaymentWorker.kt | 30 +-- .../bravedns/scheduler/PurgeConnectionLogs.kt | 8 +- .../bravedns/scheduler/WorkScheduler.kt | 37 +-- .../celzero/bravedns/service/ProxyManager.kt | 30 +-- .../bravedns/service/TcpProxyHelper.kt | 47 ++-- .../bravedns/service/WireguardManager.kt | 131 ++++----- .../celzero/bravedns/ui/HomeScreenActivity.kt | 45 ++-- .../bravedns/ui/NotificationHandlerDialog.kt | 5 +- .../bravedns/ui/activity/CheckoutActivity.kt | 19 +- .../ui/activity/MiscSettingsActivity.kt | 25 +- .../ui/activity/ProxySettingsActivity.kt | 21 +- .../ui/activity/TcpProxyMainActivity.kt | 7 +- .../UniversalFirewallSettingsActivity.kt | 15 +- .../ui/activity/WgConfigDetailActivity.kt | 5 +- .../ui/activity/WgConfigEditorActivity.kt | 7 +- .../bravedns/ui/activity/WgMainActivity.kt | 17 +- .../bottomsheet/AppDomainRulesBottomSheet.kt | 7 +- .../ui/bottomsheet/AppIpRulesBottomSheet.kt | 7 +- .../bottomsheet/BackupRestoreBottomSheet.kt | 19 +- .../ui/bottomsheet/ConnTrackerBottomSheet.kt | 30 +-- .../ui/bottomsheet/DnsBlocklistBottomSheet.kt | 54 ++-- .../HomeScreenSettingBottomSheet.kt | 6 +- .../bottomsheet/LocalBlocklistsBottomSheet.kt | 15 +- .../ui/bottomsheet/RethinkLogBottomSheet.kt | 9 +- .../bravedns/ui/dialog/WgAddPeerDialog.kt | 5 +- .../bravedns/ui/dialog/WgIncludeAppsDialog.kt | 9 +- .../bravedns/ui/fragment/AboutFragment.kt | 16 +- .../ui/fragment/DnsProxyListFragment.kt | 16 +- .../ui/fragment/DnsSettingsFragment.kt | 4 +- .../ui/fragment/HomeScreenFragment.kt | 27 +- .../ui/fragment/RethinkBlocklistFragment.kt | 20 +- .../ui/fragment/RethinkListFragment.kt | 16 +- .../util/BackgroundAccessibilityService.kt | 15 +- .../bravedns/util/QrCodeFromFileScanner.kt | 13 +- .../bravedns/util/RemoteFileTagUtil.kt | 10 +- .../celzero/bravedns/util/TunnelImporter.kt | 8 +- .../java/com/celzero/bravedns/util/UIUtils.kt | 12 +- .../bravedns/provider/ApplicationProvider.kt | 29 +- .../bravedns/provider/BlocklistProvider.kt | 23 +- .../bravedns/provider/DomainRuleProvider.kt | 56 ++-- .../celzero/bravedns/service/ProxyManager.kt | 8 + .../celzero/bravedns/backup/BackupAgent.kt | 7 +- .../celzero/bravedns/backup/BackupHelper.kt | 5 +- .../celzero/bravedns/backup/RestoreAgent.kt | 73 +++-- .../com/celzero/bravedns/data/AppConfig.kt | 8 +- .../celzero/bravedns/database/LogDatabase.kt | 2 +- .../bravedns/database/RefreshDatabase.kt | 36 ++- .../bravedns/glide/FavIconDownloader.kt | 14 +- .../celzero/bravedns/net/go/GoVpnAdapter.kt | 255 +++++++++--------- .../bravedns/net/manager/ConnectionTracer.kt | 30 +-- .../bravedns/scheduler/DataUsageUpdater.kt | 11 +- .../bravedns/scheduler/RefreshAppsJob.kt | 6 +- .../bravedns/scheduler/ScheduleManager.kt | 13 +- .../bravedns/service/BraveVPNService.kt | 224 +++++++-------- .../bravedns/service/ConnectionMonitor.kt | 116 ++++---- .../bravedns/service/DomainRulesManager.kt | 11 +- .../bravedns/service/EncryptedFileManager.kt | 21 +- .../bravedns/service/FirewallManager.kt | 28 +- .../com/celzero/bravedns/service/IPTracker.kt | 9 +- .../bravedns/service/IpRulesManager.kt | 24 +- .../celzero/bravedns/service/PauseTimer.kt | 9 +- .../service/RethinkBlocklistManager.kt | 28 +- .../celzero/bravedns/service/VpnController.kt | 13 +- .../java/com/celzero/bravedns/util/IPUtil.kt | 12 +- .../java/com/celzero/bravedns/util/Logger.kt | 90 ++++--- .../celzero/bravedns/util/NetLogBatcher.kt | 27 +- .../com/celzero/bravedns/util/OrbotHelper.kt | 58 ++-- .../com/celzero/bravedns/util/Utilities.kt | 73 +++-- 97 files changed, 1166 insertions(+), 1363 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/NonStoreAppUpdater.kt b/app/src/full/java/com/celzero/bravedns/NonStoreAppUpdater.kt index 52db1f3e0..64120c0cc 100644 --- a/app/src/full/java/com/celzero/bravedns/NonStoreAppUpdater.kt +++ b/app/src/full/java/com/celzero/bravedns/NonStoreAppUpdater.kt @@ -15,8 +15,8 @@ */ package com.celzero.bravedns +import Logger.LOG_TAG_APP_UPDATE import android.app.Activity -import android.util.Log import com.celzero.bravedns.customdownloader.RetrofitManager import com.celzero.bravedns.service.AppUpdater import com.celzero.bravedns.service.PersistentState @@ -25,7 +25,6 @@ import com.celzero.bravedns.util.Constants.Companion.JSON_LATEST import com.celzero.bravedns.util.Constants.Companion.JSON_UPDATE import com.celzero.bravedns.util.Constants.Companion.JSON_VERSION import com.celzero.bravedns.util.Constants.Companion.UPDATE_CHECK_RESPONSE_VERSION -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_APP_UPDATE import okhttp3.Call import okhttp3.Callback import okhttp3.Request @@ -43,7 +42,7 @@ class NonStoreAppUpdater( activity: Activity, listener: AppUpdater.InstallStateListener ) { - Log.i(LOG_TAG_APP_UPDATE, "Beginning update check") + Logger.i(LOG_TAG_APP_UPDATE, "Beginning update check") val url = baseUrl + BuildConfig.VERSION_CODE val client = RetrofitManager.okHttpClient() @@ -54,7 +53,7 @@ class NonStoreAppUpdater( .enqueue( object : Callback { override fun onFailure(call: Call, e: IOException) { - Log.i( + Logger.i( LOG_TAG_APP_UPDATE, "onFailure - ${call.isCanceled()}, ${call.isExecuted()}" ) @@ -82,7 +81,7 @@ class NonStoreAppUpdater( response.close() client.connectionPool.evictAll() - Log.i( + Logger.i( LOG_TAG_APP_UPDATE, "Server response for the new version download is $shouldUpdate (json version: $version), version number: $latest" ) diff --git a/app/src/full/java/com/celzero/bravedns/RethinkDnsApplication.kt b/app/src/full/java/com/celzero/bravedns/RethinkDnsApplication.kt index cf3616337..4a4ff29ca 100644 --- a/app/src/full/java/com/celzero/bravedns/RethinkDnsApplication.kt +++ b/app/src/full/java/com/celzero/bravedns/RethinkDnsApplication.kt @@ -1,12 +1,11 @@ package com.celzero.bravedns +import Logger.LOG_TAG_SCHEDULER import android.app.Application import android.content.pm.ApplicationInfo import android.os.StrictMode -import android.util.Log import com.celzero.bravedns.scheduler.ScheduleManager import com.celzero.bravedns.scheduler.WorkScheduler -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_SCHEDULER import org.koin.android.ext.android.get import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger @@ -46,7 +45,7 @@ class RethinkDnsApplication : Application() { turnOnStrictMode() - if (DEBUG) Log.d(LOG_TAG_SCHEDULER, "Schedule job") + Logger.d(LOG_TAG_SCHEDULER, "Schedule job") get().scheduleAppExitInfoCollectionJob() // database refresh is used in both headless and main project get().scheduleDatabaseRefreshJob() diff --git a/app/src/full/java/com/celzero/bravedns/adapter/AppWiseDomainsAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/AppWiseDomainsAdapter.kt index 5f7f59d5e..8d9e9ca83 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/AppWiseDomainsAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/AppWiseDomainsAdapter.kt @@ -15,10 +15,10 @@ */ package com.celzero.bravedns.adapter +import Logger.LOG_TAG_UI import android.content.Context import android.content.res.ColorStateList import android.os.Bundle -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -32,7 +32,6 @@ import com.celzero.bravedns.data.AppConnection import com.celzero.bravedns.databinding.ListItemAppDomainDetailsBinding import com.celzero.bravedns.service.DomainRulesManager import com.celzero.bravedns.ui.bottomsheet.AppDomainRulesBottomSheet -import com.celzero.bravedns.util.Logger import com.celzero.bravedns.util.UIUtils.fetchColor import com.celzero.bravedns.util.Utilities.removeBeginningTrailingCommas @@ -118,7 +117,7 @@ class AppWiseDomainsAdapter( private fun openBottomSheet(appConn: AppConnection) { if (context !is AppCompatActivity) { - Log.w(Logger.LOG_TAG_UI, "Error opening the app conn bottom sheet") + Logger.w(LOG_TAG_UI, "Error opening the app conn bottom sheet") return } diff --git a/app/src/full/java/com/celzero/bravedns/adapter/AppWiseIpsAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/AppWiseIpsAdapter.kt index 8a07c6ee7..c8003b61c 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/AppWiseIpsAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/AppWiseIpsAdapter.kt @@ -15,10 +15,10 @@ */ package com.celzero.bravedns.adapter +import Logger.LOG_TAG_UI import android.content.Context import android.content.res.ColorStateList import android.os.Bundle -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -32,7 +32,6 @@ import com.celzero.bravedns.data.AppConnection import com.celzero.bravedns.databinding.ListItemAppIpDetailsBinding import com.celzero.bravedns.service.IpRulesManager import com.celzero.bravedns.ui.bottomsheet.AppIpRulesBottomSheet -import com.celzero.bravedns.util.Logger import com.celzero.bravedns.util.UIUtils.fetchColor import com.celzero.bravedns.util.Utilities.removeBeginningTrailingCommas @@ -96,7 +95,7 @@ class AppWiseIpsAdapter(val context: Context, val lifecycleOwner: LifecycleOwner private fun openBottomSheet(appConn: AppConnection) { if (context !is AppCompatActivity) { - Log.w(Logger.LOG_TAG_UI, "Error opening the app conn bottom sheet") + Logger.w(LOG_TAG_UI, "Error opening the app conn bottom sheet") return } diff --git a/app/src/full/java/com/celzero/bravedns/adapter/ConnectionTrackerAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/ConnectionTrackerAdapter.kt index fd63c34fe..748f02ffa 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/ConnectionTrackerAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/ConnectionTrackerAdapter.kt @@ -16,10 +16,10 @@ limitations under the License. package com.celzero.bravedns.adapter +import Logger.LOG_TAG_UI import android.content.Context import android.graphics.drawable.Drawable import android.os.Bundle -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -41,16 +41,15 @@ import com.celzero.bravedns.service.VpnController import com.celzero.bravedns.ui.bottomsheet.ConnTrackerBottomSheet import com.celzero.bravedns.util.Constants.Companion.TIME_FORMAT_1 import com.celzero.bravedns.util.KnownPorts -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_UI import com.celzero.bravedns.util.Protocol import com.celzero.bravedns.util.UIUtils.getDurationInHumanReadableFormat import com.celzero.bravedns.util.Utilities import com.celzero.bravedns.util.Utilities.getIcon import com.google.gson.Gson +import java.util.Locale import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -import java.util.Locale class ConnectionTrackerAdapter(private val context: Context) : PagingDataAdapter( @@ -114,7 +113,7 @@ class ConnectionTrackerAdapter(private val context: Context) : private fun openBottomSheet(ct: ConnectionTracker) { if (context !is FragmentActivity) { - Log.w(LOG_TAG_UI, "err opening the connection tracker bottomsheet") + Logger.w(LOG_TAG_UI, "err opening the connection tracker bottomsheet") return } diff --git a/app/src/full/java/com/celzero/bravedns/adapter/CustomDomainAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/CustomDomainAdapter.kt index a295b75dd..ac4caa77f 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/CustomDomainAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/CustomDomainAdapter.kt @@ -15,11 +15,11 @@ */ package com.celzero.bravedns.adapter +import Logger.LOG_TAG_UI import android.content.Context import android.content.res.ColorStateList import android.graphics.drawable.Drawable import android.text.format.DateUtils -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -44,7 +44,6 @@ import com.celzero.bravedns.service.DomainRulesManager.isWildCardEntry import com.celzero.bravedns.service.FirewallManager import com.celzero.bravedns.ui.activity.CustomRulesActivity import com.celzero.bravedns.util.Constants -import com.celzero.bravedns.util.Logger import com.celzero.bravedns.util.UIUtils.fetchColor import com.celzero.bravedns.util.UIUtils.fetchToggleBtnColors import com.celzero.bravedns.util.Utilities @@ -109,7 +108,7 @@ class CustomDomainAdapter(val context: Context, val rule: CustomRulesActivity.RU } else if (holder is CustomDomainViewHolderWithoutHeader) { holder.update(customDomain) } else { - Log.w(Logger.LOG_TAG_UI, "unknown view holder in CustomDomainRulesAdapter") + Logger.w(LOG_TAG_UI, "unknown view holder in CustomDomainRulesAdapter") return } } diff --git a/app/src/full/java/com/celzero/bravedns/adapter/CustomIpAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/CustomIpAdapter.kt index f8433d02e..86672f2b9 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/CustomIpAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/CustomIpAdapter.kt @@ -15,11 +15,11 @@ */ package com.celzero.bravedns.adapter +import Logger.LOG_TAG_UI import android.content.Context import android.content.res.ColorStateList import android.graphics.drawable.Drawable import android.text.format.DateUtils -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -43,7 +43,6 @@ import com.celzero.bravedns.service.FirewallManager import com.celzero.bravedns.service.IpRulesManager import com.celzero.bravedns.ui.activity.CustomRulesActivity import com.celzero.bravedns.util.Constants.Companion.UID_EVERYBODY -import com.celzero.bravedns.util.Logger import com.celzero.bravedns.util.UIUtils.fetchColor import com.celzero.bravedns.util.UIUtils.fetchToggleBtnColors import com.celzero.bravedns.util.Utilities @@ -104,7 +103,7 @@ class CustomIpAdapter(private val context: Context, private val type: CustomRule holder.update(customIp) } else -> { - Log.w(Logger.LOG_TAG_UI, "unknown view holder in CustomDomainRulesAdapter") + Logger.w(LOG_TAG_UI, "unknown view holder in CustomDomainRulesAdapter") return } } diff --git a/app/src/full/java/com/celzero/bravedns/adapter/DnsQueryAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/DnsQueryAdapter.kt index 4ce3693be..7cce4aa8c 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/DnsQueryAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/DnsQueryAdapter.kt @@ -16,10 +16,11 @@ limitations under the License. package com.celzero.bravedns.adapter +import Logger.LOG_TAG_DNS +import Logger.LOG_TAG_UI import android.content.Context import android.graphics.drawable.Drawable import android.os.Bundle -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -36,13 +37,10 @@ import com.bumptech.glide.request.target.CustomViewTarget import com.bumptech.glide.request.transition.DrawableCrossFadeFactory import com.bumptech.glide.request.transition.Transition import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.database.DnsLog import com.celzero.bravedns.databinding.TransactionRowBinding import com.celzero.bravedns.glide.FavIconDownloader import com.celzero.bravedns.ui.bottomsheet.DnsBlocklistBottomSheet -import com.celzero.bravedns.util.Logger -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_DNS_LOG import com.celzero.bravedns.util.UIUtils.fetchColor import com.google.gson.Gson @@ -157,8 +155,8 @@ class DnsQueryAdapter(val context: Context, val loadFavIcon: Boolean) : private fun openBottomSheet(dnsLog: DnsLog) { if (context !is FragmentActivity) { - Log.w( - Logger.LOG_TAG_UI, + Logger.w( + LOG_TAG_UI, "Can not open bottom sheet. Context is not attached to activity" ) return @@ -212,7 +210,7 @@ class DnsQueryAdapter(val context: Context, val loadFavIcon: Boolean) : } ) } catch (e: Exception) { - if (DEBUG) Log.d(LOG_TAG_DNS_LOG, "Error loading icon, load flag instead") + Logger.d(LOG_TAG_DNS, "Error loading icon, load flag instead") displayDuckduckgoFavIcon(duckduckGoUrl, duckduckgoDomainURL) } } @@ -259,7 +257,7 @@ class DnsQueryAdapter(val context: Context, val loadFavIcon: Boolean) : } ) } catch (e: Exception) { - if (DEBUG) Log.d(LOG_TAG_DNS_LOG, "Error loading icon, load flag instead") + Logger.d(LOG_TAG_DNS, "Error loading icon, load flag instead") showFlag() hideFavIcon() } diff --git a/app/src/full/java/com/celzero/bravedns/adapter/DoTEndpointAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/DoTEndpointAdapter.kt index 4dcba76c9..31f98d33e 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/DoTEndpointAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/DoTEndpointAdapter.kt @@ -16,9 +16,9 @@ limitations under the License. package com.celzero.bravedns.adapter +import Logger.LOG_TAG_DNS import android.content.Context import android.content.DialogInterface -import android.util.Log import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Toast @@ -31,12 +31,10 @@ import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import backend.Backend import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.data.AppConfig import com.celzero.bravedns.database.DoTEndpoint import com.celzero.bravedns.databinding.ListItemEndpointBinding import com.celzero.bravedns.service.VpnController -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_DNS import com.celzero.bravedns.util.UIUtils.clipboardCopy import com.celzero.bravedns.util.UIUtils.getDnsStatusStringRes import com.celzero.bravedns.util.Utilities @@ -167,11 +165,10 @@ class DoTEndpointAdapter(private val context: Context, private val appConfig: Ap } private fun updateConnection(endpoint: DoTEndpoint) { - if (DEBUG) - Log.d( - LOG_TAG_DNS, - "on dot change - ${endpoint.name}, ${endpoint.url}, ${endpoint.isSelected}" - ) + Logger.d( + LOG_TAG_DNS, + "on dot change - ${endpoint.name}, ${endpoint.url}, ${endpoint.isSelected}" + ) io { endpoint.isSelected = true appConfig.handleDoTChanges(endpoint) diff --git a/app/src/full/java/com/celzero/bravedns/adapter/DohEndpointAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/DohEndpointAdapter.kt index 4cab696b0..72aca4ada 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/DohEndpointAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/DohEndpointAdapter.kt @@ -16,9 +16,9 @@ limitations under the License. package com.celzero.bravedns.adapter +import Logger.LOG_TAG_DNS import android.content.Context import android.content.DialogInterface -import android.util.Log import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Toast @@ -31,12 +31,10 @@ import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import backend.Backend import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.data.AppConfig import com.celzero.bravedns.database.DoHEndpoint import com.celzero.bravedns.databinding.ListItemEndpointBinding import com.celzero.bravedns.service.VpnController -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_DNS import com.celzero.bravedns.util.UIUtils.clipboardCopy import com.celzero.bravedns.util.UIUtils.getDnsStatusStringRes import com.celzero.bravedns.util.Utilities @@ -166,11 +164,10 @@ class DohEndpointAdapter(private val context: Context, private val appConfig: Ap } private fun updateConnection(endpoint: DoHEndpoint) { - if (DEBUG) - Log.d( - LOG_TAG_DNS, - "on doh change - ${endpoint.dohName}, ${endpoint.dohURL}, ${endpoint.isSelected}" - ) + Logger.d( + LOG_TAG_DNS, + "on doh change - ${endpoint.dohName}, ${endpoint.dohURL}, ${endpoint.isSelected}" + ) io { endpoint.isSelected = true appConfig.handleDoHChanges(endpoint) diff --git a/app/src/full/java/com/celzero/bravedns/adapter/DomainRulesBtmSheetAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/DomainRulesBtmSheetAdapter.kt index c7211670e..d60c16358 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/DomainRulesBtmSheetAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/DomainRulesBtmSheetAdapter.kt @@ -15,8 +15,8 @@ */ package com.celzero.bravedns.adapter +import Logger.LOG_TAG_FIREWALL import android.content.Context -import android.util.Log import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.content.ContextCompat @@ -26,7 +26,6 @@ import androidx.recyclerview.widget.RecyclerView import com.celzero.bravedns.R import com.celzero.bravedns.databinding.DomainItemBottomSheetBinding import com.celzero.bravedns.service.DomainRulesManager -import com.celzero.bravedns.util.Logger import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -95,8 +94,8 @@ class DomainRulesBtmSheetAdapter( } private fun applyDomainRule(domain: String, domainRuleStatus: DomainRulesManager.Status) { - Log.i( - Logger.LOG_TAG_FIREWALL, + Logger.i( + LOG_TAG_FIREWALL, "Apply domain rule for $domain, ${domainRuleStatus.name}" ) io { diff --git a/app/src/full/java/com/celzero/bravedns/adapter/ODoHEndpointAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/ODoHEndpointAdapter.kt index 1069330a0..6f566a1a5 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/ODoHEndpointAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/ODoHEndpointAdapter.kt @@ -16,9 +16,9 @@ limitations under the License. package com.celzero.bravedns.adapter +import Logger.LOG_TAG_DNS import android.content.Context import android.content.DialogInterface -import android.util.Log import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Toast @@ -31,12 +31,10 @@ import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import backend.Backend import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.data.AppConfig import com.celzero.bravedns.database.ODoHEndpoint import com.celzero.bravedns.databinding.ListItemEndpointBinding import com.celzero.bravedns.service.VpnController -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_DNS import com.celzero.bravedns.util.UIUtils.clipboardCopy import com.celzero.bravedns.util.UIUtils.getDnsStatusStringRes import com.celzero.bravedns.util.Utilities @@ -158,11 +156,10 @@ class ODoHEndpointAdapter(private val context: Context, private val appConfig: A } private fun updateConnection(endpoint: ODoHEndpoint) { - if (DEBUG) - Log.d( - LOG_TAG_DNS, - "on-ODoH change ${endpoint.name}, ${endpoint.proxy}, ${endpoint.resolver}, ${endpoint.isSelected}" - ) + Logger.d( + LOG_TAG_DNS, + "on-ODoH change ${endpoint.name}, ${endpoint.proxy}, ${endpoint.resolver}, ${endpoint.isSelected}" + ) io { endpoint.isSelected = true appConfig.handleODoHChanges(endpoint) diff --git a/app/src/full/java/com/celzero/bravedns/adapter/OneWgConfigAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/OneWgConfigAdapter.kt index 875c962e9..e690b3039 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/OneWgConfigAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/OneWgConfigAdapter.kt @@ -17,7 +17,6 @@ package com.celzero.bravedns.adapter import android.content.Context import android.content.Intent -import android.os.SystemClock import android.text.format.DateUtils import android.view.LayoutInflater import android.view.View diff --git a/app/src/full/java/com/celzero/bravedns/adapter/RethinkEndpointAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/RethinkEndpointAdapter.kt index 2666929bb..b950ab289 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/RethinkEndpointAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/RethinkEndpointAdapter.kt @@ -16,10 +16,10 @@ package com.celzero.bravedns.adapter +import Logger.LOG_TAG_DNS import android.content.Context import android.content.DialogInterface import android.content.Intent -import android.util.Log import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Toast @@ -32,14 +32,12 @@ import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import backend.Backend import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.data.AppConfig import com.celzero.bravedns.database.RethinkDnsEndpoint import com.celzero.bravedns.databinding.RethinkEndpointListItemBinding import com.celzero.bravedns.service.RethinkBlocklistManager import com.celzero.bravedns.service.VpnController import com.celzero.bravedns.ui.activity.ConfigureRethinkBasicActivity -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_DNS import com.celzero.bravedns.util.UIUtils import com.celzero.bravedns.util.UIUtils.clipboardCopy import com.celzero.bravedns.util.Utilities @@ -120,7 +118,8 @@ class RethinkEndpointAdapter(private val context: Context, private val appConfig if (endpoint.isActive && VpnController.hasTunnel()) { keepSelectedStatusUpdated(endpoint) } else if (endpoint.isActive) { - b.rethinkEndpointListUrlExplanation.text = context.getString(R.string.rt_filter_parent_selected) + b.rethinkEndpointListUrlExplanation.text = + context.getString(R.string.rt_filter_parent_selected) } else { b.rethinkEndpointListUrlExplanation.text = "" } @@ -181,11 +180,10 @@ class RethinkEndpointAdapter(private val context: Context, private val appConfig } private fun updateConnection(endpoint: RethinkDnsEndpoint) { - if (DEBUG) - Log.d( - LOG_TAG_DNS, - "on rethink dns change - ${endpoint.name}, ${endpoint.url}, ${endpoint.isActive}" - ) + Logger.d( + LOG_TAG_DNS, + "on rethink dns change - ${endpoint.name}, ${endpoint.url}, ${endpoint.isActive}" + ) io { endpoint.isActive = true diff --git a/app/src/full/java/com/celzero/bravedns/adapter/RethinkLogAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/RethinkLogAdapter.kt index 16f2ecec6..e71761bce 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/RethinkLogAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/RethinkLogAdapter.kt @@ -16,10 +16,10 @@ limitations under the License. package com.celzero.bravedns.adapter +import Logger.LOG_TAG_UI import android.content.Context import android.graphics.drawable.Drawable import android.os.Bundle -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -42,7 +42,6 @@ import com.celzero.bravedns.ui.bottomsheet.ConnTrackerBottomSheet import com.celzero.bravedns.ui.bottomsheet.RethinkLogBottomSheet import com.celzero.bravedns.util.Constants.Companion.TIME_FORMAT_1 import com.celzero.bravedns.util.KnownPorts -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_UI import com.celzero.bravedns.util.Protocol import com.celzero.bravedns.util.UIUtils.getDurationInHumanReadableFormat import com.celzero.bravedns.util.Utilities @@ -114,7 +113,7 @@ class RethinkLogAdapter(private val context: Context) : private fun openBottomSheet(log: RethinkLog) { if (context !is FragmentActivity) { - Log.w(LOG_TAG_UI, "Error opening the connection tracker bottomsheet") + Logger.w(LOG_TAG_UI, "err opening the connection tracker bottomsheet") return } diff --git a/app/src/full/java/com/celzero/bravedns/adapter/SummaryStatisticsAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/SummaryStatisticsAdapter.kt index b19b11105..8c3e98b87 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/SummaryStatisticsAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/SummaryStatisticsAdapter.kt @@ -15,10 +15,10 @@ */ package com.celzero.bravedns.adapter +import Logger.LOG_TAG_DNS import android.content.Context import android.content.Intent import android.graphics.drawable.Drawable -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -36,7 +36,6 @@ import com.bumptech.glide.request.target.CustomViewTarget import com.bumptech.glide.request.transition.DrawableCrossFadeFactory import com.bumptech.glide.request.transition.Transition import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.data.AppConfig import com.celzero.bravedns.data.AppConnection import com.celzero.bravedns.database.AppInfo @@ -48,7 +47,6 @@ import com.celzero.bravedns.ui.activity.AppInfoActivity import com.celzero.bravedns.ui.activity.NetworkLogsActivity import com.celzero.bravedns.ui.fragment.SummaryStatisticsFragment.SummaryStatisticsType import com.celzero.bravedns.util.Constants -import com.celzero.bravedns.util.Logger import com.celzero.bravedns.util.UIUtils.fetchToggleBtnColors import com.celzero.bravedns.util.UIUtils.getCountryNameFromFlag import com.celzero.bravedns.util.Utilities @@ -554,7 +552,7 @@ class SummaryStatisticsAdapter( } ) } catch (e: Exception) { - if (DEBUG) Log.d(Logger.LOG_TAG_DNS_LOG, "Error loading icon, load flag instead") + Logger.d(LOG_TAG_DNS, "Error loading icon, load flag instead") displayDuckduckgoFavIcon(duckDuckGoUrl, duckduckgoDomainURL) } } @@ -601,7 +599,7 @@ class SummaryStatisticsAdapter( } ) } catch (e: Exception) { - if (DEBUG) Log.d(Logger.LOG_TAG_DNS_LOG, "Error loading icon, load flag instead") + Logger.d(LOG_TAG_DNS, "err loading icon, load flag instead") showFlag() hideFavIcon() } diff --git a/app/src/full/java/com/celzero/bravedns/adapter/WgIncludeAppsAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/WgIncludeAppsAdapter.kt index 61c1ac12d..c04982a1e 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/WgIncludeAppsAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/WgIncludeAppsAdapter.kt @@ -15,10 +15,10 @@ */ package com.celzero.bravedns.adapter +import Logger.LOG_TAG_PROXY import android.content.Context import android.content.DialogInterface import android.graphics.drawable.Drawable -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -35,7 +35,6 @@ import com.celzero.bravedns.database.ProxyApplicationMapping import com.celzero.bravedns.databinding.ListItemWgIncludeAppsBinding import com.celzero.bravedns.service.FirewallManager import com.celzero.bravedns.service.ProxyManager -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_PROXY import com.celzero.bravedns.util.UIUtils import com.celzero.bravedns.util.Utilities.getDefaultIcon import com.celzero.bravedns.util.Utilities.getIcon @@ -94,7 +93,7 @@ class WgIncludeAppsAdapter( fun update(mapping: ProxyApplicationMapping) { b.wgIncludeAppListApkLabelTv.text = mapping.appName - Log.i(LOG_TAG_PROXY, "add ${mapping.appName} to ${mapping.proxyId} from $proxyId") + Logger.i(LOG_TAG_PROXY, "add ${mapping.appName} to ${mapping.proxyId} from $proxyId") if (mapping.proxyId == "") { b.wgIncludeAppAppDescTv.text = "" @@ -121,14 +120,14 @@ class WgIncludeAppsAdapter( private fun setupClickListeners(mapping: ProxyApplicationMapping, isIncluded: Boolean) { b.wgIncludeCard.setOnClickListener { - Log.i(LOG_TAG_PROXY, "wgIncludeAppListContainer- ${mapping.appName}, $isIncluded") + Logger.i(LOG_TAG_PROXY, "wgIncludeAppListContainer- ${mapping.appName}, $isIncluded") updateInterfaceDetails(mapping, !isIncluded) } b.wgIncludeAppListCheckbox.setOnCheckedChangeListener(null) b.wgIncludeAppListCheckbox.setOnClickListener { val isAdded = mapping.proxyId == proxyId - Log.i(LOG_TAG_PROXY, "wgIncludeAppListCheckbox - ${mapping.appName}, $isAdded") + Logger.i(LOG_TAG_PROXY, "wgIncludeAppListCheckbox - ${mapping.appName}, $isAdded") updateInterfaceDetails(mapping, !isAdded) } } @@ -167,11 +166,11 @@ class WgIncludeAppsAdapter( io { if (include) { ProxyManager.updateProxyIdForApp(mapping.uid, proxyId, proxyName) - Log.i(LOG_TAG_PROXY, "Included apps: ${mapping.uid}, $proxyId, $proxyName") + Logger.i(LOG_TAG_PROXY, "Included apps: ${mapping.uid}, $proxyId, $proxyName") } else { ProxyManager.setNoProxyForApp(mapping.uid) uiCtx { b.wgIncludeAppListCheckbox.isChecked = false } - Log.i(LOG_TAG_PROXY, "Removed apps: ${mapping.uid}, $proxyId, $proxyName") + Logger.i(LOG_TAG_PROXY, "Removed apps: ${mapping.uid}, $proxyId, $proxyName") } } } diff --git a/app/src/full/java/com/celzero/bravedns/customdownloader/LocalBlocklistCoordinator.kt b/app/src/full/java/com/celzero/bravedns/customdownloader/LocalBlocklistCoordinator.kt index a7fe4f47b..e190c5766 100644 --- a/app/src/full/java/com/celzero/bravedns/customdownloader/LocalBlocklistCoordinator.kt +++ b/app/src/full/java/com/celzero/bravedns/customdownloader/LocalBlocklistCoordinator.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.customdownloader +import Logger.LOG_TAG_DOWNLOAD import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent @@ -22,7 +23,6 @@ import android.content.Context import android.content.Intent import android.net.VpnService import android.os.SystemClock -import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat import androidx.work.CoroutineWorker @@ -38,7 +38,6 @@ import com.celzero.bravedns.ui.HomeScreenActivity import com.celzero.bravedns.util.Constants import com.celzero.bravedns.util.Constants.Companion.INIT_TIME_MS import com.celzero.bravedns.util.Constants.Companion.LOCAL_BLOCKLIST_DOWNLOAD_FOLDER_NAME -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_DOWNLOAD import com.celzero.bravedns.util.UIUtils import com.celzero.bravedns.util.Utilities import com.celzero.bravedns.util.Utilities.blocklistDownloadBasePath @@ -83,7 +82,7 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame } override suspend fun doWork(): Result { - if (DEBUG) Log.d(LOG_TAG_DOWNLOAD, "Local blocklist download started") + Logger.d(LOG_TAG_DOWNLOAD, "Local blocklist download started") try { val startTime = inputData.getLong("workerStartTime", 0) val timestamp = inputData.getLong("blocklistTimestamp", 0) @@ -110,14 +109,14 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame } } } catch (ex: CancellationException) { - Log.e( + Logger.e( LOG_TAG_DOWNLOAD, "Local blocklist download, received cancellation exception: ${ex.message}", ex ) notifyDownloadCancelled(context) } catch (ex: Exception) { - Log.e( + Logger.e( LOG_TAG_DOWNLOAD, "Local blocklist download, received cancellation exception: ${ex.message}", ex @@ -154,7 +153,7 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame // check if all the files are downloaded, as of now the check if for only number of files // downloaded. TODO: Later add checksum matching as well if (!isDownloadComplete(file)) { - Log.e(LOG_TAG_DOWNLOAD, "Local blocklist validation failed for timestamp: $timestamp") + Logger.e(LOG_TAG_DOWNLOAD, "Local blocklist validation failed for timestamp: $timestamp") notifyDownloadFailure(context) return false } @@ -162,7 +161,7 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame if (isDownloadCancelled()) return false if (!moveLocalBlocklistFiles(context, timestamp)) { - Log.e(LOG_TAG_DOWNLOAD, "Issue while moving the downloaded files: $timestamp") + Logger.e(LOG_TAG_DOWNLOAD, "Issue while moving the downloaded files: $timestamp") notifyDownloadFailure(context) return false } @@ -170,7 +169,7 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame if (isDownloadCancelled()) return false if (!isLocalBlocklistDownloadValid(context, timestamp)) { - Log.e(LOG_TAG_DOWNLOAD, "Invalid download for local blocklist files: $timestamp") + Logger.e(LOG_TAG_DOWNLOAD, "Invalid download for local blocklist files: $timestamp") notifyDownloadFailure(context) return false } @@ -179,7 +178,7 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame val result = updateTagsToDb(timestamp) if (!result) { - Log.e(LOG_TAG_DOWNLOAD, "Invalid download for local blocklist files: $timestamp") + Logger.e(LOG_TAG_DOWNLOAD, "Invalid download for local blocklist files: $timestamp") notifyDownloadFailure(context) return false } @@ -191,7 +190,7 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame private fun isDownloadCancelled(): Boolean { // return if the download is cancelled by the user // sometimes the worker cancellation is not received as exception - Log.i(LOG_TAG_DOWNLOAD, "Download cancel check, isStopped? $isStopped") + Logger.i(LOG_TAG_DOWNLOAD, "Download cancel check, isStopped? $isStopped") return isStopped } @@ -210,7 +209,7 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame } return file } catch (ex: IOException) { - Log.e(LOG_TAG_DOWNLOAD, "Error creating temp folder $timestamp, ${ex.message}", ex) + Logger.e(LOG_TAG_DOWNLOAD, "Error creating temp folder $timestamp, ${ex.message}", ex) } return null } @@ -235,13 +234,13 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame return downloadFile(context, response.body(), fileName) } } catch (e: Exception) { - Log.e(LOG_TAG_DOWNLOAD, "Error in startFileDownload: ${e.message}", e) + Logger.e(LOG_TAG_DOWNLOAD, "Error in startFileDownload: ${e.message}", e) } return if (isRetryRequired(retryCount)) { - Log.i(LOG_TAG_DOWNLOAD, "retrying download($url) $fileName, count: $retryCount") + Logger.i(LOG_TAG_DOWNLOAD, "retrying download($url) $fileName, count: $retryCount") startFileDownload(context, url, fileName, retryCount + 1) } else { - Log.i(LOG_TAG_DOWNLOAD, "download failed for $fileName, retry: $retryCount") + Logger.i(LOG_TAG_DOWNLOAD, "download failed for $fileName, retry: $retryCount") false } } @@ -286,10 +285,10 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame output.write(buf, 0, bytesRead) } output.flush() - Log.i(LOG_TAG_DOWNLOAD, "$fileName > ${downloadedMB}MB downloaded") + Logger.i(LOG_TAG_DOWNLOAD, "$fileName > ${downloadedMB}MB downloaded") return true } catch (e: Exception) { - Log.e(LOG_TAG_DOWNLOAD, "$fileName download err: ${e.message}", e) + Logger.e(LOG_TAG_DOWNLOAD, "$fileName download err: ${e.message}", e) } finally { output?.close() input?.close() @@ -305,7 +304,7 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame var result = false var total: Int? = 0 try { - if (DEBUG) Log.d(LOG_TAG_DOWNLOAD, "Local block list validation: ${dir.absolutePath}") + Logger.d(LOG_TAG_DOWNLOAD, "Local block list validation: ${dir.absolutePath}") total = if (dir.isDirectory) { @@ -315,11 +314,10 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame } result = Constants.ONDEVICE_BLOCKLISTS_IN_APP.count() == total } catch (e: Exception) { - Log.w(LOG_TAG_DOWNLOAD, "Local block list validation failed: ${e.message}", e) + Logger.w(LOG_TAG_DOWNLOAD, "Local block list validation failed: ${e.message}", e) } - if (DEBUG) - Log.d( + Logger.d( LOG_TAG_DOWNLOAD, "Valid on-device blocklist in folder (${dir.name}) download? $result, files: $total, dir? ${dir.isDirectory}" ) @@ -333,7 +331,7 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame File(tempDownloadBasePath(context, LOCAL_BLOCKLIST_DOWNLOAD_FOLDER_NAME, timestamp)) if (!from.isDirectory) { - if (DEBUG) Log.d(LOG_TAG_DOWNLOAD, "Invalid from: ${from.name} dir") + Logger.d(LOG_TAG_DOWNLOAD, "Invalid from: ${from.name} dir") return false } @@ -353,16 +351,15 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame val dest = File(to.absolutePath + File.separator + it.name) val result = it.copyTo(dest, true) if (!result.isFile) { - if (DEBUG) - Log.d(LOG_TAG_DOWNLOAD, "Copy failed from ${it.path} to ${dest.path}") + Logger.d(LOG_TAG_DOWNLOAD, "Copy failed from ${it.path} to ${dest.path}") return false } } - if (DEBUG) Log.d(LOG_TAG_DOWNLOAD, "Copied file from ${from.path} to ${to.path}") + Logger.d(LOG_TAG_DOWNLOAD, "Copied file from ${from.path} to ${to.path}") return true } catch (e: Exception) { - Log.e(LOG_TAG_DOWNLOAD, "Error copying files to local blocklist folder", e) + Logger.e(LOG_TAG_DOWNLOAD, "err copying files to local blocklist folder", e) } return false } @@ -377,16 +374,15 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame getTagValueFromJson(path + Constants.ONDEVICE_BLOCKLIST_FILE_BASIC_CONFIG, "tdmd5") val remoteRdmd5 = getTagValueFromJson(path + Constants.ONDEVICE_BLOCKLIST_FILE_BASIC_CONFIG, "rdmd5") - if (DEBUG) - Log.d( + Logger.d( LOG_TAG_DOWNLOAD, "tdmd5: $tdmd5, rdmd5: $rdmd5, remotetd: $remoteTdmd5, remoterd: $remoteRdmd5" ) val isDownloadValid = tdmd5 == remoteTdmd5 && rdmd5 == remoteRdmd5 - Log.i(LOG_TAG_DOWNLOAD, "AppDownloadManager isDownloadValid? $isDownloadValid") + Logger.i(LOG_TAG_DOWNLOAD, "AppDownloadManager isDownloadValid? $isDownloadValid") return isDownloadValid } catch (e: Exception) { - Log.e(LOG_TAG_DOWNLOAD, "AppDownloadManager isDownloadValid exception: ${e.message}", e) + Logger.e(LOG_TAG_DOWNLOAD, "AppDownloadManager isDownloadValid exception: ${e.message}", e) } return false } diff --git a/app/src/full/java/com/celzero/bravedns/customdownloader/RemoteBlocklistCoordinator.kt b/app/src/full/java/com/celzero/bravedns/customdownloader/RemoteBlocklistCoordinator.kt index f40d38286..45ee97f6d 100644 --- a/app/src/full/java/com/celzero/bravedns/customdownloader/RemoteBlocklistCoordinator.kt +++ b/app/src/full/java/com/celzero/bravedns/customdownloader/RemoteBlocklistCoordinator.kt @@ -15,16 +15,15 @@ */ package com.celzero.bravedns.customdownloader +import Logger.LOG_TAG_DOWNLOAD import android.content.Context import android.os.SystemClock -import android.util.Log import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import com.celzero.bravedns.download.BlocklistDownloadHelper import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.service.RethinkBlocklistManager import com.celzero.bravedns.util.Constants -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_DOWNLOAD import com.celzero.bravedns.util.RemoteFileTagUtil import com.celzero.bravedns.util.Utilities import com.google.gson.JsonObject @@ -47,7 +46,7 @@ class RemoteBlocklistCoordinator(val context: Context, workerParams: WorkerParam } override suspend fun doWork(): Result { - Log.i(LOG_TAG_DOWNLOAD, "Remote blocklist download worker started") + Logger.i(LOG_TAG_DOWNLOAD, "Remote blocklist download worker started") try { val startTime = inputData.getLong("workerStartTime", 0) val timestamp = inputData.getLong("blocklistTimestamp", 0) @@ -81,7 +80,7 @@ class RemoteBlocklistCoordinator(val context: Context, workerParams: WorkerParam } } } catch (ex: CancellationException) { - Log.e( + Logger.e( LOG_TAG_DOWNLOAD, "Local blocklist download, received cancellation exception: ${ex.message}", ex @@ -91,7 +90,7 @@ class RemoteBlocklistCoordinator(val context: Context, workerParams: WorkerParam } private suspend fun downloadRemoteBlocklist(timestamp: Long, retryCount: Int = 0): Boolean { - Log.i(LOG_TAG_DOWNLOAD, "Download remote blocklist: $timestamp") + Logger.i(LOG_TAG_DOWNLOAD, "Download remote blocklist: $timestamp") try { val retrofit = RetrofitManager.getBlocklistBaseBuilder(retryCount) @@ -105,7 +104,7 @@ class RemoteBlocklistCoordinator(val context: Context, workerParams: WorkerParam "" ) - Log.i( + Logger.i( LOG_TAG_DOWNLOAD, "response rcvd for remote blocklist, res: ${response?.isSuccessful}" ) @@ -114,13 +113,13 @@ class RemoteBlocklistCoordinator(val context: Context, workerParams: WorkerParam return saveRemoteFile(response.body(), timestamp) } } catch (ex: Exception) { - Log.e(LOG_TAG_DOWNLOAD, "err in downloadRemoteBlocklist: ${ex.message}", ex) + Logger.e(LOG_TAG_DOWNLOAD, "err in downloadRemoteBlocklist: ${ex.message}", ex) } return if (isRetryRequired(retryCount)) { - Log.i(LOG_TAG_DOWNLOAD, "retrying the downloadRemoteBlocklist") + Logger.i(LOG_TAG_DOWNLOAD, "retrying the downloadRemoteBlocklist") downloadRemoteBlocklist(timestamp, retryCount + 1) } else { - Log.i(LOG_TAG_DOWNLOAD, "retry count exceeded, returning null") + Logger.i(LOG_TAG_DOWNLOAD, "retry count exceeded, returning null") false } } @@ -142,7 +141,7 @@ class RemoteBlocklistCoordinator(val context: Context, workerParams: WorkerParam timestamp ) } catch (e: IOException) { - Log.w(LOG_TAG_DOWNLOAD, "could not create filetag.json at version $timestamp", e) + Logger.w(LOG_TAG_DOWNLOAD, "could not create filetag.json at version $timestamp", e) } return false } @@ -165,7 +164,7 @@ class RemoteBlocklistCoordinator(val context: Context, workerParams: WorkerParam } return filePath } catch (e: IOException) { - Log.e(LOG_TAG_DOWNLOAD, "err creating remote blocklist, ts: $timestamp" + e.message, e) + Logger.e(LOG_TAG_DOWNLOAD, "err creating remote blocklist, ts: $timestamp" + e.message, e) } return null } diff --git a/app/src/full/java/com/celzero/bravedns/customdownloader/RetrofitManager.kt b/app/src/full/java/com/celzero/bravedns/customdownloader/RetrofitManager.kt index 899facdb6..69aab6bd1 100644 --- a/app/src/full/java/com/celzero/bravedns/customdownloader/RetrofitManager.kt +++ b/app/src/full/java/com/celzero/bravedns/customdownloader/RetrofitManager.kt @@ -15,16 +15,14 @@ */ package com.celzero.bravedns.customdownloader -import android.util.Log import com.celzero.bravedns.util.Constants -import com.celzero.bravedns.util.Logger +import java.net.InetAddress +import java.util.concurrent.TimeUnit import okhttp3.Dns import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.OkHttpClient import okhttp3.dnsoverhttps.DnsOverHttps import retrofit2.Retrofit -import java.net.InetAddress -import java.util.concurrent.TimeUnit class RetrofitManager { @@ -119,9 +117,9 @@ class RetrofitManager { } } } catch (e: Exception) { - Log.e( + Logger.e( Logger.LOG_TAG_DOWNLOAD, - "Exception while getting custom dns: ${e.message}", + "err while getting custom dns: ${e.message}", e ) } @@ -133,11 +131,7 @@ class RetrofitManager { return try { InetAddress.getByName(ip) } catch (e: Exception) { - Log.e( - Logger.LOG_TAG_DOWNLOAD, - "Exception while getting ip address: ${e.message}", - e - ) + Logger.e(Logger.LOG_TAG_DOWNLOAD, "err while getting ip address: ${e.message}", e) throw e } } diff --git a/app/src/full/java/com/celzero/bravedns/download/AppDownloadManager.kt b/app/src/full/java/com/celzero/bravedns/download/AppDownloadManager.kt index 100117cd7..508752655 100644 --- a/app/src/full/java/com/celzero/bravedns/download/AppDownloadManager.kt +++ b/app/src/full/java/com/celzero/bravedns/download/AppDownloadManager.kt @@ -16,11 +16,12 @@ package com.celzero.bravedns.download +import Logger.LOG_TAG_DNS +import Logger.LOG_TAG_DOWNLOAD import android.app.DownloadManager import android.content.Context import android.net.Uri import android.os.SystemClock -import android.util.Log import androidx.lifecycle.MutableLiveData import androidx.work.BackoffPolicy import androidx.work.Data @@ -28,7 +29,6 @@ import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkRequest import androidx.work.workDataOf -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.customdownloader.LocalBlocklistCoordinator import com.celzero.bravedns.customdownloader.RemoteBlocklistCoordinator import com.celzero.bravedns.download.BlocklistDownloadHelper.Companion.checkBlocklistUpdate @@ -40,8 +40,6 @@ import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.service.RethinkBlocklistManager.DownloadType import com.celzero.bravedns.util.Constants.Companion.INIT_TIME_MS import com.celzero.bravedns.util.Constants.Companion.ONDEVICE_BLOCKLISTS_ADM -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_DNS -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_DOWNLOAD import com.celzero.bravedns.util.Utilities import java.util.concurrent.TimeUnit @@ -83,7 +81,7 @@ class AppDownloadManager( val response = checkBlocklistUpdate(ts, persistentState.appVersion, retryCount = 0) // if received response for update is null if (response == null) { - Log.w( + Logger.w( LOG_TAG_DNS, "blocklist update is check response is null for ${type.name}, ts: $ts, app version: ${persistentState.appVersion}" ) @@ -100,7 +98,7 @@ class AppDownloadManager( } val updatableTs = getDownloadableTimestamp(response) - Log.i( + Logger.i( LOG_TAG_DNS, "Updatable ts: $updatableTs, current ts: $ts, blocklist type: ${type.name}" ) @@ -170,7 +168,7 @@ class AppDownloadManager( val response = checkBlocklistUpdate(currentTs, persistentState.appVersion, retryCount = 0) // if received response for update is null if (response == null) { - Log.w( + Logger.w( LOG_TAG_DNS, "local blocklist update check is null, ts: $currentTs, app version: ${persistentState.appVersion}" ) @@ -181,7 +179,7 @@ class AppDownloadManager( // no need to proceed if the current and received timestamp is same if (updatableTs <= currentTs && !isRedownload) { - Log.i( + Logger.i( LOG_TAG_DNS, "local blocklist update not required, current ts: $currentTs, updatable ts: $updatableTs" ) @@ -191,11 +189,11 @@ class AppDownloadManager( } if (persistentState.useCustomDownloadManager) { - Log.i(LOG_TAG_DNS, "initiating local blocklist download with custom download mgr") + Logger.i(LOG_TAG_DNS, "initiating local blocklist download with custom download mgr") return initiateCustomDownloadManager(updatableTs) } - Log.i(LOG_TAG_DNS, "initiating local blocklist download with Android download mgr") + Logger.i(LOG_TAG_DNS, "initiating local blocklist download with Android download mgr") return initiateAndroidDownloadManager(updatableTs) } @@ -205,17 +203,17 @@ class AppDownloadManager( WorkScheduler.isWorkScheduled(context, DOWNLOAD_TAG) || WorkScheduler.isWorkScheduled(context, FILE_TAG) ) { - Log.i(LOG_TAG_DNS, "local blocklist download is already in progress, returning") + Logger.i(LOG_TAG_DNS, "local blocklist download is already in progress, returning") return DownloadManagerStatus.FAILURE } - Log.i(LOG_TAG_DNS, "local blocklist download is not in progress, starting the download") + Logger.i(LOG_TAG_DNS, "local blocklist download is not in progress, starting the download") purge(context, timestamp, DownloadType.LOCAL) val downloadIds = LongArray(ONDEVICE_BLOCKLISTS_ADM.count()) ONDEVICE_BLOCKLISTS_ADM.forEachIndexed { i, it -> val fileName = it.filename // url: https://dl.rethinkdns.com/update/blocklists?tstamp=1696197375609&vcode=33 - if (DEBUG) Log.d(LOG_TAG_DOWNLOAD, "v: ($timestamp), f: $fileName, u: $it.url") + Logger.d(LOG_TAG_DOWNLOAD, "v: ($timestamp), f: $fileName, u: $it.url") downloadIds[i] = enqueueDownload(it.url, fileName, timestamp.toString()) if (downloadIds[i] == INVALID_DOWNLOAD_ID) { return DownloadManagerStatus.FAILURE @@ -241,7 +239,7 @@ class AppDownloadManager( val response = checkBlocklistUpdate(currentTs, persistentState.appVersion, retryCount = 0) // if received response for update is null if (response == null) { - Log.w(LOG_TAG_DNS, "remote blocklist update check is null") + Logger.w(LOG_TAG_DNS, "remote blocklist update check is null") downloadRequired.postValue(DownloadManagerStatus.FAILURE) return false } @@ -249,7 +247,7 @@ class AppDownloadManager( val updatableTs = getDownloadableTimestamp(response) if (updatableTs <= currentTs && !isRedownload) { - Log.i( + Logger.i( LOG_TAG_DNS, "remote blocklist update not required, current ts: $currentTs, updatable ts: $updatableTs" ) @@ -272,7 +270,7 @@ class AppDownloadManager( RemoteBlocklistCoordinator.REMOTE_DOWNLOAD_WORKER ) ) { - Log.i(LOG_TAG_DNS, "remote blocklist download is already in progress, returning") + Logger.i(LOG_TAG_DNS, "remote blocklist download is already in progress, returning") return false } @@ -374,11 +372,11 @@ class AppDownloadManager( fileName ) val downloadId = downloadManager.enqueue(this) - if (DEBUG) Log.d(LOG_TAG_DOWNLOAD, "filename: $fileName, downloadID: $downloadId") + Logger.d(LOG_TAG_DOWNLOAD, "filename: $fileName, downloadID: $downloadId") return downloadId } } catch (e: Exception) { - Log.w(LOG_TAG_DOWNLOAD, "Exception while downloading the file: $fileName", e) + Logger.w(LOG_TAG_DOWNLOAD, "Exception while downloading the file: $fileName", e) } return INVALID_DOWNLOAD_ID } diff --git a/app/src/full/java/com/celzero/bravedns/download/BlocklistDownloadHelper.kt b/app/src/full/java/com/celzero/bravedns/download/BlocklistDownloadHelper.kt index 861b9d619..94155d780 100644 --- a/app/src/full/java/com/celzero/bravedns/download/BlocklistDownloadHelper.kt +++ b/app/src/full/java/com/celzero/bravedns/download/BlocklistDownloadHelper.kt @@ -15,21 +15,19 @@ */ package com.celzero.bravedns.download +import Logger.LOG_TAG_DOWNLOAD import android.content.Context -import android.util.Log -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.customdownloader.IBlocklistDownload import com.celzero.bravedns.customdownloader.RetrofitManager import com.celzero.bravedns.service.RethinkBlocklistManager import com.celzero.bravedns.util.Constants import com.celzero.bravedns.util.Constants.Companion.INIT_TIME_MS -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_DOWNLOAD import com.celzero.bravedns.util.Utilities.blocklistCanonicalPath import com.celzero.bravedns.util.Utilities.deleteRecursive +import java.io.File import org.json.JSONException import org.json.JSONObject import retrofit2.converter.gson.GsonConverterFactory -import java.io.File class BlocklistDownloadHelper { @@ -45,7 +43,7 @@ class BlocklistDownloadHelper { var total: Int? = 0 var dir: File? = null try { - if (DEBUG) Log.d(LOG_TAG_DOWNLOAD, "Local block list validation: $timestamp") + Logger.d(LOG_TAG_DOWNLOAD, "Local block list validation: $timestamp") dir = File(getExternalFilePath(context, timestamp.toString())) total = if (dir.isDirectory) { @@ -55,18 +53,17 @@ class BlocklistDownloadHelper { } result = Constants.ONDEVICE_BLOCKLISTS_ADM.count() == total } catch (ignored: Exception) { - Log.w( + Logger.w( LOG_TAG_DOWNLOAD, "Local block list validation failed: ${ignored.message}", ignored ) } - if (DEBUG) - Log.d( - LOG_TAG_DOWNLOAD, - "Valid on-device blocklist ($timestamp) download? $result, files: $total, dir? ${dir?.isDirectory}" - ) + Logger.d( + LOG_TAG_DOWNLOAD, + "Valid on-device blocklist ($timestamp) download? $result, files: $total, dir? ${dir?.isDirectory}" + ) return result } @@ -88,8 +85,7 @@ class BlocklistDownloadHelper { Constants.ONDEVICE_BLOCKLIST_DOWNLOAD_PATH } val dir = File(context.getExternalFilesDir(null).toString() + path + timestamp) - if (DEBUG) - Log.d(LOG_TAG_DOWNLOAD, "deleteOldFiles, File : ${dir.path}, ${dir.isDirectory}") + Logger.d(LOG_TAG_DOWNLOAD, "deleteOldFiles, File : ${dir.path}, ${dir.isDirectory}") deleteRecursive(dir) } @@ -98,11 +94,10 @@ class BlocklistDownloadHelper { if (!dir.exists()) return dir.listFiles()?.forEach { - if (DEBUG) - Log.d( - LOG_TAG_DOWNLOAD, - "Delete blocklist list residue for $which, dir: ${it.name}" - ) + Logger.d( + LOG_TAG_DOWNLOAD, + "Delete blocklist list residue for $which, dir: ${it.name}" + ) // delete all the dir other than current timestamp dir if (it.name != timestamp.toString()) { deleteRecursive(it) @@ -148,7 +143,7 @@ class BlocklistDownloadHelper { .addConverterFactory(GsonConverterFactory.create()) .build() val retrofitInterface = retrofit.create(IBlocklistDownload::class.java) - Log.i( + Logger.i( LOG_TAG_DOWNLOAD, "downloadAvailabilityCheck: ${Constants.ONDEVICE_BLOCKLIST_UPDATE_CHECK_QUERYPART_1}, ${Constants.ONDEVICE_BLOCKLIST_UPDATE_CHECK_QUERYPART_2}, $vcode, $timestamp" ) @@ -159,7 +154,7 @@ class BlocklistDownloadHelper { timestamp, vcode ) - Log.i( + Logger.i( LOG_TAG_DOWNLOAD, "downloadAvailabilityCheck: $response, $retryCount, $vcode, $timestamp" ) @@ -168,18 +163,17 @@ class BlocklistDownloadHelper { return processCheckDownloadResponse(r) } } catch (ex: Exception) { - Log.e(LOG_TAG_DOWNLOAD, "exception in checkBlocklistUpdate: ${ex.message}", ex) - Log.d(LOG_TAG_DOWNLOAD, "Ex: $ex", RuntimeException()) + Logger.e(LOG_TAG_DOWNLOAD, "exception in checkBlocklistUpdate: ${ex.message}", ex) } - Log.i( + Logger.i( LOG_TAG_DOWNLOAD, "downloadAvailabilityCheck: failed, returning null, $retryCount" ) return if (isRetryRequired(retryCount)) { - Log.i(LOG_TAG_DOWNLOAD, "retrying the downloadAvailabilityCheck") + Logger.i(LOG_TAG_DOWNLOAD, "retrying the downloadAvailabilityCheck") checkBlocklistUpdate(timestamp, vcode, retryCount + 1) } else { - Log.i(LOG_TAG_DOWNLOAD, "retry count exceeded, returning null") + Logger.i(LOG_TAG_DOWNLOAD, "retry count exceeded, returning null") null } } @@ -195,22 +189,21 @@ class BlocklistDownloadHelper { try { val version = response.optInt(Constants.JSON_VERSION, 0) - if (DEBUG) - Log.d( - LOG_TAG_DOWNLOAD, - "client onResponse for refresh blocklist files: $version" - ) + Logger.d( + LOG_TAG_DOWNLOAD, + "client onResponse for refresh blocklist files: $version" + ) val shouldUpdate = response.optBoolean(Constants.JSON_UPDATE, false) val timestamp = response.optLong(Constants.JSON_LATEST, INIT_TIME_MS) - Log.i( + Logger.i( LOG_TAG_DOWNLOAD, "response for blocklist update check: version: $version, update? $shouldUpdate, timestamp: $timestamp" ) return BlocklistUpdateServerResponse(version, shouldUpdate, timestamp) } catch (e: JSONException) { - Log.e(LOG_TAG_DOWNLOAD, "Error in parsing the response: ${e.message}", e) + Logger.e(LOG_TAG_DOWNLOAD, "Error in parsing the response: ${e.message}", e) } return null } diff --git a/app/src/full/java/com/celzero/bravedns/download/DownloadWatcher.kt b/app/src/full/java/com/celzero/bravedns/download/DownloadWatcher.kt index 39a81ffee..3cb189dd5 100644 --- a/app/src/full/java/com/celzero/bravedns/download/DownloadWatcher.kt +++ b/app/src/full/java/com/celzero/bravedns/download/DownloadWatcher.kt @@ -15,14 +15,12 @@ */ package com.celzero.bravedns.download +import Logger.LOG_TAG_DOWNLOAD import android.app.DownloadManager import android.content.Context import android.os.SystemClock -import android.util.Log import androidx.work.Worker import androidx.work.WorkerParameters -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_DOWNLOAD import org.koin.core.component.KoinComponent import java.util.concurrent.TimeUnit @@ -50,10 +48,10 @@ class DownloadWatcher(val context: Context, workerParameters: WorkerParameters) private var downloadIds: MutableList? = mutableListOf() override fun doWork(): Result { - Log.i(LOG_TAG_DOWNLOAD, "start download watcher, checking for download status") + Logger.i(LOG_TAG_DOWNLOAD, "start download watcher, checking for download status") val startTime = inputData.getLong("workerStartTime", 0) downloadIds = inputData.getLongArray("downloadIds")?.toMutableList() - if (DEBUG) Log.d(LOG_TAG_DOWNLOAD, "AppDownloadManager: $startTime, $downloadIds") + Logger.d(LOG_TAG_DOWNLOAD, "AppDownloadManager: $startTime, $downloadIds") if (downloadIds == null || downloadIds?.isEmpty() == true) return Result.failure() @@ -88,34 +86,38 @@ class DownloadWatcher(val context: Context, workerParameters: WorkerParameters) context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager val cursor = downloadManager.query(query) if (cursor == null) { - Log.i(LOG_TAG_DOWNLOAD, "status is $downloadID cursor null") + Logger.i(LOG_TAG_DOWNLOAD, "status is $downloadID cursor null") return DOWNLOAD_FAILURE } try { + val columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS) + if (columnIndex == -1) { + Logger.i(LOG_TAG_DOWNLOAD, "status is $downloadID column index -1") + return DOWNLOAD_FAILURE + } if (cursor.moveToFirst()) { - val status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) + val status = cursor.getInt(columnIndex) - if (DEBUG) Log.d(LOG_TAG_DOWNLOAD, "onReceive status $status $downloadID") + Logger.d(LOG_TAG_DOWNLOAD, "onReceive status $status $downloadID") if (status == DownloadManager.STATUS_SUCCESSFUL) { downloadIdsIterator.remove() } else if (status == DownloadManager.STATUS_FAILED) { val reason = - cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON)) - if (DEBUG) - Log.d( + cursor.getInt(columnIndex) + Logger.d( LOG_TAG_DOWNLOAD, "download status failure for $downloadID, $reason" ) return DOWNLOAD_FAILURE } } else { - if (DEBUG) Log.d(LOG_TAG_DOWNLOAD, "cursor empty") + Logger.d(LOG_TAG_DOWNLOAD, "cursor empty") return DOWNLOAD_FAILURE } } catch (e: Exception) { - Log.e(LOG_TAG_DOWNLOAD, "failure download: ${e.message}", e) + Logger.e(LOG_TAG_DOWNLOAD, "failure download: ${e.message}", e) } finally { cursor.close() } @@ -123,7 +125,7 @@ class DownloadWatcher(val context: Context, workerParameters: WorkerParameters) // send the status as success when the download ids are cleared if (downloadIds?.isEmpty() == true) { - Log.i(LOG_TAG_DOWNLOAD, "files downloaded successfully") + Logger.i(LOG_TAG_DOWNLOAD, "files downloaded successfully") return DOWNLOAD_SUCCESS } diff --git a/app/src/full/java/com/celzero/bravedns/download/FileHandleWorker.kt b/app/src/full/java/com/celzero/bravedns/download/FileHandleWorker.kt index 24b7b18f1..b318b17fe 100644 --- a/app/src/full/java/com/celzero/bravedns/download/FileHandleWorker.kt +++ b/app/src/full/java/com/celzero/bravedns/download/FileHandleWorker.kt @@ -15,30 +15,28 @@ */ package com.celzero.bravedns.download +import Logger.LOG_TAG_DOWNLOAD import android.content.Context -import android.util.Log import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import androidx.work.workDataOf -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.download.BlocklistDownloadHelper.Companion.deleteOldFiles import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.service.RethinkBlocklistManager import com.celzero.bravedns.util.Constants import com.celzero.bravedns.util.Constants.Companion.INIT_TIME_MS import com.celzero.bravedns.util.Constants.Companion.LOCAL_BLOCKLIST_DOWNLOAD_FOLDER_NAME -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_DOWNLOAD import com.celzero.bravedns.util.Utilities import com.celzero.bravedns.util.Utilities.calculateMd5 import com.celzero.bravedns.util.Utilities.getTagValueFromJson import com.celzero.bravedns.util.Utilities.hasLocalBlocklists import com.celzero.bravedns.util.Utilities.localBlocklistFileDownloadPath +import java.io.File import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.koin.core.component.KoinComponent import org.koin.core.component.inject -import java.io.File /** * Class responsible for copying the files from External path to canonical path. The worker will be @@ -57,11 +55,11 @@ class FileHandleWorker(val context: Context, workerParameters: WorkerParameters) override suspend fun doWork(): Result { try { val timestamp = inputData.getLong("blocklistDownloadInitiatedTime", Long.MIN_VALUE) - if (DEBUG) Log.d(LOG_TAG_DOWNLOAD, "blocklistDownloadInitiatedTime - $timestamp") + Logger.d(LOG_TAG_DOWNLOAD, "blocklistDownloadInitiatedTime - $timestamp") // invalid download initiated time if (timestamp <= INIT_TIME_MS) { - Log.w(LOG_TAG_DOWNLOAD, "timestamp version invalid $timestamp") + Logger.w(LOG_TAG_DOWNLOAD, "timestamp version invalid $timestamp") return Result.failure() } @@ -73,7 +71,7 @@ class FileHandleWorker(val context: Context, workerParameters: WorkerParameters) return if (response) Result.success(outputData) else Result.failure() } catch (e: Exception) { - Log.e( + Logger.e( LOG_TAG_DOWNLOAD, "FileHandleWorker Error while moving files to canonical path ${e.message}", e @@ -92,7 +90,7 @@ class FileHandleWorker(val context: Context, workerParameters: WorkerParameters) val dir = File(BlocklistDownloadHelper.getExternalFilePath(context, timestamp.toString())) if (!dir.isDirectory) { - Log.w( + Logger.w( LOG_TAG_DOWNLOAD, "Abort: file download path ${dir.absolutePath} isn't a directory" ) @@ -101,7 +99,7 @@ class FileHandleWorker(val context: Context, workerParameters: WorkerParameters) val children = dir.list() if (children.isNullOrEmpty()) { - Log.w(LOG_TAG_DOWNLOAD, "Abort: ${dir.absolutePath} is empty directory") + Logger.w(LOG_TAG_DOWNLOAD, "Abort: ${dir.absolutePath} is empty directory") return false } @@ -113,13 +111,13 @@ class FileHandleWorker(val context: Context, workerParameters: WorkerParameters) val from = dir.absolutePath + File.separator + children[i] val to = localBlocklistFileDownloadPath(context, children[i], timestamp) if (to.isEmpty()) { - Log.w(LOG_TAG_DOWNLOAD, "Copy failed from $from, to: $to") + Logger.w(LOG_TAG_DOWNLOAD, "Copy failed from $from, to: $to") return false } val result = Utilities.copy(from, to) if (!result) { - Log.w(LOG_TAG_DOWNLOAD, "Copy failed from: $from, to: $to") + Logger.w(LOG_TAG_DOWNLOAD, "Copy failed from: $from, to: $to") return false } } @@ -128,7 +126,7 @@ class FileHandleWorker(val context: Context, workerParameters: WorkerParameters) "${context.filesDir.canonicalPath}${File.separator}$timestamp${File.separator}" ) - Log.i( + Logger.i( LOG_TAG_DOWNLOAD, "After copy, dest dir: $destinationDir, ${destinationDir.isDirectory}, ${destinationDir.list()?.count()}" ) @@ -143,7 +141,7 @@ class FileHandleWorker(val context: Context, workerParameters: WorkerParameters) deleteOldFiles(context, timestamp, RethinkBlocklistManager.DownloadType.LOCAL) return true } catch (e: Exception) { - Log.e(LOG_TAG_DOWNLOAD, "AppDownloadManager Copy exception: ${e.message}", e) + Logger.e(LOG_TAG_DOWNLOAD, "AppDownloadManager Copy exception: ${e.message}", e) } return false } @@ -184,16 +182,15 @@ class FileHandleWorker(val context: Context, workerParameters: WorkerParameters) getTagValueFromJson(path + Constants.ONDEVICE_BLOCKLIST_FILE_BASIC_CONFIG, "tdmd5") val remoteRdmd5 = getTagValueFromJson(path + Constants.ONDEVICE_BLOCKLIST_FILE_BASIC_CONFIG, "rdmd5") - if (DEBUG) - Log.d( - LOG_TAG_DOWNLOAD, - "tdmd5: $tdmd5, rdmd5: $rdmd5, remotetd: $remoteTdmd5, remoterd: $remoteRdmd5" - ) + Logger.d( + LOG_TAG_DOWNLOAD, + "tdmd5: $tdmd5, rdmd5: $rdmd5, remotetd: $remoteTdmd5, remoterd: $remoteRdmd5" + ) val isDownloadValid = tdmd5 == remoteTdmd5 && rdmd5 == remoteRdmd5 - Log.i(LOG_TAG_DOWNLOAD, "AppDownloadManager, isDownloadValid? $isDownloadValid") + Logger.i(LOG_TAG_DOWNLOAD, "AppDownloadManager, isDownloadValid? $isDownloadValid") return isDownloadValid } catch (e: Exception) { - Log.e(LOG_TAG_DOWNLOAD, "AppDownloadManager, isDownloadValid err: ${e.message}", e) + Logger.e(LOG_TAG_DOWNLOAD, "AppDownloadManager, isDownloadValid err: ${e.message}", e) } return false } diff --git a/app/src/full/java/com/celzero/bravedns/receiver/BraveAutoStartReceiver.kt b/app/src/full/java/com/celzero/bravedns/receiver/BraveAutoStartReceiver.kt index c5eb3fce8..2da84df69 100644 --- a/app/src/full/java/com/celzero/bravedns/receiver/BraveAutoStartReceiver.kt +++ b/app/src/full/java/com/celzero/bravedns/receiver/BraveAutoStartReceiver.kt @@ -16,14 +16,13 @@ package com.celzero.bravedns.receiver +import Logger.LOG_TAG_VPN import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.net.VpnService -import android.util.Log import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.service.VpnController -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_VPN import org.koin.core.component.KoinComponent import org.koin.core.component.inject @@ -34,7 +33,7 @@ class BraveAutoStartReceiver : BroadcastReceiver(), KoinComponent { override fun onReceive(context: Context, intent: Intent) { if (!persistentState.prefAutoStartBootUp) { - Log.w(LOG_TAG_VPN, "Auto start is not enabled: ${persistentState.prefAutoStartBootUp}") + Logger.w(LOG_TAG_VPN, "Auto start is not enabled: ${persistentState.prefAutoStartBootUp}") return } @@ -43,7 +42,7 @@ class BraveAutoStartReceiver : BroadcastReceiver(), KoinComponent { Intent.ACTION_BOOT_COMPLETED != intent.action && Intent.ACTION_LOCKED_BOOT_COMPLETED != intent.action ) { - Log.w(LOG_TAG_VPN, "unhandled broadcast ${intent.action}") + Logger.w(LOG_TAG_VPN, "unhandled broadcast ${intent.action}") return } @@ -53,15 +52,15 @@ class BraveAutoStartReceiver : BroadcastReceiver(), KoinComponent { if (VpnController.state().activationRequested && !VpnController.isAlwaysOn(context)) { val prepareVpnIntent: Intent? = try { - Log.i(LOG_TAG_VPN, "Attempting to auto-start VPN") + Logger.i(LOG_TAG_VPN, "Attempting to auto-start VPN") VpnService.prepare(context) } catch (e: NullPointerException) { - Log.w(LOG_TAG_VPN, "Device does not support system-wide VPN mode") + Logger.w(LOG_TAG_VPN, "Device does not support system-wide VPN mode") return } if (prepareVpnIntent == null) { - Log.i(LOG_TAG_VPN, "VPN is already prepared, invoking start") + Logger.i(LOG_TAG_VPN, "VPN is already prepared, invoking start") VpnController.start(context) return } diff --git a/app/src/full/java/com/celzero/bravedns/receiver/NotificationActionReceiver.kt b/app/src/full/java/com/celzero/bravedns/receiver/NotificationActionReceiver.kt index b449cf8d5..fdf6d94d2 100644 --- a/app/src/full/java/com/celzero/bravedns/receiver/NotificationActionReceiver.kt +++ b/app/src/full/java/com/celzero/bravedns/receiver/NotificationActionReceiver.kt @@ -15,11 +15,11 @@ */ package com.celzero.bravedns.receiver +import Logger.LOG_TAG_VPN import android.app.NotificationManager import android.content.BroadcastReceiver import android.content.Context import android.content.Intent -import android.util.Log import android.widget.Toast import com.celzero.bravedns.R import com.celzero.bravedns.data.AppConfig @@ -28,7 +28,6 @@ import com.celzero.bravedns.service.FirewallManager import com.celzero.bravedns.service.FirewallManager.NOTIF_CHANNEL_ID_FIREWALL_ALERTS import com.celzero.bravedns.service.VpnController import com.celzero.bravedns.util.Constants -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_VPN import com.celzero.bravedns.util.OrbotHelper import com.celzero.bravedns.util.OrbotHelper.Companion.NOTIF_CHANNEL_ID_PROXY_ALERTS import com.celzero.bravedns.util.Utilities @@ -46,7 +45,7 @@ class NotificationActionReceiver : BroadcastReceiver(), KoinComponent { override fun onReceive(context: Context, intent: Intent) { // TODO - Move the NOTIFICATION_ACTIONs value to enum val action: String? = intent.getStringExtra(Constants.NOTIFICATION_ACTION) - Log.i(LOG_TAG_VPN, "Received notification action: $action") + Logger.i(LOG_TAG_VPN, "Received notification action: $action") val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager when (action) { OrbotHelper.ORBOT_NOTIFICATION_ACTION_TEXT -> { diff --git a/app/src/full/java/com/celzero/bravedns/scheduler/BlocklistUpdateCheckJob.kt b/app/src/full/java/com/celzero/bravedns/scheduler/BlocklistUpdateCheckJob.kt index 3d44b8421..4ae3201df 100644 --- a/app/src/full/java/com/celzero/bravedns/scheduler/BlocklistUpdateCheckJob.kt +++ b/app/src/full/java/com/celzero/bravedns/scheduler/BlocklistUpdateCheckJob.kt @@ -15,14 +15,13 @@ */ package com.celzero.bravedns.scheduler +import Logger.LOG_TAG_SCHEDULER import android.content.Context -import android.util.Log import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import com.celzero.bravedns.download.BlocklistDownloadHelper import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.service.RethinkBlocklistManager -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_SCHEDULER import com.celzero.bravedns.util.Utilities import org.koin.core.component.KoinComponent import org.koin.core.component.inject @@ -33,7 +32,7 @@ class BlocklistUpdateCheckJob(val context: Context, workerParameters: WorkerPara private val persistentState by inject() override suspend fun doWork(): Result { - Log.i(LOG_TAG_SCHEDULER, "starting blocklist update check job") + Logger.i(LOG_TAG_SCHEDULER, "starting blocklist update check job") if (!Utilities.isPlayStoreFlavour()) { isDownloadRequired( diff --git a/app/src/full/java/com/celzero/bravedns/scheduler/BugReportCollector.kt b/app/src/full/java/com/celzero/bravedns/scheduler/BugReportCollector.kt index cd82ad645..ffeac815d 100644 --- a/app/src/full/java/com/celzero/bravedns/scheduler/BugReportCollector.kt +++ b/app/src/full/java/com/celzero/bravedns/scheduler/BugReportCollector.kt @@ -16,18 +16,16 @@ package com.celzero.bravedns.scheduler +import Logger.LOG_TAG_SCHEDULER import android.app.ActivityManager import android.content.Context import android.os.Build -import android.util.Log import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import androidx.preference.PreferenceManager import androidx.work.CoroutineWorker import androidx.work.WorkerParameters -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.service.PersistentState -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_SCHEDULER import com.celzero.bravedns.util.Utilities import com.celzero.bravedns.util.Utilities.isAtleastO import org.koin.core.component.KoinComponent @@ -51,7 +49,7 @@ class BugReportCollector(val context: Context, workerParameters: WorkerParameter } override suspend fun doWork(): Result { - if (DEBUG) Log.d(LOG_TAG_SCHEDULER, "starting app-exit-info job") + Logger.d(LOG_TAG_SCHEDULER, "starting app-exit-info job") if (!isAtleastO()) { // support for zip file creation for devices below Oreo is not straightforward // hence, we are not supporting it for now @@ -72,9 +70,9 @@ class BugReportCollector(val context: Context, workerParameters: WorkerParameter @RequiresApi(Build.VERSION_CODES.O) private fun prepare(): File { val path = BugReportZipper.prepare(applicationContext.filesDir) - Log.i(LOG_TAG_SCHEDULER, "app-exit-info job path: $path") + Logger.i(LOG_TAG_SCHEDULER, "app-exit-info job path: $path") val file = File(path) - Log.i(LOG_TAG_SCHEDULER, "app-exit-info job file: ${file.name}, ${file.absolutePath}") + Logger.i(LOG_TAG_SCHEDULER, "app-exit-info job file: ${file.name}, ${file.absolutePath}") return file } @@ -91,7 +89,7 @@ class BugReportCollector(val context: Context, workerParameters: WorkerParameter // app exit info is available only on Android R and above, normal process builder // for logcat is used for all the other versions if (!Utilities.isAtleastR()) { - Log.i(LOG_TAG_SCHEDULER, "app-exit-info job not supported on this device") + Logger.i(LOG_TAG_SCHEDULER, "app-exit-info job not supported on this device") return -1L } @@ -144,10 +142,10 @@ class BugReportCollector(val context: Context, workerParameters: WorkerParameter BugReportZipper.fileWrite(ips, file) val exitcode = pd.waitFor() if (exitcode != 0) { - Log.e(LOG_TAG_SCHEDULER, "logcat process exited with $exitcode") + Logger.e(LOG_TAG_SCHEDULER, "logcat process exited with $exitcode") } } catch (e: Exception) { - Log.e(LOG_TAG_SCHEDULER, "Error while dumping logs", e) + Logger.e(LOG_TAG_SCHEDULER, "err while dumping logs", e) } } } diff --git a/app/src/full/java/com/celzero/bravedns/scheduler/BugReportZipper.kt b/app/src/full/java/com/celzero/bravedns/scheduler/BugReportZipper.kt index 0354964bd..dcab8cd28 100644 --- a/app/src/full/java/com/celzero/bravedns/scheduler/BugReportZipper.kt +++ b/app/src/full/java/com/celzero/bravedns/scheduler/BugReportZipper.kt @@ -16,14 +16,13 @@ package com.celzero.bravedns.scheduler +import Logger.LOG_TAG_SCHEDULER import android.app.ApplicationExitInfo import android.content.SharedPreferences import android.os.Build -import android.util.Log import androidx.annotation.RequiresApi import com.celzero.bravedns.BuildConfig import com.celzero.bravedns.util.Constants -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_SCHEDULER import com.celzero.bravedns.util.Utilities import com.google.common.io.Files import java.io.File @@ -80,10 +79,10 @@ object BugReportZipper { return try { ZipFile(getZipFileName(dir)) } catch (e: FileNotFoundException) { - Log.w(LOG_TAG_SCHEDULER, "File not found exception while creating zip file", e) + Logger.w(LOG_TAG_SCHEDULER, "File not found exception while creating zip file", e) null } catch (e: ZipException) { - Log.w(LOG_TAG_SCHEDULER, "Zip exception while creating zip file", e) + Logger.w(LOG_TAG_SCHEDULER, "Zip exception while creating zip file", e) null } } @@ -153,7 +152,7 @@ object BugReportZipper { private fun addNewZipEntry(zo: ZipOutputStream, file: File) { if (file.isDirectory) return - Log.i(LOG_TAG_SCHEDULER, "Add new file: ${file.name} to bug_report.zip") + Logger.i(LOG_TAG_SCHEDULER, "Add new file: ${file.name} to bug_report.zip") val entry = ZipEntry(file.name) zo.putNextEntry(entry) FileInputStream(file).use { inStream -> copy(inStream, zo) } @@ -168,7 +167,7 @@ object BugReportZipper { while (entries.hasMoreElements()) { val e = entries.nextElement() if (ignoreFileName == e.name) { - Log.i(LOG_TAG_SCHEDULER, "Ignoring file to be replaced: ${e.name}") + Logger.i(LOG_TAG_SCHEDULER, "Ignoring file to be replaced: ${e.name}") continue } diff --git a/app/src/full/java/com/celzero/bravedns/scheduler/PaymentWorker.kt b/app/src/full/java/com/celzero/bravedns/scheduler/PaymentWorker.kt index 816c318ca..4fe5f32ce 100644 --- a/app/src/full/java/com/celzero/bravedns/scheduler/PaymentWorker.kt +++ b/app/src/full/java/com/celzero/bravedns/scheduler/PaymentWorker.kt @@ -15,21 +15,18 @@ */ package com.celzero.bravedns.scheduler +import Logger.LOG_TAG_DOWNLOAD import android.content.Context import android.os.SystemClock -import android.util.Log import androidx.work.CoroutineWorker import androidx.work.WorkerParameters -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.customdownloader.ITcpProxy import com.celzero.bravedns.customdownloader.RetrofitManager import com.celzero.bravedns.service.TcpProxyHelper -import com.celzero.bravedns.util.Logger -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_DOWNLOAD +import java.util.concurrent.TimeUnit import org.json.JSONObject import org.koin.core.component.KoinComponent import retrofit2.converter.gson.GsonConverterFactory -import java.util.concurrent.TimeUnit class PaymentWorker(val context: Context, workerParameters: WorkerParameters) : CoroutineWorker(context, workerParameters), KoinComponent { @@ -46,13 +43,13 @@ class PaymentWorker(val context: Context, workerParameters: WorkerParameters) : val startTime = inputData.getLong("workerStartTime", 0) if (SystemClock.elapsedRealtime() - startTime > MAX_RETRY_TIMEOUT) { - Log.w(LOG_TAG_DOWNLOAD, "Payment verification timed out") + Logger.w(LOG_TAG_DOWNLOAD, "Payment verification timed out") TcpProxyHelper.updatePaymentStatus(TcpProxyHelper.PaymentStatus.FAILED) return Result.failure() } val paymentStatus = getPaymentStatusFromServer() - Log.i( + Logger.i( LOG_TAG_DOWNLOAD, "Payment status: $paymentStatus received at ${System.currentTimeMillis()}" ) @@ -83,11 +80,10 @@ class PaymentWorker(val context: Context, workerParameters: WorkerParameters) : // TODO: get refId from EncryptedFile val refId = "" val response = retrofitInterface.getPaymentStatus(refId) - if (DEBUG) - Log.d( - Logger.LOG_TAG_PROXY, - "getPaymentStatusFromServer: ${response?.headers()}, ${response?.message()}, ${response?.raw()?.request?.url}" - ) + Logger.d( + Logger.LOG_TAG_PROXY, + "getPaymentStatusFromServer: ${response?.headers()}, ${response?.message()}, ${response?.raw()?.request?.url}" + ) if (response?.isSuccessful == true) { val jsonObject = JSONObject(response.body().toString()) @@ -96,7 +92,7 @@ class PaymentWorker(val context: Context, workerParameters: WorkerParameters) : paymentStatus = TcpProxyHelper.PaymentStatus.entries.find { it.name == paymentStatusString } ?: TcpProxyHelper.PaymentStatus.NOT_PAID - Log.i( + Logger.i( Logger.LOG_TAG_PROXY, "getPaymentStatusFromServer: status: $status, paymentStatus: $paymentStatus" ) @@ -105,13 +101,13 @@ class PaymentWorker(val context: Context, workerParameters: WorkerParameters) : } return paymentStatus } else { - Log.w( + Logger.w( Logger.LOG_TAG_PROXY, "unsuccessful response for ${response?.raw()?.request?.url}" ) } } catch (e: Exception) { - Log.w( + Logger.w( Logger.LOG_TAG_PROXY, "getPaymentStatusFromServer: exception while checking payment status", e @@ -120,10 +116,10 @@ class PaymentWorker(val context: Context, workerParameters: WorkerParameters) : return if ( isRetryRequired(retryCount) && paymentStatus == TcpProxyHelper.PaymentStatus.INITIATED ) { - Log.i(LOG_TAG_DOWNLOAD, "retrying the payment status check") + Logger.i(LOG_TAG_DOWNLOAD, "retrying the payment status check") getPaymentStatusFromServer(retryCount + 1) } else { - Log.i(LOG_TAG_DOWNLOAD, "retry count exceeded, returning null") + Logger.i(LOG_TAG_DOWNLOAD, "retry count exceeded, returning null") return paymentStatus } } diff --git a/app/src/full/java/com/celzero/bravedns/scheduler/PurgeConnectionLogs.kt b/app/src/full/java/com/celzero/bravedns/scheduler/PurgeConnectionLogs.kt index 8fd8a636b..8d3e9d0f2 100644 --- a/app/src/full/java/com/celzero/bravedns/scheduler/PurgeConnectionLogs.kt +++ b/app/src/full/java/com/celzero/bravedns/scheduler/PurgeConnectionLogs.kt @@ -15,13 +15,11 @@ */ package com.celzero.bravedns.scheduler +import Logger.LOG_TAG_SCHEDULER import android.content.Context -import android.util.Log import androidx.work.CoroutineWorker import androidx.work.WorkerParameters -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.database.RefreshDatabase -import com.celzero.bravedns.util.Logger import org.koin.core.component.KoinComponent import org.koin.core.component.inject import java.util.Calendar @@ -36,11 +34,11 @@ class PurgeConnectionLogs(val context: Context, workerParameters: WorkerParamete } override suspend fun doWork(): Result { - if (DEBUG) Log.d(Logger.LOG_TAG_SCHEDULER, "starting purge-database job") + Logger.d(LOG_TAG_SCHEDULER, "starting purge-database job") val calendar = Calendar.getInstance() calendar.add(Calendar.DAY_OF_YEAR, NUMBER_OF_DAYS_TO_PURGE) val date = calendar.time.time - Log.i(Logger.LOG_TAG_SCHEDULER, "purging logs older than 7 days, date: $date") + Logger.i(LOG_TAG_SCHEDULER, "purging logs older than 7 days, date: $date") /** * purge logs older than 7 days (on version v053l, subject to change in later versions based diff --git a/app/src/full/java/com/celzero/bravedns/scheduler/WorkScheduler.kt b/app/src/full/java/com/celzero/bravedns/scheduler/WorkScheduler.kt index 091bb0134..7f547440a 100644 --- a/app/src/full/java/com/celzero/bravedns/scheduler/WorkScheduler.kt +++ b/app/src/full/java/com/celzero/bravedns/scheduler/WorkScheduler.kt @@ -16,8 +16,8 @@ package com.celzero.bravedns.scheduler +import Logger.LOG_TAG_SCHEDULER import android.content.Context -import android.util.Log import androidx.work.BackoffPolicy import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.ExistingWorkPolicy @@ -26,8 +26,6 @@ import androidx.work.PeriodicWorkRequest import androidx.work.WorkInfo import androidx.work.WorkManager import androidx.work.WorkRequest -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_SCHEDULER import com.celzero.bravedns.util.Utilities import com.google.common.util.concurrent.ListenableFuture import java.util.concurrent.ExecutionException @@ -50,7 +48,7 @@ class WorkScheduler(val context: Context) { fun isWorkRunning(context: Context, tag: String): Boolean { val instance = WorkManager.getInstance(context) val statuses: ListenableFuture> = instance.getWorkInfosByTag(tag) - if (DEBUG) Log.d(LOG_TAG_SCHEDULER, "Job $tag already running check") + Logger.d(LOG_TAG_SCHEDULER, "Job $tag already running check") return try { var running = false val workInfos = statuses.get() @@ -60,13 +58,13 @@ class WorkScheduler(val context: Context) { for (workStatus in workInfos) { running = workStatus.state == WorkInfo.State.RUNNING } - Log.i(LOG_TAG_SCHEDULER, "Job $tag already running? $running") + Logger.i(LOG_TAG_SCHEDULER, "Job $tag already running? $running") running } catch (e: ExecutionException) { - Log.e(LOG_TAG_SCHEDULER, "error on status check ${e.message}", e) + Logger.e(LOG_TAG_SCHEDULER, "error on status check ${e.message}", e) false } catch (e: InterruptedException) { - Log.e(LOG_TAG_SCHEDULER, "error on status check ${e.message}", e) + Logger.e(LOG_TAG_SCHEDULER, "error on status check ${e.message}", e) false } } @@ -76,7 +74,7 @@ class WorkScheduler(val context: Context) { fun isWorkScheduled(context: Context, tag: String): Boolean { val instance = WorkManager.getInstance(context) val statuses: ListenableFuture> = instance.getWorkInfosByTag(tag) - if (DEBUG) Log.d(LOG_TAG_SCHEDULER, "Job $tag already scheduled check") + Logger.d(LOG_TAG_SCHEDULER, "Job $tag already scheduled check") return try { var running = false val workInfos = statuses.get() @@ -88,13 +86,13 @@ class WorkScheduler(val context: Context) { workStatus.state == WorkInfo.State.RUNNING || workStatus.state == WorkInfo.State.ENQUEUED } - Log.i(LOG_TAG_SCHEDULER, "Job $tag already scheduled? $running") + Logger.i(LOG_TAG_SCHEDULER, "Job $tag already scheduled? $running") running } catch (e: ExecutionException) { - Log.e(LOG_TAG_SCHEDULER, "error on status check ${e.message}", e) + Logger.e(LOG_TAG_SCHEDULER, "error on status check ${e.message}", e) false } catch (e: InterruptedException) { - Log.e(LOG_TAG_SCHEDULER, "error on status check ${e.message}", e) + Logger.e(LOG_TAG_SCHEDULER, "error on status check ${e.message}", e) false } } @@ -102,12 +100,10 @@ class WorkScheduler(val context: Context) { // Schedule AppExitInfo every APP_EXIT_INFO_JOB_TIME_INTERVAL_DAYS fun scheduleAppExitInfoCollectionJob() { - // if (isWorkScheduled(context.applicationContext, APP_EXIT_INFO_JOB_TAG)) return - // app exit info is supported from R+ if (!Utilities.isAtleastR()) return - if (DEBUG) Log.d(LOG_TAG_SCHEDULER, "App exit info job scheduled") + Logger.d(LOG_TAG_SCHEDULER, "App exit info job scheduled") val bugReportCollector = PeriodicWorkRequest.Builder( BugReportCollector::class.java, @@ -125,8 +121,6 @@ class WorkScheduler(val context: Context) { } fun schedulePurgeConnectionsLog() { - // if (isWorkScheduled(context.applicationContext, PURGE_CONNECTION_LOGS_JOB_TAG)) return - val purgeLogs = PeriodicWorkRequest.Builder( PurgeConnectionLogs::class.java, @@ -136,7 +130,7 @@ class WorkScheduler(val context: Context) { .addTag(PURGE_CONNECTION_LOGS_JOB_TAG) .build() - if (DEBUG) Log.d(LOG_TAG_SCHEDULER, "purge connection logs job scheduled") + Logger.d(LOG_TAG_SCHEDULER, "purge connection logs job scheduled") WorkManager.getInstance(context.applicationContext) .enqueueUniquePeriodicWork( PURGE_CONNECTION_LOGS_JOB_TAG, @@ -147,8 +141,6 @@ class WorkScheduler(val context: Context) { // Schedule AppExitInfo on demand fun scheduleOneTimeWorkForAppExitInfo() { - /// if (isWorkScheduled(context.applicationContext, APP_EXIT_INFO_ONE_TIME_JOB_TAG)) return - val bugReportCollector = OneTimeWorkRequestBuilder() .setBackoffCriteria( @@ -171,7 +163,7 @@ class WorkScheduler(val context: Context) { fun scheduleBlocklistUpdateCheckJob() { // if (isWorkScheduled(context.applicationContext, BLOCKLIST_UPDATE_CHECK_JOB_TAG)) return - Log.i(LOG_TAG_SCHEDULER, "Scheduled blocklist update check") + Logger.i(LOG_TAG_SCHEDULER, "Scheduled blocklist update check") val blocklistUpdateCheck = PeriodicWorkRequest.Builder( BlocklistUpdateCheckJob::class.java, @@ -189,10 +181,7 @@ class WorkScheduler(val context: Context) { } fun scheduleDataUsageJob() { - Log.i(LOG_TAG_SCHEDULER, "Data usage job schedule started") - // if (isWorkScheduled(context.applicationContext, DATA_USAGE_JOB_TAG)) return - - Log.i(LOG_TAG_SCHEDULER, "Data usage job scheduled") + Logger.i(LOG_TAG_SCHEDULER, "Data usage job scheduled") val workRequest = PeriodicWorkRequest.Builder( DataUsageUpdater::class.java, diff --git a/app/src/full/java/com/celzero/bravedns/service/ProxyManager.kt b/app/src/full/java/com/celzero/bravedns/service/ProxyManager.kt index 790879355..b9e186d3f 100644 --- a/app/src/full/java/com/celzero/bravedns/service/ProxyManager.kt +++ b/app/src/full/java/com/celzero/bravedns/service/ProxyManager.kt @@ -15,13 +15,11 @@ */ package com.celzero.bravedns.service -import android.util.Log +import Logger.LOG_TAG_PROXY import backend.Backend -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.database.AppInfo import com.celzero.bravedns.database.ProxyAppMappingRepository import com.celzero.bravedns.database.ProxyApplicationMapping -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_PROXY import org.koin.core.component.KoinComponent import org.koin.core.component.inject import java.util.concurrent.CopyOnWriteArraySet @@ -100,7 +98,7 @@ object ProxyManager : KoinComponent { // proxyId cannot be empty. suspend fun updateProxyIdForApp(uid: Int, nonEmptyProxyId: String, proxyName: String) { if (!isValidProxyPrefix(nonEmptyProxyId)) { - Log.e(LOG_TAG_PROXY, "cannot update $nonEmptyProxyId; setNoProxyForApp instead?") + Logger.e(LOG_TAG_PROXY, "cannot update $nonEmptyProxyId; setNoProxyForApp instead?") return } @@ -114,7 +112,7 @@ object ProxyManager : KoinComponent { pamSet.addAll(n) db.updateProxyIdForApp(uid, nonEmptyProxyId, proxyName) } else { - Log.e(LOG_TAG_PROXY, "updateProxyIdForApp: map not found for uid $uid") + Logger.e(LOG_TAG_PROXY, "updateProxyIdForApp: map not found for uid $uid") } } @@ -125,14 +123,14 @@ object ProxyManager : KoinComponent { suspend fun setProxyIdForAllApps(proxyId: String, proxyName: String) { // ID_NONE or empty proxy-id is not allowed; see removeProxyForAllApps() if (!isValidProxyPrefix(proxyId)) { - Log.e(LOG_TAG_PROXY, "Invalid proxy id: $proxyId") + Logger.e(LOG_TAG_PROXY, "Invalid proxy id: $proxyId") return } val m = pamSet.map { ProxyAppMapTuple(it.uid, it.packageName, proxyId) } pamSet.clear() pamSet.addAll(m) db.updateProxyForAllApps(proxyId, proxyName) - Log.i(LOG_TAG_PROXY, "added all apps to proxy: $proxyId") + Logger.i(LOG_TAG_PROXY, "added all apps to proxy: $proxyId") } suspend fun updateProxyNameForProxyId(proxyId: String, proxyName: String) { @@ -143,7 +141,7 @@ object ProxyManager : KoinComponent { suspend fun setProxyIdForUnselectedApps(proxyId: String, proxyName: String) { // ID_NONE or empty proxy-id is not allowed if (!isValidProxyPrefix(proxyId)) { - Log.e(LOG_TAG_PROXY, "Invalid proxy id: $proxyId") + Logger.e(LOG_TAG_PROXY, "Invalid proxy id: $proxyId") return } val m = pamSet.filter { it.proxyId == "" }.toSet() @@ -151,7 +149,7 @@ object ProxyManager : KoinComponent { pamSet.removeAll(m) pamSet.addAll(n) db.updateProxyForUnselectedApps(proxyId, proxyName) - Log.i(LOG_TAG_PROXY, "added unselected apps to interface: $proxyId") + Logger.i(LOG_TAG_PROXY, "added unselected apps to interface: $proxyId") } suspend fun setNoProxyForApp(uid: Int) { @@ -164,13 +162,13 @@ object ProxyManager : KoinComponent { // update the id as empty string to remove the proxy db.updateProxyIdForApp(uid, noProxy, noProxy) } else { - Log.e(LOG_TAG_PROXY, "app config mapping is null for uid $uid on setNoProxyForApp") + Logger.e(LOG_TAG_PROXY, "app config mapping is null for uid $uid on setNoProxyForApp") } } suspend fun setNoProxyForAllApps() { val noProxy = "" - Log.i(LOG_TAG_PROXY, "Removing all apps from proxy") + Logger.i(LOG_TAG_PROXY, "Removing all apps from proxy") val m = pamSet.filter { it.proxyId != noProxy }.toSet() val n = m.map { ProxyAppMapTuple(it.uid, it.packageName, noProxy) } pamSet.removeAll(m) @@ -179,7 +177,7 @@ object ProxyManager : KoinComponent { } suspend fun removeProxyId(proxyId: String) { - Log.i(LOG_TAG_PROXY, "Removing all apps from proxy with id: $proxyId") + Logger.i(LOG_TAG_PROXY, "Removing all apps from proxy with id: $proxyId") val noProxy = "" val m = pamSet.filter { it.proxyId == proxyId }.toSet() val n = m.map { ProxyAppMapTuple(it.uid, it.packageName, noProxy) } @@ -213,11 +211,11 @@ object ProxyManager : KoinComponent { // refreshDatabase so that any entries removed are added back as "new mappings" via // addNewApp if (dups.size > 0) { - Log.w(LOG_TAG_PROXY, "delete dup pxms: $dups") + Logger.w(LOG_TAG_PROXY, "delete dup pxms: $dups") deleteApps(dups) } else { // no dups found - Log.i(LOG_TAG_PROXY, "no dups found") + Logger.i(LOG_TAG_PROXY, "no dups found") } } @@ -238,7 +236,7 @@ object ProxyManager : KoinComponent { } private fun deleteFromCache(pam: ProxyApplicationMapping) { - pamSet.forEach() { + pamSet.forEach { if (it.uid == pam.uid && it.packageName == pam.packageName) { pamSet.remove(it) } @@ -258,7 +256,7 @@ object ProxyManager : KoinComponent { ProxyApplicationMapping(uid, packageName, "", "", false, "") deleteFromCache(pam) db.deleteApp(pam) - if (DEBUG) Log.d(LOG_TAG_PROXY, "Deleting app for mapping: ${pam.appName}, ${pam.uid}") + Logger.d(LOG_TAG_PROXY, "Deleting app for mapping: ${pam.appName}, ${pam.uid}") } suspend fun clear() { diff --git a/app/src/full/java/com/celzero/bravedns/service/TcpProxyHelper.kt b/app/src/full/java/com/celzero/bravedns/service/TcpProxyHelper.kt index 541ffe0b6..94dac0322 100644 --- a/app/src/full/java/com/celzero/bravedns/service/TcpProxyHelper.kt +++ b/app/src/full/java/com/celzero/bravedns/service/TcpProxyHelper.kt @@ -1,8 +1,8 @@ package com.celzero.bravedns.service +import Logger.LOG_TAG_PROXY import android.content.Context import android.os.SystemClock -import android.util.Log import androidx.work.BackoffPolicy import androidx.work.Data import androidx.work.OneTimeWorkRequestBuilder @@ -10,15 +10,12 @@ import androidx.work.WorkInfo import androidx.work.WorkManager import androidx.work.WorkRequest import backend.Backend -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.customdownloader.ITcpProxy import com.celzero.bravedns.customdownloader.RetrofitManager import com.celzero.bravedns.data.AppConfig import com.celzero.bravedns.database.TcpProxyEndpoint import com.celzero.bravedns.database.TcpProxyRepository import com.celzero.bravedns.scheduler.PaymentWorker -import com.celzero.bravedns.util.Logger -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_PROXY import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -107,7 +104,7 @@ object TcpProxyHelper : KoinComponent { private fun loadTrie() { cfIpTrie = Backend.newIpTree() cfIpAddresses.forEach { cfIpTrie.set(it, "") } - if (DEBUG) Log.d(LOG_TAG_PROXY, "loadTrie: loading trie for cloudflare ips") + Logger.d(LOG_TAG_PROXY, "loadTrie: loading trie for cloudflare ips") } fun isCloudflareIp(ip: String): Boolean { @@ -116,7 +113,7 @@ object TcpProxyHelper : KoinComponent { return try { cfIpTrie.hasAny(ip) } catch (e: Exception) { - Log.w(LOG_TAG_PROXY, "isCloudflareIp: exception while checking ip: $ip") + Logger.w(LOG_TAG_PROXY, "isCloudflareIp: exception while checking ip: $ip") false } } @@ -138,8 +135,7 @@ object TcpProxyHelper : KoinComponent { val retrofitInterface = retrofit.create(ITcpProxy::class.java) val response = retrofitInterface.getPublicKey(persistentState.appVersion.toString()) - if (DEBUG) - Log.d( + Logger.d( LOG_TAG_PROXY, "new tcp config: ${response?.headers()}, ${response?.message()}, ${response?.raw()?.request?.url}" ) @@ -149,16 +145,16 @@ object TcpProxyHelper : KoinComponent { works = jsonObject.optString(JSON_STATUS, "") == STATUS_OK val minVersionCode = jsonObject.optString(JSON_MIN_VERSION_CODE, "") publicKey = jsonObject.optString(JSON_PUB_KEY, "") - Log.i( + Logger.i( LOG_TAG_PROXY, "tcp response for ${response.raw().request.url}, works? $works, minVersionCode: $minVersionCode, publicKey: $publicKey" ) return works } else { - Log.w(LOG_TAG_PROXY, "unsuccessful response for ${response?.raw()?.request?.url}") + Logger.w(LOG_TAG_PROXY, "unsuccessful response for ${response?.raw()?.request?.url}") } } catch (e: Exception) { - Log.e( + Logger.e( LOG_TAG_PROXY, "publicKeyUsable: exception while checking public key: ${e.message}", e @@ -166,10 +162,10 @@ object TcpProxyHelper : KoinComponent { } return if (isRetryRequired(retryCount) && !works) { - Log.i(Logger.LOG_TAG_DOWNLOAD, "retrying publicKeyUsable for $retryCount") + Logger.i(Logger.LOG_TAG_DOWNLOAD, "retrying publicKeyUsable for $retryCount") publicKeyUsable(retryCount + 1) } else { - Log.i(Logger.LOG_TAG_DOWNLOAD, "retry count exceeded for publicKeyUsable") + Logger.i(Logger.LOG_TAG_DOWNLOAD, "retry count exceeded for publicKeyUsable") works } } @@ -181,7 +177,7 @@ object TcpProxyHelper : KoinComponent { suspend fun isPaymentInitiated(): Boolean { val tcpProxy = tcpProxies.find { it.id == DEFAULT_ID } if (tcpProxy == null) { - Log.w(LOG_TAG_PROXY, "isPaymentInitiated: tcpProxy not found") + Logger.w(LOG_TAG_PROXY, "isPaymentInitiated: tcpProxy not found") return false } return tcpProxy.paymentStatus == PaymentStatus.INITIATED.value @@ -190,7 +186,7 @@ object TcpProxyHelper : KoinComponent { suspend fun isPaymentExpired(): Boolean { val tcpProxy = tcpProxies.find { it.id == DEFAULT_ID } if (tcpProxy == null) { - Log.w(LOG_TAG_PROXY, "isPaymentExpired: tcpProxy not found") + Logger.w(LOG_TAG_PROXY, "isPaymentExpired: tcpProxy not found") return false } return tcpProxy.paymentStatus == PaymentStatus.EXPIRED.value @@ -199,7 +195,7 @@ object TcpProxyHelper : KoinComponent { fun getTcpProxyPaymentStatus(): PaymentStatus { val tcpProxy = tcpProxies.find { it.id == DEFAULT_ID } if (tcpProxy == null) { - Log.w(LOG_TAG_PROXY, "getTcpProxyPaymentStatus: tcpProxy not found") + Logger.w(LOG_TAG_PROXY, "getTcpProxyPaymentStatus: tcpProxy not found") return PaymentStatus.NOT_PAID } return PaymentStatus.values().find { it.value == tcpProxy.paymentStatus } @@ -210,7 +206,7 @@ object TcpProxyHelper : KoinComponent { if (publicKey.isEmpty()) { publicKeyUsable() } else { - Log.i(LOG_TAG_PROXY, "getPublicKey: returning cached public key") + Logger.i(LOG_TAG_PROXY, "getPublicKey: returning cached public key") } return publicKey } @@ -218,7 +214,7 @@ object TcpProxyHelper : KoinComponent { suspend fun updatePaymentStatus(paymentStatus: PaymentStatus) { val tcpProxy = tcpProxies.find { it.id == DEFAULT_ID } if (tcpProxy == null) { - Log.w(LOG_TAG_PROXY, "updatePaymentStatus: tcpProxy not found") + Logger.w(LOG_TAG_PROXY, "updatePaymentStatus: tcpProxy not found") return } tcpProxy.paymentStatus = paymentStatus.value @@ -228,7 +224,7 @@ object TcpProxyHelper : KoinComponent { suspend fun updateToken(token: String) { val tcpProxy = tcpProxies.find { it.id == DEFAULT_ID } if (tcpProxy == null) { - Log.w(LOG_TAG_PROXY, "updateToken: tcpProxy not found") + Logger.w(LOG_TAG_PROXY, "updateToken: tcpProxy not found") return } tcpProxy.token = token @@ -238,7 +234,7 @@ object TcpProxyHelper : KoinComponent { suspend fun updateUrl(url: String) { val tcpProxy = tcpProxies.find { it.id == DEFAULT_ID } if (tcpProxy == null) { - Log.w(LOG_TAG_PROXY, "updateUrl: tcpProxy not found") + Logger.w(LOG_TAG_PROXY, "updateUrl: tcpProxy not found") return } tcpProxy.url = url @@ -247,13 +243,12 @@ object TcpProxyHelper : KoinComponent { fun initiatePaymentVerification(context: Context) { val appContext = context.applicationContext - if (DEBUG) - Log.d(LOG_TAG_PROXY, "initiatePaymentVerification: initiating payment verification") + Logger.d(LOG_TAG_PROXY, "initiatePaymentVerification: initiating payment verification") // if worker is already running, don't start another one val workInfos = WorkManager.getInstance(appContext).getWorkInfosByTag(PAYMENT_WORKER_TAG) if (workInfos.get().any { it.state == WorkInfo.State.RUNNING }) { - Log.i(LOG_TAG_PROXY, "initiatePaymentVerification: worker already running") + Logger.i(LOG_TAG_PROXY, "initiatePaymentVerification: worker already running") return } @@ -272,14 +267,14 @@ object TcpProxyHelper : KoinComponent { .setInitialDelay(10, TimeUnit.SECONDS) .build() - Log.i(LOG_TAG_PROXY, "initiatePaymentVerification: enqueuing payment worker") + Logger.i(LOG_TAG_PROXY, "initiatePaymentVerification: enqueuing payment worker") WorkManager.getInstance(appContext).beginWith(paymentWorker).enqueue() } suspend fun enable(id: Int = DEFAULT_ID) { val tcpProxy = tcpProxies.find { it.id == id } if (tcpProxy == null) { - Log.w(LOG_TAG_PROXY, "enable: tcpProxy not found for id: $id") + Logger.w(LOG_TAG_PROXY, "enable: tcpProxy not found for id: $id") return } @@ -291,7 +286,7 @@ object TcpProxyHelper : KoinComponent { suspend fun disable(id: Int = DEFAULT_ID) { val tcpProxy = tcpProxies.find { it.id == id } if (tcpProxy == null) { - Log.w(LOG_TAG_PROXY, "disable: tcpProxy not found for id: $id") + Logger.w(LOG_TAG_PROXY, "disable: tcpProxy not found for id: $id") return } diff --git a/app/src/full/java/com/celzero/bravedns/service/WireguardManager.kt b/app/src/full/java/com/celzero/bravedns/service/WireguardManager.kt index 35913bf20..2fa1e6f88 100644 --- a/app/src/full/java/com/celzero/bravedns/service/WireguardManager.kt +++ b/app/src/full/java/com/celzero/bravedns/service/WireguardManager.kt @@ -15,11 +15,10 @@ */ package com.celzero.bravedns.service +import Logger.LOG_TAG_PROXY import android.content.Context -import android.util.Log import backend.Backend import backend.WgKey -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.customdownloader.IWireguardWarp import com.celzero.bravedns.customdownloader.RetrofitManager import com.celzero.bravedns.data.AppConfig @@ -27,8 +26,6 @@ import com.celzero.bravedns.database.WgConfigFiles import com.celzero.bravedns.database.WgConfigFilesImmutable import com.celzero.bravedns.database.WgConfigFilesRepository import com.celzero.bravedns.util.Constants.Companion.WIREGUARD_FOLDER_NAME -import com.celzero.bravedns.util.Logger -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_PROXY import com.celzero.bravedns.wireguard.BadConfigException import com.celzero.bravedns.wireguard.Config import com.celzero.bravedns.wireguard.Peer @@ -81,7 +78,7 @@ object WireguardManager : KoinComponent { // increment the id by 1, as the first config id is 0 lastAddedConfigId = db.getLastAddedConfigId() + 1 if (configs.isNotEmpty()) { - Log.i(LOG_TAG_PROXY, "configs already loaded; refreshing...") + Logger.i(LOG_TAG_PROXY, "configs already loaded; refreshing...") } val m = db.getWgConfigs().map { it.toImmutable() } mappings = CopyOnWriteArraySet(m) @@ -97,7 +94,7 @@ object WireguardManager : KoinComponent { .setInterface(config.getInterface()) .addPeers(config.getPeers()) .build() - if (DEBUG) Log.d(LOG_TAG_PROXY, "read wg config: ${it.id}, ${it.name}") + Logger.d(LOG_TAG_PROXY, "read wg config: ${it.id}, ${it.name}") configs.add(c) } } @@ -112,7 +109,7 @@ object WireguardManager : KoinComponent { fun getConfigById(id: Int): Config? { val config = configs.find { it.getId() == id } if (config == null) { - Log.e(LOG_TAG_PROXY, "getConfigById: wg not found: $id, ${configs.size}") + Logger.e(LOG_TAG_PROXY, "getConfigById: wg not found: $id, ${configs.size}") } return config } @@ -120,7 +117,7 @@ object WireguardManager : KoinComponent { fun getConfigFilesById(id: Int): WgConfigFilesImmutable? { val config = mappings.find { it.id == id } if (config == null) { - Log.e(LOG_TAG_PROXY, "getConfigFilesById: wg not found: $id, ${configs.size}") + Logger.e(LOG_TAG_PROXY, "getConfigFilesById: wg not found: $id, ${configs.size}") } return config } @@ -154,7 +151,7 @@ object WireguardManager : KoinComponent { } return false } catch (e: Exception) { - Log.w(LOG_TAG_PROXY, "Exception while checking config active: ${e.message}") + Logger.w(LOG_TAG_PROXY, "Exception while checking config active: ${e.message}") } return false } @@ -175,14 +172,17 @@ object WireguardManager : KoinComponent { fun enableConfig(unmapped: WgConfigFilesImmutable) { val map = mappings.find { it.id == unmapped.id } if (map == null) { - Log.e(LOG_TAG_PROXY, "enableConfig: wg not found, id: ${unmapped.id}, ${mappings.size}") + Logger.e( + LOG_TAG_PROXY, + "enableConfig: wg not found, id: ${unmapped.id}, ${mappings.size}" + ) return } val config = configs.find { it.getId() == map.id } // no need to enable config if it is sec warp if (config == null || config.getId() == SEC_WARP_ID) { - Log.w(LOG_TAG_PROXY, "Config not found or is SEC_WARP: ${map.id}") + Logger.w(LOG_TAG_PROXY, "Config not found or is SEC_WARP: ${map.id}") return } @@ -207,7 +207,7 @@ object WireguardManager : KoinComponent { val proxyProvider = AppConfig.ProxyProvider.WIREGUARD appConfig.addProxy(proxyType, proxyProvider) VpnController.addWireGuardProxy(ProxyManager.ID_WG_BASE + map.id) - Log.i(LOG_TAG_PROXY, "enable wg config: ${map.id}, ${map.name}") + Logger.i(LOG_TAG_PROXY, "enable wg config: ${map.id}, ${map.name}") return } @@ -222,7 +222,7 @@ object WireguardManager : KoinComponent { } val config = configs.find { it.getId() == map.id } if (config == null) { - Log.e(LOG_TAG_PROXY, "canEnableConfig: wg not found, id: ${map.id}, ${configs.size}") + Logger.e(LOG_TAG_PROXY, "canEnableConfig: wg not found, id: ${map.id}, ${configs.size}") return false } return true @@ -245,7 +245,7 @@ object WireguardManager : KoinComponent { fun getConfigName(id: Int): String { val config = configs.find { it.getId() == id } if (config == null) { - Log.e(LOG_TAG_PROXY, "getConfigName: wg not found, id: ${id}, ${configs.size}") + Logger.e(LOG_TAG_PROXY, "getConfigName: wg not found, id: ${id}, ${configs.size}") return "" } return config.getName() @@ -262,7 +262,7 @@ object WireguardManager : KoinComponent { fun disableConfig(unmapped: WgConfigFilesImmutable) { val m = mappings.find { it.id == unmapped.id } if (m == null) { - Log.e( + Logger.e( LOG_TAG_PROXY, "disableConfig: wg not found, id: ${unmapped.id}, ${mappings.size}" ) @@ -272,7 +272,7 @@ object WireguardManager : KoinComponent { val config = configs.find { it.getId() == unmapped.id } // no need to enable config if it is sec warp if (config == null || config.getId() == SEC_WARP_ID) { - Log.w(LOG_TAG_PROXY, "Config not found or is SEC_WARP: ${unmapped.id}") + Logger.w(LOG_TAG_PROXY, "Config not found or is SEC_WARP: ${unmapped.id}") return } @@ -301,7 +301,7 @@ object WireguardManager : KoinComponent { } // directly remove the proxy from the tunnel, instead of calling updateTun VpnController.removeWireGuardProxy(newMap.id) - Log.i(LOG_TAG_PROXY, "disable wg config: ${newMap.id}, ${newMap.name}") + Logger.i(LOG_TAG_PROXY, "disable wg config: ${newMap.id}, ${newMap.name}") return } @@ -319,7 +319,7 @@ object WireguardManager : KoinComponent { val retrofitInterface = retrofit.create(IWireguardWarp::class.java) val response = retrofitInterface.getNewWarpConfig(publicKey, deviceName, locale) - if (DEBUG) Log.d(LOG_TAG_PROXY, "New wg(warp) config: ${response?.body()}") + Logger.d(LOG_TAG_PROXY, "New wg(warp) config: ${response?.body()}") if (response?.isSuccessful == true) { val jsonObject = JSONObject(response.body().toString()) @@ -342,13 +342,13 @@ object WireguardManager : KoinComponent { return config } } catch (e: Exception) { - Log.e(LOG_TAG_PROXY, "err: new wg(warp) config: ${e.message}") + Logger.e(LOG_TAG_PROXY, "err: new wg(warp) config: ${e.message}") } return if (isRetryRequired(retryCount)) { - Log.i(Logger.LOG_TAG_DOWNLOAD, "retrying to getNewWarpConfig") + Logger.i(Logger.LOG_TAG_DOWNLOAD, "retrying to getNewWarpConfig") getNewWarpConfig(id, retryCount + 1) } else { - Log.i(LOG_TAG_PROXY, "retry count exceeded(getNewWarpConfig), returning null") + Logger.i(LOG_TAG_PROXY, "retry count exceeded(getNewWarpConfig), returning null") null } } @@ -368,32 +368,34 @@ object WireguardManager : KoinComponent { val retrofitInterface = retrofit.create(IWireguardWarp::class.java) val response = retrofitInterface.isWarpConfigWorking() - if (DEBUG) - Log.d( - LOG_TAG_PROXY, - "new wg(warp) config: ${response?.headers()}, ${response?.message()}, ${response?.raw()?.request?.url}" - ) + Logger.d( + LOG_TAG_PROXY, + "new wg(warp) config: ${response?.headers()}, ${response?.message()}, ${response?.raw()?.request?.url}" + ) if (response?.isSuccessful == true) { val jsonObject = JSONObject(response.body().toString()) works = jsonObject.optBoolean(JSON_RESPONSE_WORKS, false) val reason = jsonObject.optString(JSON_RESPONSE_REASON, "") - Log.i( + Logger.i( LOG_TAG_PROXY, "warp response for ${response.raw().request.url}, works? $works, reason: $reason" ) } else { - Log.w(LOG_TAG_PROXY, "unsuccessful response for ${response?.raw()?.request?.url}") + Logger.w( + LOG_TAG_PROXY, + "unsuccessful response for ${response?.raw()?.request?.url}" + ) } } catch (e: Exception) { - Log.e(LOG_TAG_PROXY, "err checking warp(works): ${e.message}") + Logger.e(LOG_TAG_PROXY, "err checking warp(works): ${e.message}") } return if (isRetryRequired(retryCount) && !works) { - Log.i(Logger.LOG_TAG_DOWNLOAD, "retrying to getNewWarpConfig") + Logger.i(Logger.LOG_TAG_DOWNLOAD, "retrying to getNewWarpConfig") isWarpWorking(retryCount + 1) } else { - Log.i(LOG_TAG_PROXY, "retry count exceeded(getNewWarpConfig), returning null") + Logger.i(LOG_TAG_PROXY, "retry count exceeded(getNewWarpConfig), returning null") works } } @@ -401,11 +403,11 @@ object WireguardManager : KoinComponent { fun getConfigIdForApp(uid: Int): WgConfigFilesImmutable? { val configId = ProxyManager.getProxyIdForApp(uid) if (configId == "" || !configId.contains(ProxyManager.ID_WG_BASE)) { - if (DEBUG) Log.d(LOG_TAG_PROXY, "app config mapping not found for uid: $uid") + Logger.d(LOG_TAG_PROXY, "app config mapping not found for uid: $uid") // there maybe catch-all config enabled, so return the active catch-all config val catchAllConfig = mappings.find { it.isActive && it.isCatchAll } return if (catchAllConfig == null) { - if (DEBUG) Log.d(LOG_TAG_PROXY, "catch all config not found for uid: $uid") + Logger.d(LOG_TAG_PROXY, "catch all config not found for uid: $uid") null } else { catchAllConfig @@ -421,7 +423,7 @@ object WireguardManager : KoinComponent { val configId = id.substring(ProxyManager.ID_WG_BASE.length) configId.toIntOrNull() ?: INVALID_CONF_ID } catch (e: Exception) { - Log.e(LOG_TAG_PROXY, "err converting string id to int: $id") + Logger.e(LOG_TAG_PROXY, "err converting string id to int: $id") INVALID_CONF_ID } } @@ -429,7 +431,7 @@ object WireguardManager : KoinComponent { private fun parseNewConfigJsonResponse(privateKey: WgKey, jsonObject: JSONObject?): Config? { // get the json tag "wgconf" from the response if (jsonObject == null) { - Log.e(LOG_TAG_PROXY, "new warp config json object is null") + Logger.e(LOG_TAG_PROXY, "new warp config json object is null") return null } @@ -448,19 +450,19 @@ object WireguardManager : KoinComponent { try { Config.parse(configStream) } catch (e: BadConfigException) { - Log.e( + Logger.e( LOG_TAG_PROXY, "err parsing config: ${e.message}, ${e.reason}, ${e.text}, ${e.location}, ${e.section}, ${e.stackTrace}, ${e.cause}" ) null } - Log.i(LOG_TAG_PROXY, "New wireguard config: ${cfg?.getName()}, ${cfg?.getId()}") + Logger.i(LOG_TAG_PROXY, "New wireguard config: ${cfg?.getName()}, ${cfg?.getId()}") return cfg } suspend fun addConfig(config: Config?): Config? { if (config == null) { - Log.e(LOG_TAG_PROXY, "error adding config") + Logger.e(LOG_TAG_PROXY, "error adding config") return null } // increment the id and add the config @@ -475,7 +477,7 @@ object WireguardManager : KoinComponent { .addPeers(config.getPeers()) .build() writeConfigAndUpdateDb(cfg) - if (DEBUG) Log.d(LOG_TAG_PROXY, "add config: ${config.getId()}, ${config.getName()}") + Logger.d(LOG_TAG_PROXY, "add config: ${config.getId()}, ${config.getName()}") return config } @@ -497,7 +499,7 @@ object WireguardManager : KoinComponent { val id = lastAddedConfigId val name = configName.ifEmpty { "wg$id" } val cfg = Config.Builder().setId(id).setName(name).setInterface(wgInterface).build() - if (DEBUG) Log.d(LOG_TAG_PROXY, "adding interface for config: $id, $name") + Logger.d(LOG_TAG_PROXY, "adding interface for config: $id, $name") writeConfigAndUpdateDb(cfg) return cfg } @@ -511,7 +513,7 @@ object WireguardManager : KoinComponent { // update the interface for the config val config = configs.find { it.getId() == configId } if (config == null) { - Log.e(LOG_TAG_PROXY, "updateInterface: wg not found, id: $configId, ${configs.size}") + Logger.e(LOG_TAG_PROXY, "updateInterface: wg not found, id: $configId, ${configs.size}") return null } cfg = @@ -521,7 +523,7 @@ object WireguardManager : KoinComponent { .setInterface(wgInterface) .addPeers(config.getPeers()) .build() - Log.i(LOG_TAG_PROXY, "updating interface for config: $configId, ${config.getName()}") + Logger.i(LOG_TAG_PROXY, "updating interface for config: $configId, ${config.getName()}") val cfgId = ProxyManager.ID_WG_BASE + configId if (configName != config.getName()) { ProxyManager.updateProxyNameForProxyId(cfgId, configName) @@ -536,24 +538,24 @@ object WireguardManager : KoinComponent { fun deleteConfig(id: Int) { val cf = mappings.find { it.id == id } - Log.i(LOG_TAG_PROXY, "deleteConfig start: $id, ${cf?.name}, ${cf?.configPath}") + Logger.i(LOG_TAG_PROXY, "deleteConfig start: $id, ${cf?.name}, ${cf?.configPath}") mappings.forEach { - Log.i(LOG_TAG_PROXY, "deleteConfig: ${it.id}, ${it.name}, ${it.configPath}") + Logger.i(LOG_TAG_PROXY, "deleteConfig: ${it.id}, ${it.name}, ${it.configPath}") } val canDelete = cf?.isDeletable ?: false if (!canDelete) { - Log.e(LOG_TAG_PROXY, "wg config not deletable for id: $id") + Logger.e(LOG_TAG_PROXY, "wg config not deletable for id: $id") return } // delete the config file val config = configs.find { it.getId() == id } if (cf?.isActive == true) { - Log.e(LOG_TAG_PROXY, "wg config is active for id: $id") + Logger.e(LOG_TAG_PROXY, "wg config is active for id: $id") disableConfig(cf) } if (config == null) { - Log.e(LOG_TAG_PROXY, "deleteConfig: wg not found, id: $id, ${configs.size}") + Logger.e(LOG_TAG_PROXY, "deleteConfig: wg not found, id: $id, ${configs.size}") io { db.deleteConfig(id) mappings.remove(mappings.find { it.id == id }) @@ -579,10 +581,10 @@ object WireguardManager : KoinComponent { val config = configs.find { it.getId() == id } val map = mappings.find { it.id == id } if (config == null) { - Log.e(LOG_TAG_PROXY, "updateLockdownConfig: wg not found, id: $id, ${configs.size}") + Logger.e(LOG_TAG_PROXY, "updateLockdownConfig: wg not found, id: $id, ${configs.size}") return } - Log.i(LOG_TAG_PROXY, "updating lockdown for config: $id, ${config.getPeers()}") + Logger.i(LOG_TAG_PROXY, "updating lockdown for config: $id, ${config.getPeers()}") db.updateLockdownConfig(id, isLockdown) val m = mappings.find { it.id == id } ?: return mappings.remove(m) @@ -607,10 +609,10 @@ object WireguardManager : KoinComponent { suspend fun updateCatchAllConfig(id: Int, isEnabled: Boolean) { val config = configs.find { it.getId() == id } if (config == null) { - Log.e(LOG_TAG_PROXY, "updateCatchAllConfig: wg not found, id: $id, ${configs.size}") + Logger.e(LOG_TAG_PROXY, "updateCatchAllConfig: wg not found, id: $id, ${configs.size}") return } - Log.i(LOG_TAG_PROXY, "updating catch all for config: $id, ${config.getName()}") + Logger.i(LOG_TAG_PROXY, "updating catch all for config: $id, ${config.getName()}") db.updateCatchAllConfig(id, isEnabled) val m = mappings.find { it.id == id } ?: return mappings.remove(m) @@ -634,10 +636,10 @@ object WireguardManager : KoinComponent { suspend fun updateOneWireGuardConfig(id: Int, owg: Boolean) { val config = configs.find { it.getId() == id } if (config == null) { - Log.e(LOG_TAG_PROXY, "update one wg: id($id) not found, size: ${configs.size}") + Logger.e(LOG_TAG_PROXY, "update one wg: id($id) not found, size: ${configs.size}") return } - Log.i(LOG_TAG_PROXY, "update one wg, id: $id, ${config.getName()} to $owg") + Logger.i(LOG_TAG_PROXY, "update one wg, id: $id, ${config.getName()} to $owg") db.updateOneWireGuardConfig(id, owg) val m = mappings.find { it.id == id } ?: return mappings.remove(m) @@ -661,7 +663,7 @@ object WireguardManager : KoinComponent { val cfg: Config val config = configs.find { it.getId() == id } if (config == null) { - Log.e(LOG_TAG_PROXY, "addPeer: wg not found, id: $id, ${configs.size}") + Logger.e(LOG_TAG_PROXY, "addPeer: wg not found, id: $id, ${configs.size}") return } val peers = config.getPeers() ?: mutableListOf() @@ -674,7 +676,7 @@ object WireguardManager : KoinComponent { .setInterface(config.getInterface()) .addPeers(newPeers) .build() - Log.i(LOG_TAG_PROXY, "adding peer for config: $id, ${cfg.getName()}, ${newPeers.size}") + Logger.i(LOG_TAG_PROXY, "adding peer for config: $id, ${cfg.getName()}, ${newPeers.size}") writeConfigAndUpdateDb(cfg) } @@ -683,12 +685,12 @@ object WireguardManager : KoinComponent { val cfg: Config val config = configs.find { it.getId() == id } if (config == null) { - Log.e(LOG_TAG_PROXY, "deletePeer: wg not found, id: $id, ${configs.size}") + Logger.e(LOG_TAG_PROXY, "deletePeer: wg not found, id: $id, ${configs.size}") return } val peers = config.getPeers()?.toMutableList() if (peers == null) { - Log.e(LOG_TAG_PROXY, "peers not found for config: $id") + Logger.e(LOG_TAG_PROXY, "peers not found for config: $id") return } val isRemoved = @@ -698,11 +700,10 @@ object WireguardManager : KoinComponent { it.getAllowedIps() == peer.getAllowedIps() && it.getPreSharedKey() == peer.getPreSharedKey() } - if (DEBUG) - Log.d( - LOG_TAG_PROXY, - "new peers: ${peers.size}, ${peer.getPublicKey().base64()} is removed? $isRemoved" - ) + Logger.d( + LOG_TAG_PROXY, + "new peers: ${peers.size}, ${peer.getPublicKey().base64()} is removed? $isRemoved" + ) cfg = Config.Builder() .setId(config.getId()) @@ -710,7 +711,7 @@ object WireguardManager : KoinComponent { .setInterface(config.getInterface()) .addPeers(peers) .build() - Log.i(LOG_TAG_PROXY, "deleting peer for config: $id, ${cfg.getName()}") + Logger.i(LOG_TAG_PROXY, "deleting peer for config: $id, ${cfg.getName()}") writeConfigAndUpdateDb(cfg) } @@ -720,7 +721,7 @@ object WireguardManager : KoinComponent { val fileName = getConfigFileName(cfg.getId()) EncryptedFileManager.writeWireguardConfig(applicationContext, parsedCfg, fileName) val path = getConfigFilePath() + fileName - Log.i(LOG_TAG_PROXY, "writing wg config to file: $path") + Logger.i(LOG_TAG_PROXY, "writing wg config to file: $path") // no need to write the config to the database if it is default config / WARP if (cfg.getId() == WARP_ID || cfg.getId() == SEC_WARP_ID) { return @@ -806,7 +807,7 @@ object WireguardManager : KoinComponent { io { val count = db.deleteOnAppRestore() ProxyManager.removeWgProxies() - Log.i(LOG_TAG_PROXY, "Deleted wg entries: $count") + Logger.i(LOG_TAG_PROXY, "Deleted wg entries: $count") clearLoadedConfigs() load() } diff --git a/app/src/full/java/com/celzero/bravedns/ui/HomeScreenActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/HomeScreenActivity.kt index a57914e8b..fb8f57e57 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/HomeScreenActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/HomeScreenActivity.kt @@ -15,6 +15,10 @@ */ package com.celzero.bravedns.ui +import Logger.LOG_TAG_APP_UPDATE +import Logger.LOG_TAG_BACKUP_RESTORE +import Logger.LOG_TAG_DOWNLOAD +import Logger.LOG_TAG_UI import android.app.UiModeManager import android.content.ActivityNotFoundException import android.content.Context @@ -26,7 +30,6 @@ import android.net.Uri import android.os.Bundle import android.os.PersistableBundle import android.os.SystemClock -import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.biometric.BiometricManager @@ -45,7 +48,6 @@ import by.kirich1409.viewbindingdelegate.viewBinding import com.celzero.bravedns.BuildConfig import com.celzero.bravedns.NonStoreAppUpdater import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.backup.BackupHelper import com.celzero.bravedns.backup.BackupHelper.Companion.BACKUP_FILE_EXTN import com.celzero.bravedns.backup.BackupHelper.Companion.INTENT_RESTART_APP @@ -62,11 +64,6 @@ import com.celzero.bravedns.ui.activity.PauseActivity import com.celzero.bravedns.ui.activity.WelcomeActivity import com.celzero.bravedns.util.Constants import com.celzero.bravedns.util.Constants.Companion.PKG_NAME_PLAY_STORE -import com.celzero.bravedns.util.Logger -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_APP_UPDATE -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_BACKUP_RESTORE -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_DOWNLOAD -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_UI import com.celzero.bravedns.util.RemoteFileTagUtil import com.celzero.bravedns.util.Themes.Companion.getCurrentTheme import com.celzero.bravedns.util.Utilities @@ -188,7 +185,7 @@ class HomeScreenActivity : AppCompatActivity(R.layout.activity_home_screen) { object : BiometricPrompt.AuthenticationCallback() { override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { super.onAuthenticationError(errorCode, errString) - Log.i( + Logger.i( LOG_TAG_UI, "Biometric authentication error (code: $errorCode): $errString" ) @@ -227,7 +224,7 @@ class HomeScreenActivity : AppCompatActivity(R.layout.activity_home_screen) { super.onAuthenticationSucceeded(result) // biometricPromptRetryCount = 1 persistentState.biometricAuthTime = SystemClock.elapsedRealtime() - Log.i(LOG_TAG_UI, "Biometric success @ ${System.currentTimeMillis()}") + Logger.i(LOG_TAG_UI, "Biometric success @ ${System.currentTimeMillis()}") } override fun onAuthenticationFailed() { @@ -237,7 +234,7 @@ class HomeScreenActivity : AppCompatActivity(R.layout.activity_home_screen) { getString(R.string.hs_biometeric_failed), Toast.LENGTH_SHORT ) - Log.i(LOG_TAG_UI, "Biometric authentication failed") + Logger.i(LOG_TAG_UI, "Biometric authentication failed") // show the biometric prompt again only if the ui is in foreground if (isInForeground()) biometricPrompt.authenticate(promptInfo) } @@ -281,7 +278,7 @@ class HomeScreenActivity : AppCompatActivity(R.layout.activity_home_screen) { Toast.LENGTH_SHORT ) } else if (intent.getBooleanExtra(INTENT_RESTART_APP, false)) { - Log.i(LOG_TAG_UI, "Restart from restore, so refreshing app database...") + Logger.i(LOG_TAG_UI, "Restart from restore, so refreshing app database...") io { rdb.refresh(RefreshDatabase.ACTION_REFRESH_RESTORE) } } } @@ -319,7 +316,7 @@ class HomeScreenActivity : AppCompatActivity(R.layout.activity_home_screen) { } private fun startRestore(fileUri: Uri) { - Log.i(LOG_TAG_BACKUP_RESTORE, "invoke worker to initiate the restore process") + Logger.i(LOG_TAG_BACKUP_RESTORE, "invoke worker to initiate the restore process") val data = Data.Builder() data.putString(BackupHelper.DATA_BUILDER_RESTORE_URI, fileUri.toString()) @@ -342,7 +339,7 @@ class HomeScreenActivity : AppCompatActivity(R.layout.activity_home_screen) { // observer for custom download manager worker workManager.getWorkInfosByTagLiveData(RestoreAgent.TAG).observe(this) { workInfoList -> val workInfo = workInfoList?.getOrNull(0) ?: return@observe - Log.i( + Logger.i( LOG_TAG_BACKUP_RESTORE, "WorkManager state: ${workInfo.state} for ${RestoreAgent.TAG}" ) @@ -425,7 +422,7 @@ class HomeScreenActivity : AppCompatActivity(R.layout.activity_home_screen) { if (!isNewVersion()) return val version = getLatestVersion() - Log.i(LOG_TAG_UI, "New version detected, updating the app version, version: $version") + Logger.i(LOG_TAG_UI, "New version detected, updating the app version, version: $version") persistentState.appVersion = version persistentState.showWhatsNewChip = true @@ -452,7 +449,7 @@ class HomeScreenActivity : AppCompatActivity(R.layout.activity_home_screen) { val diff = System.currentTimeMillis() - persistentState.lastAppUpdateCheck val daysElapsed = TimeUnit.MILLISECONDS.toDays(diff) - Log.i(LOG_TAG_UI, "App update check initiated, number of days: $daysElapsed") + Logger.i(LOG_TAG_UI, "App update check initiated, number of days: $daysElapsed") if (daysElapsed <= 1L) return checkForUpdate() @@ -473,11 +470,9 @@ class HomeScreenActivity : AppCompatActivity(R.layout.activity_home_screen) { // Check updates only for play store / website version. Not fDroid. if (!isPlayStoreFlavour() && !isWebsiteFlavour()) { - if (DEBUG) - Log.d( - LOG_TAG_APP_UPDATE, - "Check for update: Not play or website- ${BuildConfig.FLAVOR}" - ) + Logger.d(LOG_TAG_APP_UPDATE, + "Check for update: Not play or website- ${BuildConfig.FLAVOR}" + ) return } @@ -489,7 +484,7 @@ class HomeScreenActivity : AppCompatActivity(R.layout.activity_home_screen) { installStateUpdatedListener ) // Might be play updater or web updater } catch (e: Exception) { - Log.e(LOG_TAG_APP_UPDATE, "err in app update check: ${e.message}", e) + Logger.e(LOG_TAG_APP_UPDATE, "err in app update check: ${e.message}", e) showDownloadDialog( AppUpdater.InstallSource.STORE, getString(R.string.download_update_dialog_failure_title), @@ -505,7 +500,7 @@ class HomeScreenActivity : AppCompatActivity(R.layout.activity_home_screen) { installStateUpdatedListener ) // Always web updater } catch (e: Exception) { - Log.e(LOG_TAG_APP_UPDATE, "Error in app (web) update check: ${e.message}", e) + Logger.e(LOG_TAG_APP_UPDATE, "Error in app (web) update check: ${e.message}", e) showDownloadDialog( AppUpdater.InstallSource.OTHER, getString(R.string.download_update_dialog_failure_title), @@ -527,7 +522,7 @@ class HomeScreenActivity : AppCompatActivity(R.layout.activity_home_screen) { private val installStateUpdatedListener = object : AppUpdater.InstallStateListener { override fun onStateUpdate(state: AppUpdater.InstallState) { - Log.i(LOG_TAG_UI, "InstallStateUpdatedListener: state: " + state.status) + Logger.i(LOG_TAG_UI, "InstallStateUpdatedListener: state: " + state.status) when (state.status) { AppUpdater.InstallStatus.DOWNLOADED -> { // CHECK THIS if AppUpdateType.FLEXIBLE, otherwise you can skip @@ -663,7 +658,7 @@ class HomeScreenActivity : AppCompatActivity(R.layout.activity_home_screen) { startActivity(intent) } catch (e: ActivityNotFoundException) { showToastUiCentered(this, getString(R.string.no_browser_error), Toast.LENGTH_SHORT) - Log.w(Logger.LOG_TAG_VPN, "Failure opening rethink download link: ${e.message}", e) + Logger.w(Logger.LOG_TAG_VPN, "Failure opening rethink download link: ${e.message}", e) } } @@ -672,7 +667,7 @@ class HomeScreenActivity : AppCompatActivity(R.layout.activity_home_screen) { try { appUpdateManager.unregisterListener(installStateUpdatedListener) } catch (e: IllegalArgumentException) { - Log.w(LOG_TAG_DOWNLOAD, "Unregister receiver exception") + Logger.w(LOG_TAG_DOWNLOAD, "Unregister receiver exception") } } diff --git a/app/src/full/java/com/celzero/bravedns/ui/NotificationHandlerDialog.kt b/app/src/full/java/com/celzero/bravedns/ui/NotificationHandlerDialog.kt index cb1aaf0f4..c564c8bc7 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/NotificationHandlerDialog.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/NotificationHandlerDialog.kt @@ -15,12 +15,12 @@ */ package com.celzero.bravedns.ui +import Logger.LOG_TAG_VPN import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.provider.Settings -import android.util.Log import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import com.celzero.bravedns.R @@ -28,7 +28,6 @@ import com.celzero.bravedns.service.VpnController import com.celzero.bravedns.ui.activity.AppListActivity import com.celzero.bravedns.ui.activity.PauseActivity import com.celzero.bravedns.util.Constants -import com.celzero.bravedns.util.Logger import com.google.android.material.dialog.MaterialAlertDialogBuilder class NotificationHandlerDialog : AppCompatActivity() { @@ -76,7 +75,7 @@ class NotificationHandlerDialog : AppCompatActivity() { } private fun trampoline(trampolineType: TrampolineType) { - Log.i(Logger.LOG_TAG_VPN, "act on notification, notification type: $trampolineType") + Logger.i(LOG_TAG_VPN, "act on notification, notification type: $trampolineType") when (trampolineType) { TrampolineType.ACCESSIBILITY_SERVICE_FAILURE_DIALOG -> { handleAccessibilitySettings() diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/CheckoutActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/CheckoutActivity.kt index c6b5d74c5..a0d95e75f 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/CheckoutActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/CheckoutActivity.kt @@ -22,7 +22,6 @@ import android.os.Bundle import android.text.Spannable import android.text.SpannableStringBuilder import android.text.style.ForegroundColorSpan -import android.util.Log import android.view.View import android.widget.RadioButton import androidx.appcompat.app.AppCompatActivity @@ -32,12 +31,10 @@ import androidx.work.WorkManager import backend.Backend import by.kirich1409.viewbindingdelegate.viewBinding import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.databinding.ActivityCheckoutProxyBinding import com.celzero.bravedns.service.EncryptedFileManager import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.service.TcpProxyHelper -import com.celzero.bravedns.util.Logger import com.celzero.bravedns.util.Themes import com.celzero.bravedns.util.UIUtils.fetchColor import kotlinx.coroutines.Dispatchers @@ -95,9 +92,9 @@ class CheckoutActivity : AppCompatActivity(R.layout.activity_checkout_proxy) { handleKeys() } - UUID.randomUUID().toString().let { uuid -> Log.d(Logger.LOG_TAG_PROXY, "UUID: $uuid") } + UUID.randomUUID().toString().let { uuid -> Logger.d(Logger.LOG_TAG_PROXY, "UUID: $uuid") } generateRandomHexToken(TOKEN_LENGTH).let { token -> - Log.d(Logger.LOG_TAG_PROXY, "Token: $token") + Logger.d(Logger.LOG_TAG_PROXY, "Token: $token") } setSpannablePricing(b.plan1MonthButton, "1 Month / 1.99", "( 1.99 / month )") setSpannablePricing(b.plan3MonthsButton, "3 Months / 3.99", "( 1.33 / month )") @@ -106,7 +103,7 @@ class CheckoutActivity : AppCompatActivity(R.layout.activity_checkout_proxy) { private fun handlePaymentStatusUi() { val paymentStatus: TcpProxyHelper.PaymentStatus = TcpProxyHelper.getTcpProxyPaymentStatus() - if (DEBUG) Log.d(Logger.LOG_TAG_PROXY, "Payment Status: $paymentStatus") + Logger.d(Logger.LOG_TAG_PROXY, "Payment Status: $paymentStatus") when (paymentStatus) { TcpProxyHelper.PaymentStatus.INITIATED -> { b.paymentAwaitingContainer.visibility = View.VISIBLE @@ -148,7 +145,7 @@ class CheckoutActivity : AppCompatActivity(R.layout.activity_checkout_proxy) { workManager.getWorkInfosByTagLiveData(TcpProxyHelper.PAYMENT_WORKER_TAG).observe(this) { workInfoList -> val workInfo = workInfoList?.getOrNull(0) ?: return@observe - Log.i( + Logger.i( Logger.LOG_TAG_PROXY, "WorkManager state: ${workInfo.state} for ${TcpProxyHelper.PAYMENT_WORKER_TAG}" ) @@ -177,10 +174,10 @@ class CheckoutActivity : AppCompatActivity(R.layout.activity_checkout_proxy) { io { try { val key = TcpProxyHelper.getPublicKey() - Log.d(Logger.LOG_TAG_PROXY, "Public Key: $key") + Logger.d(Logger.LOG_TAG_PROXY, "Public Key: $key") val encryptedKey = Backend.newPipKey(key, "") val blind = encryptedKey.blind() - Log.d(Logger.LOG_TAG_PROXY, "Blind: $blind") + Logger.d(Logger.LOG_TAG_PROXY, "Blind: $blind") val path = File( this.filesDir.canonicalPath + @@ -191,9 +188,9 @@ class CheckoutActivity : AppCompatActivity(R.layout.activity_checkout_proxy) { ) EncryptedFileManager.writeTcpConfig(this, blind, TcpProxyHelper.PIP_KEY_FILE_NAME) val content = EncryptedFileManager.read(this, path) - Log.d(Logger.LOG_TAG_PROXY, "Content: $content") + Logger.d(Logger.LOG_TAG_PROXY, "Content: $content") } catch (e: Exception) { - Log.e(Logger.LOG_TAG_PROXY, "Exception in handleKeys: ${e.message}", e) + Logger.e(Logger.LOG_TAG_PROXY, "err in handleKeys: ${e.message}", e) } } } diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/MiscSettingsActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/MiscSettingsActivity.kt index 131d5697c..330fbdd67 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/MiscSettingsActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/MiscSettingsActivity.kt @@ -15,6 +15,9 @@ */ package com.celzero.bravedns.ui.activity +import Logger.LOG_TAG_UI +import Logger.LOG_TAG_VPN +import Logger.updateConfigLevel import android.Manifest import android.app.LocaleManager import android.content.ActivityNotFoundException @@ -28,7 +31,6 @@ import android.os.Bundle import android.os.Environment import android.os.LocaleList import android.provider.Settings -import android.util.Log import android.view.View import android.widget.CompoundButton import android.widget.Toast @@ -52,8 +54,6 @@ import com.celzero.bravedns.net.go.GoVpnAdapter import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.ui.bottomsheet.BackupRestoreBottomSheet import com.celzero.bravedns.util.Constants -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_UI -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_VPN import com.celzero.bravedns.util.NotificationActionType import com.celzero.bravedns.util.PcapMode import com.celzero.bravedns.util.Themes @@ -342,7 +342,7 @@ class MiscSettingsActivity : AppCompatActivity(R.layout.activity_misc_settings) getString(R.string.intent_launch_error, intent.data), Toast.LENGTH_SHORT ) - Log.w(LOG_TAG_UI, "activity not found ${e.message}", e) + Logger.w(LOG_TAG_UI, "activity not found ${e.message}", e) } } @@ -360,9 +360,9 @@ class MiscSettingsActivity : AppCompatActivity(R.layout.activity_misc_settings) xpp.next() } } catch (e: XmlPullParserException) { - Log.e(LOG_TAG_UI, "error parsing locale_config.xml", e) + Logger.e(LOG_TAG_UI, "error parsing locale_config.xml", e) } catch (e: IOException) { - Log.e(LOG_TAG_UI, "error parsing locale_config.xml", e) + Logger.e(LOG_TAG_UI, "error parsing locale_config.xml", e) } return LocaleListCompat.forLanguageTags(tagsList.joinToString(",")) @@ -449,6 +449,7 @@ class MiscSettingsActivity : AppCompatActivity(R.layout.activity_misc_settings) persistentState.goLoggerLevel = which.toLong() GoVpnAdapter.setLogLevel(persistentState.goLoggerLevel) + updateConfigLevel(persistentState.goLoggerLevel) } alertBuilder.create().show() } @@ -558,11 +559,11 @@ class MiscSettingsActivity : AppCompatActivity(R.layout.activity_misc_settings) registerForActivityResult(ActivityResultContracts.RequestPermission()) { persistentState.shouldRequestNotificationPermission = it if (it) { - Log.i(LOG_TAG_VPN, "User allowed notification permission for the app") + Logger.i(LOG_TAG_VPN, "User allowed notification permission for the app") b.settingsActivityAppNotificationRl.visibility = View.VISIBLE b.settingsActivityAppNotificationSwitch.isChecked = true } else { - Log.w(LOG_TAG_VPN, "User rejected notification permission for the app") + Logger.w(LOG_TAG_VPN, "User rejected notification permission for the app") b.settingsActivityAppNotificationRl.visibility = View.VISIBLE b.settingsActivityAppNotificationSwitch.isChecked = false invokeAndroidNotificationSetting() @@ -641,12 +642,12 @@ class MiscSettingsActivity : AppCompatActivity(R.layout.activity_misc_settings) // check for storage permissions if (!checkStoragePermissions()) { // request for storage permissions - Log.i(LOG_TAG_VPN, "requesting for storage permissions") + Logger.i(LOG_TAG_VPN, "requesting for storage permissions") requestForStoragePermissions() return } - Log.i(LOG_TAG_VPN, "storage permission granted, creating pcap file") + Logger.i(LOG_TAG_VPN, "storage permission granted, creating pcap file") try { val file = makePcapFile() if (file == null) { @@ -693,7 +694,7 @@ class MiscSettingsActivity : AppCompatActivity(R.layout.activity_misc_settings) } file } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "error creating pcap file ${e.message}", e) + Logger.e(LOG_TAG_VPN, "error creating pcap file ${e.message}", e) null } } @@ -746,7 +747,7 @@ class MiscSettingsActivity : AppCompatActivity(R.layout.activity_misc_settings) getString(R.string.notification_screen_error), Toast.LENGTH_SHORT ) - Log.w(LOG_TAG_UI, "activity not found ${e.message}", e) + Logger.w(LOG_TAG_UI, "activity not found ${e.message}", e) } } diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/ProxySettingsActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/ProxySettingsActivity.kt index 032d0b073..dc08c21af 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/ProxySettingsActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/ProxySettingsActivity.kt @@ -15,6 +15,8 @@ */ package com.celzero.bravedns.ui.activity +import Logger.LOG_TAG_PROXY +import Logger.LOG_TAG_UI import android.app.Dialog import android.content.ActivityNotFoundException import android.content.Context @@ -22,7 +24,6 @@ import android.content.Intent import android.content.res.Configuration import android.content.res.Configuration.UI_MODE_NIGHT_YES import android.os.Bundle -import android.util.Log import android.view.View import android.view.Window import android.view.WindowManager @@ -40,7 +41,6 @@ import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import by.kirich1409.viewbindingdelegate.viewBinding import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.data.AppConfig import com.celzero.bravedns.database.ProxyEndpoint import com.celzero.bravedns.databinding.DialogSetProxyBinding @@ -53,9 +53,6 @@ import com.celzero.bravedns.service.VpnController import com.celzero.bravedns.service.WireguardManager import com.celzero.bravedns.ui.bottomsheet.OrbotBottomSheet import com.celzero.bravedns.util.Constants -import com.celzero.bravedns.util.Logger -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_PROXY -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_UI import com.celzero.bravedns.util.OrbotHelper import com.celzero.bravedns.util.Themes.Companion.getCurrentTheme import com.celzero.bravedns.util.UIUtils @@ -447,7 +444,7 @@ class ProxySettingsActivity : AppCompatActivity(R.layout.fragment_proxy_configur } private fun displayTcpProxyUi() { - // v055b, no-op + // v055f, no-op return val tcpProxies = TcpProxyHelper.getActiveTcpProxy() @@ -457,7 +454,7 @@ class ProxySettingsActivity : AppCompatActivity(R.layout.fragment_proxy_configur return } - Log.i( + Logger.i( LOG_TAG_UI, "displayTcpProxyUi: ${tcpProxies?.isActive}, ${tcpProxies?.name}, ${tcpProxies?.url}" ) @@ -482,7 +479,7 @@ class ProxySettingsActivity : AppCompatActivity(R.layout.fragment_proxy_configur val resId = UIUtils.getProxyStatusStringRes(statusId) val s = getString(resId).replaceFirstChar(Char::titlecase) wgStatus += getString(R.string.ci_ip_label, it.getName(), s.padStart(1, ' ')) + "\n" - if (DEBUG) Log.d(LOG_TAG_PROXY, "current proxy status for $id: $s") + Logger.d(LOG_TAG_PROXY, "current proxy status for $id: $s") } else { wgStatus += getString( @@ -492,7 +489,7 @@ class ProxySettingsActivity : AppCompatActivity(R.layout.fragment_proxy_configur .replaceFirstChar(Char::titlecase) .padStart(1, ' ') ) + "\n" - if (DEBUG) Log.d(LOG_TAG_PROXY, "current proxy status is null for $id") + Logger.d(LOG_TAG_PROXY, "current proxy status is null for $id") } } wgStatus = wgStatus.trimEnd() @@ -720,7 +717,7 @@ class ProxySettingsActivity : AppCompatActivity(R.layout.fragment_proxy_configur errorTxt.text = getString(R.string.settings_http_proxy_error_text1) } } catch (e: NumberFormatException) { - Log.w(Logger.LOG_TAG_VPN, "Error: ${e.message}", e) + Logger.w(LOG_TAG_PROXY, "err: ${e.message}", e) errorTxt.text = getString(R.string.settings_http_proxy_error_text2) isValid = false } @@ -1004,12 +1001,12 @@ class ProxySettingsActivity : AppCompatActivity(R.layout.fragment_proxy_configur isUdp: Boolean ): ProxyEndpoint? { if (ip.isNullOrEmpty()) { - Log.w(LOG_TAG_PROXY, "cannot construct proxy with values ip: $ip, port: $port") + Logger.w(LOG_TAG_PROXY, "cannot construct proxy with values ip: $ip, port: $port") return null } if (mode == ProxyManager.ProxyMode.SOCKS5 && (!isValidPort(port))) { - Log.w(LOG_TAG_PROXY, "cannot construct proxy with values ip: $ip, port: $port") + Logger.w(LOG_TAG_PROXY, "cannot construct proxy with values ip: $ip, port: $port") return null } diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/TcpProxyMainActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/TcpProxyMainActivity.kt index 2ff07ae4e..3db8efe66 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/TcpProxyMainActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/TcpProxyMainActivity.kt @@ -1,10 +1,10 @@ package com.celzero.bravedns.ui.activity +import Logger.LOG_TAG_UI import android.content.Context import android.content.Intent import android.content.res.Configuration import android.os.Bundle -import android.util.Log import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity @@ -22,7 +22,6 @@ import com.celzero.bravedns.service.WireguardManager.SEC_WARP_ID import com.celzero.bravedns.service.WireguardManager.WARP_ID import com.celzero.bravedns.service.WireguardManager.isWarpWorking import com.celzero.bravedns.ui.dialog.WgIncludeAppsDialog -import com.celzero.bravedns.util.Logger import com.celzero.bravedns.util.Themes import com.celzero.bravedns.util.Utilities import com.celzero.bravedns.viewmodel.ProxyAppsMappingViewModel @@ -66,7 +65,7 @@ class TcpProxyMainActivity : AppCompatActivity(R.layout.activity_tcp_proxy) { return } - Log.i(Logger.LOG_TAG_UI, "displayTcpProxyUi: ${tcpProxies.name}, ${tcpProxies.url}") + Logger.i(LOG_TAG_UI, "displayTcpProxyUi: ${tcpProxies.name}, ${tcpProxies.url}") b.tcpProxySwitch.isChecked = true b.tcpProxyStatus.text = "Active" // getString(R.string.tcp_proxy_description_active) } @@ -259,7 +258,7 @@ class TcpProxyMainActivity : AppCompatActivity(R.layout.activity_tcp_proxy) { private suspend fun fetchWarpConfigFromServer() { val config = WireguardManager.getNewWarpConfig(SEC_WARP_ID) - Log.i(Logger.LOG_TAG_PROXY, "new config from server: ${config?.getName()}") + Logger.i(Logger.LOG_TAG_PROXY, "new config from server: ${config?.getName()}") if (config == null) { showConfigCreationError() return diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/UniversalFirewallSettingsActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/UniversalFirewallSettingsActivity.kt index 69a8e0072..cc5790def 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/UniversalFirewallSettingsActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/UniversalFirewallSettingsActivity.kt @@ -15,23 +15,21 @@ */ package com.celzero.bravedns.ui.activity +import Logger.LOG_TAG_FIREWALL import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.content.res.Configuration import android.os.Bundle import android.provider.Settings -import android.util.Log import android.widget.CompoundButton import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import by.kirich1409.viewbindingdelegate.viewBinding import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.databinding.ActivityUniversalFirewallSettingsBinding import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.util.BackgroundAccessibilityService -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_FIREWALL import com.celzero.bravedns.util.Themes import com.celzero.bravedns.util.Utilities import com.google.android.material.dialog.MaterialAlertDialogBuilder @@ -226,11 +224,10 @@ class UniversalFirewallSettingsActivity : BackgroundAccessibilityService::class.java ) - if (DEBUG) - Log.d( - LOG_TAG_FIREWALL, - "backgroundEnabled? ${persistentState.getBlockAppWhenBackground()}, isServiceEnabled? $isAccessibilityServiceEnabled, isServiceRunning? $isAccessibilityServiceRunning" - ) + Logger.d( + LOG_TAG_FIREWALL, + "backgroundEnabled? ${persistentState.getBlockAppWhenBackground()}, isServiceEnabled? $isAccessibilityServiceEnabled, isServiceRunning? $isAccessibilityServiceRunning" + ) val isAccessibilityServiceFunctional = isAccessibilityServiceRunning && isAccessibilityServiceEnabled @@ -274,7 +271,7 @@ class UniversalFirewallSettingsActivity : getString(R.string.alert_firewall_accessibility_exception), Toast.LENGTH_SHORT ) - Log.e(LOG_TAG_FIREWALL, "Failure accessing accessibility settings: ${e.message}", e) + Logger.e(LOG_TAG_FIREWALL, "Failure accessing accessibility settings: ${e.message}", e) } } } diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigDetailActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigDetailActivity.kt index 7afe3fd83..035363746 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigDetailActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigDetailActivity.kt @@ -15,11 +15,11 @@ */ package com.celzero.bravedns.ui.activity +import Logger.LOG_TAG_PROXY import android.content.Context import android.content.Intent import android.content.res.Configuration import android.os.Bundle -import android.util.Log import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity @@ -36,7 +36,6 @@ import com.celzero.bravedns.service.WireguardManager import com.celzero.bravedns.service.WireguardManager.INVALID_CONF_ID import com.celzero.bravedns.ui.dialog.WgAddPeerDialog import com.celzero.bravedns.ui.dialog.WgIncludeAppsDialog -import com.celzero.bravedns.util.Logger import com.celzero.bravedns.util.Themes import com.celzero.bravedns.util.UIUtils import com.celzero.bravedns.util.Utilities @@ -378,7 +377,7 @@ class WgConfigDetailActivity : AppCompatActivity(R.layout.activity_wg_detail) { io { val config = WireguardManager.getConfigFilesById(configId) if (config == null) { - Log.e(Logger.LOG_TAG_PROXY, "updateCatchAll: config not found for $configId") + Logger.e(LOG_TAG_PROXY, "updateCatchAll: config not found for $configId") return@io } if (WireguardManager.canEnableConfig(config)) { diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigEditorActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigEditorActivity.kt index ca865076e..71672d79d 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigEditorActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigEditorActivity.kt @@ -15,10 +15,11 @@ */ package com.celzero.bravedns.ui.activity +import Logger.LOG_TAG_PROXY +import Logger.throwableToException import android.content.Context import android.content.res.Configuration import android.os.Bundle -import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope @@ -29,7 +30,6 @@ import com.celzero.bravedns.databinding.ActivityWgConfigEditorBinding import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.service.WireguardManager import com.celzero.bravedns.ui.activity.WgConfigDetailActivity.Companion.INTENT_EXTRA_WG_TYPE -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_PROXY import com.celzero.bravedns.util.Themes import com.celzero.bravedns.util.UIUtils.clipboardCopy import com.celzero.bravedns.util.Utilities @@ -197,7 +197,8 @@ class WgConfigEditorActivity : AppCompatActivity(R.layout.activity_wg_config_edi return wgConfig } catch (e: Throwable) { val error = ErrorMessages[this, e] - Log.e(LOG_TAG_PROXY, "Exception while parsing wg interface: $error", e) + val ex = throwableToException(e) + Logger.e(LOG_TAG_PROXY, "err while parsing wg interface: $error", ex) uiCtx { Utilities.showToastUiCentered(this, error, Toast.LENGTH_LONG) } return null } diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/WgMainActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/WgMainActivity.kt index 4602f27ed..3542e8c66 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/WgMainActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/WgMainActivity.kt @@ -15,12 +15,12 @@ */ package com.celzero.bravedns.ui.activity +import Logger.LOG_TAG_PROXY import android.content.Context import android.content.Intent import android.content.res.ColorStateList import android.content.res.Configuration import android.os.Bundle -import android.util.Log import android.view.View import android.widget.Toast import androidx.activity.addCallback @@ -36,7 +36,6 @@ import com.celzero.bravedns.data.AppConfig import com.celzero.bravedns.databinding.ActivityWireguardMainBinding import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.service.WireguardManager -import com.celzero.bravedns.util.Logger import com.celzero.bravedns.util.QrCodeFromFileScanner import com.celzero.bravedns.util.Themes import com.celzero.bravedns.util.TunnelImporter @@ -79,17 +78,17 @@ class WgMainActivity : val qrCodeFromFileScanner = QrCodeFromFileScanner(contentResolver, QRCodeReader()) val result = qrCodeFromFileScanner.scan(data) - Log.i(Logger.LOG_TAG_PROXY, "result: $result, data: $data") + Logger.i(LOG_TAG_PROXY, "result: $result, data: $data") if (result != null) { withContext(Dispatchers.Main) { - Log.i(Logger.LOG_TAG_PROXY, "result: ${result.text}") + Logger.i(LOG_TAG_PROXY, "result: ${result.text}") TunnelImporter.importTunnel(result.text) { Utilities.showToastUiCentered( this@WgMainActivity, it.toString(), Toast.LENGTH_LONG ) - Log.e(Logger.LOG_TAG_PROXY, it.toString()) + Logger.e(LOG_TAG_PROXY, it.toString()) } } } else { @@ -103,7 +102,7 @@ class WgMainActivity : message, Toast.LENGTH_LONG ) - Log.e(Logger.LOG_TAG_PROXY, message) + Logger.e(LOG_TAG_PROXY, message) } } catch (e: Exception) { val message = @@ -116,11 +115,11 @@ class WgMainActivity : message, Toast.LENGTH_LONG ) - Log.e(Logger.LOG_TAG_PROXY, e.message, e) + Logger.e(LOG_TAG_PROXY, e.message ?: "err tun import", e) } } else { TunnelImporter.importTunnel(contentResolver, data) { - Log.e(Logger.LOG_TAG_PROXY, it.toString()) + Logger.e(LOG_TAG_PROXY, it.toString()) Utilities.showToastUiCentered( this@WgMainActivity, it.toString(), @@ -142,7 +141,7 @@ class WgMainActivity : it.toString(), Toast.LENGTH_LONG ) - Log.e(Logger.LOG_TAG_PROXY, it.toString()) + Logger.e(LOG_TAG_PROXY, it.toString()) } } } diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/AppDomainRulesBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/AppDomainRulesBottomSheet.kt index fbe4be7e4..6b2c4aa49 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/AppDomainRulesBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/AppDomainRulesBottomSheet.kt @@ -15,10 +15,10 @@ */ package com.celzero.bravedns.ui.bottomsheet +import Logger.LOG_TAG_FIREWALL import android.content.DialogInterface import android.content.res.Configuration import android.os.Bundle -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -30,7 +30,6 @@ import com.celzero.bravedns.databinding.BottomSheetAppConnectionsBinding import com.celzero.bravedns.service.DomainRulesManager import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.util.Constants.Companion.INVALID_UID -import com.celzero.bravedns.util.Logger import com.celzero.bravedns.util.Themes.Companion.getBottomsheetCurrentTheme import com.celzero.bravedns.util.UIUtils.updateHtmlEncodedText import com.google.android.material.bottomsheet.BottomSheetDialogFragment @@ -124,7 +123,7 @@ class AppDomainRulesBottomSheet : BottomSheetDialogFragment() { io { // no need to send port number for the app info screen domainRule = DomainRulesManager.status(domain, uid) - Log.d("FirewallManager", "Set selection of ip: $domain, ${domainRule.id}") + Logger.d(LOG_TAG_FIREWALL, "Set selection of ip: $domain, ${domainRule.id}") uiCtx { when (domainRule) { DomainRulesManager.Status.TRUST -> { @@ -173,7 +172,7 @@ class AppDomainRulesBottomSheet : BottomSheetDialogFragment() { } private fun applyDomainRule(status: DomainRulesManager.Status) { - Log.i(Logger.LOG_TAG_FIREWALL, "domain rule for uid: $uid:$domain (${status.name})") + Logger.i(LOG_TAG_FIREWALL, "domain rule for uid: $uid:$domain (${status.name})") domainRule = status // set port number as null for all the rules applied from this screen diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/AppIpRulesBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/AppIpRulesBottomSheet.kt index d4e8a77d0..fb9a8b85d 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/AppIpRulesBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/AppIpRulesBottomSheet.kt @@ -15,10 +15,10 @@ */ package com.celzero.bravedns.ui.bottomsheet +import Logger.LOG_TAG_FIREWALL import android.content.DialogInterface import android.content.res.Configuration import android.os.Bundle -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -32,7 +32,6 @@ import com.celzero.bravedns.service.IpRulesManager import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.util.Constants.Companion.INVALID_UID import com.celzero.bravedns.util.CustomLinearLayoutManager -import com.celzero.bravedns.util.Logger import com.celzero.bravedns.util.Themes.Companion.getBottomsheetCurrentTheme import com.celzero.bravedns.util.UIUtils.updateHtmlEncodedText import com.google.android.material.bottomsheet.BottomSheetDialogFragment @@ -143,7 +142,7 @@ class AppIpRulesBottomSheet : BottomSheetDialogFragment() { io { // no need to send port number for the app info screen ipRule = IpRulesManager.getMostSpecificRuleMatch(uid, ipAddress) - Log.d("FirewallManager", "Set selection of ip: $ipAddress, ${ipRule.id}") + Logger.d(LOG_TAG_FIREWALL, "Set selection of ip: $ipAddress, ${ipRule.id}") uiCtx { when (ipRule) { IpRulesManager.IpRuleStatus.TRUST -> { @@ -195,7 +194,7 @@ class AppIpRulesBottomSheet : BottomSheetDialogFragment() { } private fun applyIpRule(status: IpRulesManager.IpRuleStatus) { - Log.i(Logger.LOG_TAG_FIREWALL, "ip rule for uid: $uid, ip: $ipAddress (${status.name})") + Logger.i(LOG_TAG_FIREWALL, "ip rule for uid: $uid, ip: $ipAddress (${status.name})") ipRule = status val ipPair = IpRulesManager.getIpNetPort(ipAddress) val ip = ipPair.first ?: return diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/BackupRestoreBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/BackupRestoreBottomSheet.kt index 84ea1f679..66a2a0b5d 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/BackupRestoreBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/BackupRestoreBottomSheet.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.bottomsheet +import Logger.LOG_TAG_BACKUP_RESTORE import android.app.Activity import android.content.Context import android.content.Intent @@ -23,7 +24,6 @@ import android.content.pm.PackageManager import android.content.res.Configuration import android.net.Uri import android.os.Bundle -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -52,7 +52,6 @@ import com.celzero.bravedns.backup.BackupHelper.Companion.INTENT_TYPE_XZIP import com.celzero.bravedns.backup.RestoreAgent import com.celzero.bravedns.databinding.ActivityBackupRestoreBinding import com.celzero.bravedns.service.PersistentState -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_BACKUP_RESTORE import com.celzero.bravedns.util.Themes import com.celzero.bravedns.util.Utilities import com.celzero.bravedns.util.Utilities.delay @@ -156,7 +155,7 @@ class BackupRestoreBottomSheet : BottomSheetDialogFragment() { workInfoList -> val workInfo = workInfoList?.getOrNull(0) ?: return@observe - Log.i( + Logger.i( LOG_TAG_BACKUP_RESTORE, "WorkManager state: ${workInfo.state} for ${BackupAgent.TAG}" ) @@ -183,7 +182,7 @@ class BackupRestoreBottomSheet : BottomSheetDialogFragment() { workManager.getWorkInfosByTagLiveData(RestoreAgent.TAG).observe(viewLifecycleOwner) { workInfoList -> val workInfo = workInfoList?.getOrNull(0) ?: return@observe - Log.i( + Logger.i( LOG_TAG_BACKUP_RESTORE, "WorkManager state: ${workInfo.state} for ${RestoreAgent.TAG}" ) @@ -222,7 +221,7 @@ class BackupRestoreBottomSheet : BottomSheetDialogFragment() { // result data contains the uri from the file picker var fileUri: Uri? = null result.data?.also { uri -> fileUri = uri.data } - Log.i( + Logger.i( LOG_TAG_BACKUP_RESTORE, "activity result for restore process with uri: $fileUri" ) @@ -245,7 +244,7 @@ class BackupRestoreBottomSheet : BottomSheetDialogFragment() { // get URI of file created by picker var backupFileUri: Uri? = null result.data?.also { uri -> backupFileUri = uri.data } - Log.i( + Logger.i( LOG_TAG_BACKUP_RESTORE, "activity result for backup process with uri: $backupFileUri" ) @@ -263,7 +262,7 @@ class BackupRestoreBottomSheet : BottomSheetDialogFragment() { private fun startRestoreProcess(fileUri: Uri?) { if (fileUri == null) { - Log.w( + Logger.w( LOG_TAG_BACKUP_RESTORE, "uri received from activity result is null, cancel restore process" ) @@ -271,7 +270,7 @@ class BackupRestoreBottomSheet : BottomSheetDialogFragment() { return } - Log.i(LOG_TAG_BACKUP_RESTORE, "invoke worker to initiate the restore process") + Logger.i(LOG_TAG_BACKUP_RESTORE, "invoke worker to initiate the restore process") val data = Data.Builder() data.putString(DATA_BUILDER_RESTORE_URI, fileUri.toString()) @@ -290,7 +289,7 @@ class BackupRestoreBottomSheet : BottomSheetDialogFragment() { private fun startBackupProcess(backupUri: Uri?) { if (backupUri == null) { - Log.w( + Logger.w( LOG_TAG_BACKUP_RESTORE, "uri received from activity result is null, cancel backup process" ) @@ -301,7 +300,7 @@ class BackupRestoreBottomSheet : BottomSheetDialogFragment() { // stop vpn before beginning the backup process BackupHelper.stopVpn(requireContext()) - Log.i(LOG_TAG_BACKUP_RESTORE, "invoke worker to initiate the backup process") + Logger.i(LOG_TAG_BACKUP_RESTORE, "invoke worker to initiate the backup process") val data = Data.Builder() data.putString(DATA_BUILDER_BACKUP_URI, backupUri.toString()) diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/ConnTrackerBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/ConnTrackerBottomSheet.kt index 3a0ec59d2..3f32a197a 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/ConnTrackerBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/ConnTrackerBottomSheet.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.bottomsheet +import Logger.LOG_TAG_FIREWALL import android.content.Intent import android.content.res.ColorStateList import android.content.res.Configuration @@ -24,7 +25,6 @@ import android.os.Bundle import android.text.Spanned import android.text.TextUtils import android.text.format.DateUtils -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -35,7 +35,6 @@ import androidx.appcompat.widget.AppCompatImageView import androidx.core.content.ContextCompat import androidx.lifecycle.lifecycleScope import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.adapter.FirewallStatusSpinnerAdapter import com.celzero.bravedns.data.ConnectionRules import com.celzero.bravedns.database.ConnectionTracker @@ -50,7 +49,6 @@ import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.service.VpnController import com.celzero.bravedns.ui.activity.AppInfoActivity import com.celzero.bravedns.util.Constants -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_FIREWALL import com.celzero.bravedns.util.Protocol import com.celzero.bravedns.util.Themes import com.celzero.bravedns.util.UIUtils @@ -118,7 +116,7 @@ class ConnTrackerBottomSheet : BottomSheetDialogFragment(), KoinComponent { private fun initView() { if (info == null) { - Log.w(LOG_TAG_FIREWALL, "ip-details missing: initView called before onViewCreated?") + Logger.w(LOG_TAG_FIREWALL, "ip-details missing: initView called before onViewCreated?") this.dismiss() return } @@ -163,7 +161,7 @@ class ConnTrackerBottomSheet : BottomSheetDialogFragment(), KoinComponent { override fun onResume() { super.onResume() if (info == null) { - Log.w(LOG_TAG_FIREWALL, "ip-details missing: initView called before onViewCreated?") + Logger.w(LOG_TAG_FIREWALL, "ip-details missing: initView called before onViewCreated?") this.dismiss() return } @@ -197,7 +195,7 @@ class ConnTrackerBottomSheet : BottomSheetDialogFragment(), KoinComponent { private fun updateConnDetailsChip() { if (info == null) { - Log.w(LOG_TAG_FIREWALL, "ip-details missing: not updating the chip details") + Logger.w(LOG_TAG_FIREWALL, "ip-details missing: not updating the chip details") return } @@ -387,11 +385,10 @@ class ConnTrackerBottomSheet : BottomSheetDialogFragment(), KoinComponent { private fun setupClickListeners() { b.bsConnUnknownAppCheck.setOnCheckedChangeListener(null) b.bsConnUnknownAppCheck.setOnClickListener { - if (DEBUG) - Log.d( - LOG_TAG_FIREWALL, - "Unknown app, universal firewall settings(block unknown app): ${b.bsConnUnknownAppCheck.isChecked} " - ) + Logger.d( + LOG_TAG_FIREWALL, + "Unknown app, universal firewall settings(block unknown app): ${b.bsConnUnknownAppCheck.isChecked} " + ) persistentState.setBlockUnknownConnections(b.bsConnUnknownAppCheck.isChecked) } @@ -441,7 +438,7 @@ class ConnTrackerBottomSheet : BottomSheetDialogFragment(), KoinComponent { if (a == fStatus && c == connStatus) return@io - Log.i( + Logger.i( LOG_TAG_FIREWALL, "Change in firewall rule for app uid: ${info?.uid}, firewall status: $fStatus, conn status: $connStatus" ) @@ -489,7 +486,7 @@ class ConnTrackerBottomSheet : BottomSheetDialogFragment(), KoinComponent { id: Long ) { if (info!!.dnsQuery == null) { - Log.w(LOG_TAG_FIREWALL, "DNS query is null, cannot apply domain rule") + Logger.w(LOG_TAG_FIREWALL, "DNS query is null, cannot apply domain rule") return } @@ -676,7 +673,10 @@ class ConnTrackerBottomSheet : BottomSheetDialogFragment(), KoinComponent { val proto = Protocol.getProtocolName(info!!.protocol).name val cr = ConnectionRules(info!!.ipAddress, info!!.port, proto) - Log.i(LOG_TAG_FIREWALL, "Apply ip rule for ${cr.ipAddress}, ${FirewallRuleset.RULE2.name}") + Logger.i( + LOG_TAG_FIREWALL, + "Apply ip rule for ${cr.ipAddress}, ${FirewallRuleset.RULE2.name}" + ) io { // no need to apply rule, prev selection and current selection are same if ( @@ -692,7 +692,7 @@ class ConnTrackerBottomSheet : BottomSheetDialogFragment(), KoinComponent { } private fun applyDomainRule(domainRuleStatus: DomainRulesManager.Status) { - Log.i( + Logger.i( LOG_TAG_FIREWALL, "Apply domain rule for ${info!!.dnsQuery}, ${domainRuleStatus.name}" ) diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/DnsBlocklistBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/DnsBlocklistBottomSheet.kt index 55135282f..fc2ad5e88 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/DnsBlocklistBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/DnsBlocklistBottomSheet.kt @@ -15,6 +15,7 @@ limitations under the License. */ package com.celzero.bravedns.ui.bottomsheet +import Logger.LOG_TAG_DNS import android.content.res.ColorStateList import android.content.res.Configuration import android.graphics.drawable.Drawable @@ -22,7 +23,6 @@ import android.os.Bundle import android.text.Spanned import android.text.TextUtils import android.text.format.DateUtils -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -39,7 +39,6 @@ import com.bumptech.glide.request.target.CustomViewTarget import com.bumptech.glide.request.transition.DrawableCrossFadeFactory import com.bumptech.glide.request.transition.Transition import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.adapter.FirewallStatusSpinnerAdapter import com.celzero.bravedns.database.DnsLog import com.celzero.bravedns.databinding.BottomSheetDnsLogBinding @@ -49,7 +48,6 @@ import com.celzero.bravedns.glide.FavIconDownloader import com.celzero.bravedns.service.DomainRulesManager import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.util.Constants -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_DNS_LOG import com.celzero.bravedns.util.ResourceRecordTypes import com.celzero.bravedns.util.Themes import com.celzero.bravedns.util.UIUtils.fetchColor @@ -118,7 +116,7 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { log = Gson().fromJson(data, DnsLog::class.java) if (log == null) { - Log.w(LOG_TAG_DNS_LOG, "Transaction detail missing, dismiss the dialog") + Logger.w(LOG_TAG_DNS, "Transaction detail missing, dismiss the dialog") this.dismiss() return } @@ -150,7 +148,7 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { private fun displayRecordTypeChip() { if (log == null) { - Log.w(LOG_TAG_DNS_LOG, "Transaction detail missing, no need to update chips") + Logger.w(LOG_TAG_DNS, "Transaction detail missing, no need to update chips") return } @@ -199,7 +197,7 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { private fun applyDnsRule(status: DomainRulesManager.Status) { if (log == null) { - Log.w(LOG_TAG_DNS_LOG, "Transaction detail missing, no need to apply dns rules") + Logger.w(LOG_TAG_DNS, "Transaction detail missing, no need to apply dns rules") return } io { @@ -215,7 +213,7 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { private fun displayDnsTransactionDetails() { if (log == null) { - Log.w(LOG_TAG_DNS_LOG, "Transaction detail missing, no need to update ui") + Logger.w(LOG_TAG_DNS, "Transaction detail missing, no need to update ui") return } @@ -259,7 +257,7 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { private fun handleBlocklistChip() { if (log == null) { - Log.w(LOG_TAG_DNS_LOG, "Transaction detail missing, no need to update chips") + Logger.w(LOG_TAG_DNS, "Transaction detail missing, no need to update chips") return } @@ -292,7 +290,7 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { private fun determineMaybeBlocked(): Boolean { if (log == null) { - Log.w(LOG_TAG_DNS_LOG, "Transaction detail missing, no need to update chips") + Logger.w(LOG_TAG_DNS, "Transaction detail missing, no need to update chips") return false } @@ -362,7 +360,7 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { private fun showIpsDialog() { if (log == null) { - Log.w(LOG_TAG_DNS_LOG, "Transaction detail missing, not showing dialog") + Logger.w(LOG_TAG_DNS, "Transaction detail missing, not showing dialog") return } @@ -422,7 +420,7 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { private fun displayDescription() { if (log == null) { - Log.w(LOG_TAG_DNS_LOG, "Transaction detail missing, no need to update ui") + Logger.w(LOG_TAG_DNS, "Transaction detail missing, no need to update ui") return } @@ -443,7 +441,7 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { private fun showResolvedState(uptime: String, latency: Long, isGrounded: Boolean) { if (log == null) { - Log.w(LOG_TAG_DNS_LOG, "Transaction detail missing, no need to update ui") + Logger.w(LOG_TAG_DNS, "Transaction detail missing, no need to update ui") return } @@ -467,7 +465,7 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { private fun showBlockedState(uptime: String) { if (log == null) { - Log.w(LOG_TAG_DNS_LOG, "Transaction detail missing, no need to update ui") + Logger.w(LOG_TAG_DNS, "Transaction detail missing, no need to update ui") return } @@ -481,7 +479,7 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { private fun displayFavIcon() { if (log == null) { - Log.w(LOG_TAG_DNS_LOG, "Transaction detail missing, no need to update ui") + Logger.w(LOG_TAG_DNS, "Transaction detail missing, no need to update ui") return } @@ -509,8 +507,7 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { val duckduckgoUrl = FavIconDownloader.constructFavUrlDuckDuckGo(query) val duckduckgoDomainURL = FavIconDownloader.getDomainUrlFromFdqnDuckduckgo(query) try { - if (DEBUG) - Log.d(LOG_TAG_DNS_LOG, "Glide, TransactionViewHolder lookupForImageNextDns :$url") + Logger.d(LOG_TAG_DNS, "Glide, TransactionViewHolder lookupForImageNextDns :$url") val factory = DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(true).build() Glide.with(requireContext().applicationContext) .load(url) @@ -530,11 +527,10 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { resource: Drawable, transition: Transition? ) { - if (DEBUG) - Log.d( - LOG_TAG_DNS_LOG, - "Glide - CustomViewTarget onResourceReady() nextdns: $url" - ) + Logger.d( + LOG_TAG_DNS, + "Glide - CustomViewTarget onResourceReady() nextdns: $url" + ) if (!isAdded) return b.dnsBlockFavIcon.visibility = View.VISIBLE @@ -549,17 +545,15 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { } ) } catch (e: Exception) { - if (DEBUG) - Log.d(LOG_TAG_DNS_LOG, "Glide - TransactionViewHolder Exception() -${e.message}") + Logger.d(LOG_TAG_DNS, "Glide - TransactionViewHolder Exception() -${e.message}") lookupForImageDuckduckgo(duckduckgoUrl, duckduckgoDomainURL) } } private fun lookupForImageDuckduckgo(url: String, domainUrl: String) { try { - if (DEBUG) - Log.d( - LOG_TAG_DNS_LOG, + Logger.d( + LOG_TAG_DNS, "Glide - TransactionViewHolder lookupForImageDuckduckgo: $url, $domainUrl" ) val factory = DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(true).build() @@ -585,9 +579,8 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { resource: Drawable, transition: Transition? ) { - if (DEBUG) - Log.d( - LOG_TAG_DNS_LOG, + Logger.d( + LOG_TAG_DNS, "Glide - CustomViewTarget onResourceReady() -$url" ) if (!isAdded) return @@ -604,8 +597,7 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { } ) } catch (e: Exception) { - if (DEBUG) - Log.d(LOG_TAG_DNS_LOG, "Glide - TransactionViewHolder Exception() -${e.message}") + Logger.d(LOG_TAG_DNS, "Glide - TransactionViewHolder Exception() -${e.message}") if (!isAdded) return b.dnsBlockFavIcon.visibility = View.GONE diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/HomeScreenSettingBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/HomeScreenSettingBottomSheet.kt index 40b4109fb..e77499e80 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/HomeScreenSettingBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/HomeScreenSettingBottomSheet.kt @@ -15,23 +15,21 @@ */ package com.celzero.bravedns.ui.bottomsheet +import Logger.LOG_TAG_VPN import android.content.res.Configuration import android.os.Bundle import android.text.format.DateUtils -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CompoundButton import androidx.lifecycle.lifecycleScope import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.data.AppConfig import com.celzero.bravedns.databinding.BottomSheetHomeScreenBinding import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.service.VpnController import com.celzero.bravedns.util.Constants.Companion.INIT_TIME_MS -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_VPN import com.celzero.bravedns.util.Themes.Companion.getBottomsheetCurrentTheme import com.celzero.bravedns.util.UIUtils.openVpnProfile import com.google.android.material.bottomsheet.BottomSheetDialogFragment @@ -82,7 +80,7 @@ class HomeScreenSettingBottomSheet : BottomSheetDialogFragment() { private fun initView() { b.bsHomeScreenConnectedStatus.text = getConnectionStatus() val selectedIndex = appConfig.getBraveMode().mode - if (DEBUG) Log.d(LOG_TAG_VPN, "Home screen bottom sheet selectedIndex: $selectedIndex") + Logger.d(LOG_TAG_VPN, "Home screen bottom sheet selectedIndex: $selectedIndex") updateStatus(selectedIndex) } diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/LocalBlocklistsBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/LocalBlocklistsBottomSheet.kt index ab3c6a720..06091fa56 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/LocalBlocklistsBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/LocalBlocklistsBottomSheet.kt @@ -15,12 +15,12 @@ */ package com.celzero.bravedns.ui.bottomsheet +import Logger.LOG_TAG_DNS import android.content.DialogInterface import android.content.Intent import android.content.res.Configuration import android.net.Uri import android.os.Bundle -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -44,7 +44,6 @@ import com.celzero.bravedns.ui.fragment.DnsSettingsFragment import com.celzero.bravedns.util.Constants import com.celzero.bravedns.util.Constants.Companion.INIT_TIME_MS import com.celzero.bravedns.util.Constants.Companion.RETHINK_SEARCH_URL -import com.celzero.bravedns.util.Logger import com.celzero.bravedns.util.Themes.Companion.getBottomsheetCurrentTheme import com.celzero.bravedns.util.UIUtils.clipboardCopy import com.celzero.bravedns.util.UIUtils.fetchToggleBtnColors @@ -147,7 +146,7 @@ class LocalBlocklistsBottomSheet : BottomSheetDialogFragment() { private fun initializeObservers() { appDownloadManager.downloadRequired.observe(viewLifecycleOwner) { - Log.i(Logger.LOG_TAG_DNS, "Check for blocklist update, status: $it") + Logger.i(LOG_TAG_DNS, "Check for blocklist update, status: $it") if (it == null) return@observe handleDownloadStatus(it) @@ -495,7 +494,7 @@ class LocalBlocklistsBottomSheet : BottomSheetDialogFragment() { viewLifecycleOwner ) { workInfoList -> val workInfo = workInfoList?.getOrNull(0) ?: return@observe - Log.i( + Logger.i( Logger.LOG_TAG_DOWNLOAD, "WorkManager state: ${workInfo.state} for ${LocalBlocklistCoordinator.CUSTOM_DOWNLOAD}" ) @@ -524,7 +523,7 @@ class LocalBlocklistsBottomSheet : BottomSheetDialogFragment() { viewLifecycleOwner ) { workInfoList -> val workInfo = workInfoList?.getOrNull(0) ?: return@observe - Log.i( + Logger.i( Logger.LOG_TAG_DOWNLOAD, "WorkManager state: ${workInfo.state} for ${DownloadConstants.DOWNLOAD_TAG}" ) @@ -552,7 +551,7 @@ class LocalBlocklistsBottomSheet : BottomSheetDialogFragment() { if (workInfoList != null && workInfoList.isNotEmpty()) { val workInfo = workInfoList[0] if (workInfo != null && workInfo.state == WorkInfo.State.SUCCEEDED) { - Log.i( + Logger.i( Logger.LOG_TAG_DOWNLOAD, "AppDownloadManager Work Manager completed - ${DownloadConstants.FILE_TAG}" ) @@ -566,12 +565,12 @@ class LocalBlocklistsBottomSheet : BottomSheetDialogFragment() { onDownloadFail() workManager.pruneWork() workManager.cancelAllWorkByTag(DownloadConstants.FILE_TAG) - Log.i( + Logger.i( Logger.LOG_TAG_DOWNLOAD, "AppDownloadManager Work Manager failed - ${DownloadConstants.FILE_TAG}" ) } else { - Log.i( + Logger.i( Logger.LOG_TAG_DOWNLOAD, "AppDownloadManager Work Manager - ${DownloadConstants.FILE_TAG}, ${workInfo.state}" ) diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/RethinkLogBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/RethinkLogBottomSheet.kt index 8a9a78680..0f01e1a31 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/RethinkLogBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/RethinkLogBottomSheet.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.bottomsheet +import Logger.LOG_TAG_FIREWALL import android.content.Intent import android.content.res.ColorStateList import android.content.res.Configuration @@ -22,7 +23,6 @@ import android.graphics.PorterDuff import android.graphics.PorterDuffColorFilter import android.os.Bundle import android.text.format.DateUtils -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -39,7 +39,6 @@ import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.service.VpnController import com.celzero.bravedns.ui.activity.AppInfoActivity import com.celzero.bravedns.util.Constants -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_FIREWALL import com.celzero.bravedns.util.Protocol import com.celzero.bravedns.util.Themes import com.celzero.bravedns.util.UIUtils @@ -105,7 +104,7 @@ class RethinkLogBottomSheet : BottomSheetDialogFragment(), KoinComponent { private fun initView() { if (info == null) { - Log.w(LOG_TAG_FIREWALL, "ip-details missing: initView called before onViewCreated?") + Logger.w(LOG_TAG_FIREWALL, "ip-details missing: initView called before onViewCreated?") this.dismiss() return } @@ -148,7 +147,7 @@ class RethinkLogBottomSheet : BottomSheetDialogFragment(), KoinComponent { override fun onResume() { super.onResume() if (info == null) { - Log.w(LOG_TAG_FIREWALL, "ip-details missing: initView called before onViewCreated?") + Logger.w(LOG_TAG_FIREWALL, "ip-details missing: initView called before onViewCreated?") this.dismiss() return } @@ -190,7 +189,7 @@ class RethinkLogBottomSheet : BottomSheetDialogFragment(), KoinComponent { private fun updateConnDetailsChip() { if (info == null) { - Log.w(LOG_TAG_FIREWALL, "ip-details missing: not updating the chip details") + Logger.w(LOG_TAG_FIREWALL, "ip-details missing: not updating the chip details") return } diff --git a/app/src/full/java/com/celzero/bravedns/ui/dialog/WgAddPeerDialog.kt b/app/src/full/java/com/celzero/bravedns/ui/dialog/WgAddPeerDialog.kt index 8e0870a89..28192acaa 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/dialog/WgAddPeerDialog.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/dialog/WgAddPeerDialog.kt @@ -18,7 +18,6 @@ package com.celzero.bravedns.ui.dialog import android.app.Activity import android.app.Dialog import android.os.Bundle -import android.util.Log import android.view.Window import android.view.WindowManager import android.widget.Toast @@ -26,7 +25,6 @@ import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.lifecycleScope import com.celzero.bravedns.databinding.DialogWgAddPeerBinding import com.celzero.bravedns.service.WireguardManager -import com.celzero.bravedns.util.Logger import com.celzero.bravedns.util.Utilities import com.celzero.bravedns.wireguard.Peer import com.celzero.bravedns.wireguard.util.ErrorMessages @@ -108,7 +106,8 @@ class WgAddPeerDialog( this.dismiss() } } catch (e: Throwable) { - Log.e(Logger.LOG_TAG_PROXY, "Error while adding peer", e) + val ex = Logger.throwableToException(e) + Logger.e(Logger.LOG_TAG_PROXY, "Error while adding peer", ex) Utilities.showToastUiCentered( context, ErrorMessages[context, e], diff --git a/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt b/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt index 75a61a29e..93eb883c2 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt @@ -15,12 +15,12 @@ */ package com.celzero.bravedns.ui.dialog +import Logger.LOG_TAG_PROXY import android.app.Activity import android.app.Dialog import android.graphics.PorterDuff import android.graphics.PorterDuffColorFilter import android.os.Bundle -import android.util.Log import android.view.Window import android.view.WindowManager import android.view.animation.Animation @@ -37,7 +37,6 @@ import com.celzero.bravedns.R import com.celzero.bravedns.database.RefreshDatabase import com.celzero.bravedns.databinding.WgAppsIncludeDialogBinding import com.celzero.bravedns.service.ProxyManager -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_PROXY import com.celzero.bravedns.util.Utilities import com.celzero.bravedns.viewmodel.ProxyAppsMappingViewModel import com.google.android.material.chip.Chip @@ -259,10 +258,10 @@ class WgIncludeAppsDialog( // add all if the list is empty or remove all if the list is full io { if (toAdd) { - Log.i(LOG_TAG_PROXY, "Adding all apps to proxy $proxyId, $proxyName") + Logger.i(LOG_TAG_PROXY, "Adding all apps to proxy $proxyId, $proxyName") ProxyManager.setProxyIdForAllApps(proxyId, proxyName) } else { - Log.i(LOG_TAG_PROXY, "Removing all apps from proxy $proxyId, $proxyName") + Logger.i(LOG_TAG_PROXY, "Removing all apps from proxy $proxyId, $proxyName") ProxyManager.setNoProxyForAllApps() } } @@ -282,7 +281,7 @@ class WgIncludeAppsDialog( builder.setCancelable(true) builder.setPositiveButton(context.getString(R.string.lbl_include)) { _, _ -> io { - Log.i(LOG_TAG_PROXY, "Adding remaining apps to proxy $proxyId, $proxyName") + Logger.i(LOG_TAG_PROXY, "Adding remaining apps to proxy $proxyId, $proxyName") ProxyManager.setProxyIdForUnselectedApps(proxyId, proxyName) } } diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/AboutFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/AboutFragment.kt index 8d8071e5f..856a2f883 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/AboutFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/AboutFragment.kt @@ -15,6 +15,7 @@ limitations under the License. */ package com.celzero.bravedns.ui.fragment +import Logger.LOG_TAG_UI import android.content.ActivityNotFoundException import android.content.DialogInterface import android.content.Intent @@ -26,7 +27,6 @@ import android.os.SystemClock import android.provider.Settings import android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS import android.text.method.LinkMovementMethod -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.WindowManager @@ -52,8 +52,6 @@ import com.celzero.bravedns.service.AppUpdater import com.celzero.bravedns.ui.HomeScreenActivity import com.celzero.bravedns.util.Constants.Companion.INIT_TIME_MS import com.celzero.bravedns.util.Constants.Companion.RETHINKDNS_SPONSOR_LINK -import com.celzero.bravedns.util.Logger -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_UI import com.celzero.bravedns.util.UIUtils.openVpnProfile import com.celzero.bravedns.util.UIUtils.sendEmailIntent import com.celzero.bravedns.util.UIUtils.updateHtmlEncodedText @@ -124,7 +122,7 @@ class AboutFragment : Fragment(R.layout.fragment_about), View.OnClickListener, K b.aboutAppVersion.text = getString(R.string.about_version_install_source, version, getDownloadSource()) } catch (e: PackageManager.NameNotFoundException) { - Log.w(LOG_TAG_UI, "package name not found: ${e.message}", e) + Logger.w(LOG_TAG_UI, "package name not found: ${e.message}", e) } } @@ -238,7 +236,7 @@ class AboutFragment : Fragment(R.layout.fragment_about), View.OnClickListener, K getString(R.string.intent_launch_error, intent.data), Toast.LENGTH_SHORT ) - Log.w(LOG_TAG_UI, "activity not found ${e.message}", e) + Logger.w(LOG_TAG_UI, "activity not found ${e.message}", e) } } @@ -255,7 +253,7 @@ class AboutFragment : Fragment(R.layout.fragment_about), View.OnClickListener, K getString(R.string.app_info_error), Toast.LENGTH_SHORT ) - Log.w(LOG_TAG_UI, "activity not found ${e.message}", e) + Logger.w(LOG_TAG_UI, "activity not found ${e.message}", e) } } @@ -278,7 +276,7 @@ class AboutFragment : Fragment(R.layout.fragment_about), View.OnClickListener, K getString(R.string.notification_screen_error), Toast.LENGTH_SHORT ) - Log.w(LOG_TAG_UI, "activity not found ${e.message}", e) + Logger.w(LOG_TAG_UI, "activity not found ${e.message}", e) } } @@ -423,7 +421,7 @@ class AboutFragment : Fragment(R.layout.fragment_about), View.OnClickListener, K binding.logs.text = inputString?.slice(0 until maxLength) } } catch (e: Exception) { - Log.w(LOG_TAG_UI, "Error loading log files to textview: ${e.message}", e) + Logger.w(LOG_TAG_UI, "err loading log files to textview: ${e.message}", e) uiCtx { if (!isAdded) return@uiCtx binding.info.visibility = View.GONE @@ -468,7 +466,7 @@ class AboutFragment : Fragment(R.layout.fragment_about), View.OnClickListener, K viewLifecycleOwner ) { workInfoList -> val workInfo = workInfoList?.getOrNull(0) ?: return@observe - Log.i( + Logger.i( Logger.LOG_TAG_SCHEDULER, "WorkManager state: ${workInfo.state} for ${WorkScheduler.APP_EXIT_INFO_ONE_TIME_JOB_TAG}" ) diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt index 19a78e77f..c82fc6e71 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt @@ -16,7 +16,6 @@ package com.celzero.bravedns.ui.fragment import android.os.Bundle -import android.util.Log import android.view.View import android.view.WindowManager import android.widget.ArrayAdapter @@ -27,14 +26,12 @@ import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import by.kirich1409.viewbindingdelegate.viewBinding import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.adapter.DnsProxyEndpointAdapter import com.celzero.bravedns.data.AppConfig import com.celzero.bravedns.database.DnsProxyEndpoint import com.celzero.bravedns.databinding.DialogSetDnsProxyBinding import com.celzero.bravedns.databinding.FragmentDnsProxyListBinding import com.celzero.bravedns.service.FirewallManager -import com.celzero.bravedns.util.Logger import com.celzero.bravedns.util.Utilities import com.celzero.bravedns.viewmodel.DnsProxyEndpointViewModel import com.google.android.material.dialog.MaterialAlertDialogBuilder @@ -88,9 +85,7 @@ class DnsProxyListFragment : Fragment(R.layout.fragment_dns_proxy_list) { // fetch the count from repository and increment by 1 to show the // next doh name in the dialog val nextIndex = appConfig.getDnsProxyCount().plus(1) - uiCtx { - showAddDnsProxyDialog(appNames, nextIndex) - } + uiCtx { showAddDnsProxyDialog(appNames, nextIndex) } } } } @@ -155,17 +150,17 @@ class DnsProxyListFragment : Fragment(R.layout.fragment_dns_proxy_list) { errorTxt.text = getString(R.string.cd_dns_proxy_error_text_2) } } catch (e: NumberFormatException) { - Log.w(Logger.LOG_TAG_UI, "Error: ${e.message}", e) + Logger.w(Logger.LOG_TAG_UI, "Error: ${e.message}", e) errorTxt.text = getString(R.string.cd_dns_proxy_error_text_3) isPortValid = false } if (isPortValid && isIpValid) { - if (DEBUG) Log.d(Logger.LOG_TAG_UI, "new value inserted into DNSProxy") + Logger.d(Logger.LOG_TAG_UI, "new value inserted into DNSProxy") io { insertDNSProxyEndpointDB(mode, name, appName, ip, port) } dialog.dismiss() } else { - Log.i(Logger.LOG_TAG_UI, "cannot insert invalid dns-proxy IPs: $name, $appName") + Logger.i(Logger.LOG_TAG_UI, "cannot insert invalid dns-proxy IPs: $name, $appName") } } @@ -210,8 +205,7 @@ class DnsProxyListFragment : Fragment(R.layout.fragment_dns_proxy_list) { latency = 0 ) appConfig.insertDnsproxyEndpoint(dnsProxyEndpoint) - if (DEBUG) - Log.d(Logger.LOG_TAG_UI, "Insert into DNSProxy database: $packageName, $port") + Logger.d(Logger.LOG_TAG_UI, "Insert into DNSProxy database: $packageName, $port") } } diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsSettingsFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsSettingsFragment.kt index cf9059c47..a6cbc6ca4 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsSettingsFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsSettingsFragment.kt @@ -17,7 +17,6 @@ package com.celzero.bravedns.ui.fragment import android.content.Intent import android.os.Bundle -import android.util.Log import android.view.View import android.view.animation.Animation import android.view.animation.RotateAnimation @@ -40,7 +39,6 @@ import com.celzero.bravedns.ui.activity.ConfigureRethinkBasicActivity import com.celzero.bravedns.ui.activity.DnsListActivity import com.celzero.bravedns.ui.activity.PauseActivity import com.celzero.bravedns.ui.bottomsheet.LocalBlocklistsBottomSheet -import com.celzero.bravedns.util.Logger import com.celzero.bravedns.util.UIUtils.fetchColor import com.celzero.bravedns.util.Utilities import com.celzero.bravedns.util.Utilities.isPlayStoreFlavour @@ -293,7 +291,7 @@ class DnsSettingsFragment : if (enabled) { get().scheduleBlocklistUpdateCheckJob() } else { - Log.i( + Logger.i( Logger.LOG_TAG_SCHEDULER, "Cancel all the work related to blocklist update check" ) diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt index 20c34789d..1f942e088 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt @@ -15,6 +15,8 @@ */ package com.celzero.bravedns.ui.fragment +import Logger.LOG_TAG_UI +import Logger.LOG_TAG_VPN import android.Manifest import android.app.Activity import android.content.ActivityNotFoundException @@ -33,7 +35,6 @@ import android.os.PowerManager import android.os.SystemClock import android.provider.Settings import android.text.format.DateUtils -import android.util.Log import android.util.TypedValue import android.view.View import android.widget.Toast @@ -47,7 +48,6 @@ import androidx.lifecycle.lifecycleScope import backend.Backend import by.kirich1409.viewbindingdelegate.viewBinding import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.data.AppConfig import com.celzero.bravedns.database.AppInfo import com.celzero.bravedns.databinding.FragmentHomeScreenBinding @@ -67,8 +67,6 @@ import com.celzero.bravedns.ui.activity.WgMainActivity import com.celzero.bravedns.ui.bottomsheet.HomeScreenSettingBottomSheet import com.celzero.bravedns.util.* import com.celzero.bravedns.util.Constants.Companion.RETHINKDNS_SPONSOR_LINK -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_UI -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_VPN import com.celzero.bravedns.util.UIUtils.openNetworkSettings import com.celzero.bravedns.util.UIUtils.openVpnProfile import com.celzero.bravedns.util.UIUtils.updateHtmlEncodedText @@ -702,7 +700,7 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { b.fhsCardApps.visibility = View.GONE b.fhsCardAllowedApps.isSelected = true } catch (e: Exception) { // NoSuchElementException, ConcurrentModification - Log.e(LOG_TAG_VPN, "error retrieving value from appInfos observer ${e.message}", e) + Logger.e(LOG_TAG_VPN, "error retrieving value from appInfos observer ${e.message}", e) } } } @@ -742,8 +740,7 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { private fun batteryOptimizationActive(context: Context): Boolean { val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager - if (DEBUG) - Log.d( + Logger.d( LOG_TAG_UI, "ignore battery optimization: ${powerManager.isIgnoringBatteryOptimizations(context.packageName)}" ) @@ -775,8 +772,7 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager - if (DEBUG) - Log.d( + Logger.d( LOG_TAG_UI, "restrict background status: ${connectivityManager.restrictBackgroundStatus}" ) @@ -948,7 +944,7 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { */ private fun maybeAutoStartVpn() { if (isVpnActivated && !VpnController.isOn()) { - Log.i(LOG_TAG_VPN, "start VPN (previous state)") + Logger.i(LOG_TAG_VPN, "start VPN (previous state)") prepareAndStartVpn() } } @@ -1019,8 +1015,7 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { } private fun startAppsActivity() { - if (DEBUG) - Log.d(LOG_TAG_VPN, "Status : $isVpnActivated , BraveMode: ${appConfig.getBraveMode()}") + Logger.d(LOG_TAG_VPN, "Status : $isVpnActivated , BraveMode: ${appConfig.getBraveMode()}") // no need to check for app modes to open this activity // one use case: https://github.com/celzero/rethink-app/issues/611 @@ -1107,7 +1102,7 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { if (!persistentState.shouldRequestNotificationPermission) { // user rejected notification permission - Log.w(LOG_TAG_VPN, "User rejected notification permission for the app") + Logger.w(LOG_TAG_VPN, "User rejected notification permission for the app") return } @@ -1128,7 +1123,7 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { // This exception is not mentioned in the documentation, but it has been encountered // users and also by other developers, e.g. // https://stackoverflow.com/questions/45470113. - Log.e(LOG_TAG_VPN, "Device does not support system-wide VPN mode.", e) + Logger.e(LOG_TAG_VPN, "Device does not support system-wide VPN mode.", e) return false } // If the VPN.prepare() is not null, then the first time VPN dialog is shown, Show info @@ -1181,9 +1176,9 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { registerForActivityResult(ActivityResultContracts.RequestPermission()) { persistentState.shouldRequestNotificationPermission = it if (it) { - Log.i(LOG_TAG_UI, "User accepted notification permission") + Logger.i(LOG_TAG_UI, "User accepted notification permission") } else { - Log.w(LOG_TAG_UI, "User rejected notification permission") + Logger.w(LOG_TAG_UI, "User rejected notification permission") Snackbar.make( requireActivity().findViewById(android.R.id.content).rootView, getString(R.string.hsf_notification_permission_failure), diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkBlocklistFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkBlocklistFragment.kt index 98811e10d..9722d26b2 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkBlocklistFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkBlocklistFragment.kt @@ -15,9 +15,9 @@ */ package com.celzero.bravedns.ui.fragment +import Logger.LOG_TAG_UI import android.content.res.ColorStateList import android.os.Bundle -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -58,8 +58,6 @@ import com.celzero.bravedns.util.Constants.Companion.DEFAULT_RDNS_REMOTE_DNS_NAM import com.celzero.bravedns.util.Constants.Companion.MAX_ENDPOINT import com.celzero.bravedns.util.Constants.Companion.RETHINK_STAMP_VERSION import com.celzero.bravedns.util.CustomLinearLayoutManager -import com.celzero.bravedns.util.Logger -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_UI import com.celzero.bravedns.util.UIUtils.fetchToggleBtnColors import com.celzero.bravedns.util.UIUtils.updateHtmlEncodedText import com.celzero.bravedns.util.Utilities.getRemoteBlocklistStamp @@ -437,9 +435,9 @@ class RethinkBlocklistFragment : } private fun setStamp(stamp: String?) { - Log.i(LOG_TAG_UI, "set stamp for blocklist type: ${type.name} with $stamp") + Logger.i(LOG_TAG_UI, "set stamp for blocklist type: ${type.name} with $stamp") if (stamp == null) { - Log.i(LOG_TAG_UI, "stamp is null") + Logger.i(LOG_TAG_UI, "stamp is null") return } @@ -449,7 +447,7 @@ class RethinkBlocklistFragment : persistentState.localBlocklistStamp = stamp persistentState.numberOfLocalBlocklists = blocklistCount persistentState.blocklistEnabled = true - Log.i(LOG_TAG_UI, "set stamp for local blocklist with $stamp, $blocklistCount") + Logger.i(LOG_TAG_UI, "set stamp for local blocklist with $stamp, $blocklistCount") } else { // set stamp for remote blocklist appConfig.updateRethinkEndpoint( @@ -797,7 +795,7 @@ class RethinkBlocklistFragment : workManager.getWorkInfosByTagLiveData(CUSTOM_DOWNLOAD).observe(viewLifecycleOwner) { workInfoList -> val workInfo = workInfoList?.getOrNull(0) ?: return@observe - Log.i( + Logger.i( Logger.LOG_TAG_DOWNLOAD, "WorkManager state: ${workInfo.state} for $CUSTOM_DOWNLOAD" ) @@ -825,7 +823,7 @@ class RethinkBlocklistFragment : workManager.getWorkInfosByTagLiveData(DOWNLOAD_TAG).observe(viewLifecycleOwner) { workInfoList -> val workInfo = workInfoList?.getOrNull(0) ?: return@observe - Log.i(Logger.LOG_TAG_DOWNLOAD, "WorkManager state: ${workInfo.state} for $DOWNLOAD_TAG") + Logger.i(Logger.LOG_TAG_DOWNLOAD, "WorkManager state: ${workInfo.state} for $DOWNLOAD_TAG") if ( WorkInfo.State.ENQUEUED == workInfo.state || WorkInfo.State.RUNNING == workInfo.state @@ -849,7 +847,7 @@ class RethinkBlocklistFragment : if (workInfoList != null && workInfoList.isNotEmpty()) { val workInfo = workInfoList[0] if (workInfo != null && workInfo.state == WorkInfo.State.SUCCEEDED) { - Log.i( + Logger.i( Logger.LOG_TAG_DOWNLOAD, "AppDownloadManager Work Manager completed - $FILE_TAG" ) @@ -863,12 +861,12 @@ class RethinkBlocklistFragment : onDownloadFail() workManager.pruneWork() workManager.cancelAllWorkByTag(FILE_TAG) - Log.i( + Logger.i( Logger.LOG_TAG_DOWNLOAD, "AppDownloadManager Work Manager failed - $FILE_TAG" ) } else { - Log.i( + Logger.i( Logger.LOG_TAG_DOWNLOAD, "AppDownloadManager Work Manager - $FILE_TAG, ${workInfo.state}" ) diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkListFragment.kt index 4010e2d4d..2da210e1f 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkListFragment.kt @@ -17,7 +17,6 @@ package com.celzero.bravedns.ui.fragment import android.content.Intent import android.os.Bundle -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -33,7 +32,6 @@ import androidx.work.WorkInfo import androidx.work.WorkManager import by.kirich1409.viewbindingdelegate.viewBinding import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.adapter.RethinkEndpointAdapter import com.celzero.bravedns.customdownloader.LocalBlocklistCoordinator import com.celzero.bravedns.customdownloader.RemoteBlocklistCoordinator @@ -48,7 +46,6 @@ import com.celzero.bravedns.ui.activity.ConfigureRethinkBasicActivity.Companion. import com.celzero.bravedns.util.Constants import com.celzero.bravedns.util.Constants.Companion.INIT_TIME_MS import com.celzero.bravedns.util.Constants.Companion.MAX_ENDPOINT -import com.celzero.bravedns.util.Logger import com.celzero.bravedns.util.UIUtils.fetchColor import com.celzero.bravedns.util.Utilities import com.celzero.bravedns.viewmodel.RethinkEndpointViewModel @@ -145,11 +142,10 @@ class RethinkListFragment : Fragment(R.layout.fragment_rethink_list) { } private fun isBlocklistUpdateAvailable(): Boolean { - if (DEBUG) - Log.d( - Logger.LOG_TAG_DOWNLOAD, - "Update available? newest: ${persistentState.newestRemoteBlocklistTimestamp}, available: ${persistentState.remoteBlocklistTimestamp}" - ) + Logger.d( + Logger.LOG_TAG_DOWNLOAD, + "Update available? newest: ${persistentState.newestRemoteBlocklistTimestamp}, available: ${persistentState.remoteBlocklistTimestamp}" + ) return (persistentState.newestRemoteBlocklistTimestamp != INIT_TIME_MS && persistentState.newestRemoteBlocklistTimestamp > persistentState.remoteBlocklistTimestamp) @@ -267,7 +263,7 @@ class RethinkListFragment : Fragment(R.layout.fragment_rethink_list) { .getWorkInfosByTagLiveData(RemoteBlocklistCoordinator.REMOTE_DOWNLOAD_WORKER) .observe(viewLifecycleOwner) { workInfoList -> val workInfo = workInfoList?.getOrNull(0) ?: return@observe - Log.i( + Logger.i( Logger.LOG_TAG_DOWNLOAD, "WorkManager state: ${workInfo.state} for ${RemoteBlocklistCoordinator.REMOTE_DOWNLOAD_WORKER}" ) @@ -299,7 +295,7 @@ class RethinkListFragment : Fragment(R.layout.fragment_rethink_list) { } appDownloadManager.downloadRequired.observe(viewLifecycleOwner) { - Log.i(Logger.LOG_TAG_DNS, "Check for blocklist update, status: $it") + Logger.i(Logger.LOG_TAG_DNS, "Check for blocklist update, status: $it") if (it == null) return@observe when (it) { diff --git a/app/src/full/java/com/celzero/bravedns/util/BackgroundAccessibilityService.kt b/app/src/full/java/com/celzero/bravedns/util/BackgroundAccessibilityService.kt index 5f9e44508..dc6ae661f 100644 --- a/app/src/full/java/com/celzero/bravedns/util/BackgroundAccessibilityService.kt +++ b/app/src/full/java/com/celzero/bravedns/util/BackgroundAccessibilityService.kt @@ -15,17 +15,15 @@ */ package com.celzero.bravedns.util +import Logger.LOG_TAG_FIREWALL import android.accessibilityservice.AccessibilityService import android.content.Intent import android.content.pm.PackageManager import android.text.TextUtils -import android.util.Log import android.view.accessibility.AccessibilityEvent -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.service.FirewallManager import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.service.VpnController -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_FIREWALL import com.celzero.bravedns.util.Utilities.isAtleastT import org.koin.android.ext.android.inject import org.koin.core.component.KoinComponent @@ -35,7 +33,7 @@ class BackgroundAccessibilityService : AccessibilityService(), KoinComponent { private val persistentState by inject() override fun onInterrupt() { - Log.w(LOG_TAG_FIREWALL, "BackgroundAccessibilityService Interrupted") + Logger.w(LOG_TAG_FIREWALL, "BackgroundAccessibilityService Interrupted") } override fun onRebind(intent: Intent?) { @@ -126,11 +124,10 @@ class BackgroundAccessibilityService : AccessibilityService(), KoinComponent { } else { event.eventType == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED } - if (DEBUG) - Log.d( - LOG_TAG_FIREWALL, - "onAccessibilityEvent: ${event.packageName}, ${event.eventType}, $hasContentChanged" - ) + Logger.d( + LOG_TAG_FIREWALL, + "onAccessibilityEvent: ${event.packageName}, ${event.eventType}, $hasContentChanged" + ) if (!hasContentChanged) return diff --git a/app/src/full/java/com/celzero/bravedns/util/QrCodeFromFileScanner.kt b/app/src/full/java/com/celzero/bravedns/util/QrCodeFromFileScanner.kt index ff936f0fc..edbc19190 100644 --- a/app/src/full/java/com/celzero/bravedns/util/QrCodeFromFileScanner.kt +++ b/app/src/full/java/com/celzero/bravedns/util/QrCodeFromFileScanner.kt @@ -18,11 +18,11 @@ */ package com.celzero.bravedns.util +import Logger.LOG_QR_CODE import android.content.ContentResolver import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri -import android.util.Log import com.google.zxing.BinaryBitmap import com.google.zxing.DecodeHintType import com.google.zxing.NotFoundException @@ -83,7 +83,7 @@ class QrCodeFromFileScanner( } private fun doScan(data: Uri): Result? { - Log.d(TAG, "Starting to scan an image: $data") + Logger.d(LOG_QR_CODE, "Starting to scan an image: $data") contentResolver.openInputStream(data).use { inputStream -> val originalBitmap = BitmapFactory.decodeStream(inputStream) @@ -91,10 +91,13 @@ class QrCodeFromFileScanner( return try { scanBitmapForResult(originalBitmap).also { - Log.d(TAG, "Found result in original image") + Logger.d(LOG_QR_CODE, "Found result in original image") } } catch (e: Exception) { - Log.e(TAG, "Original image scan finished with error: $e, will try downscaled image") + Logger.e( + LOG_QR_CODE, + "Original image scan finished with error: $e, will try downscaled image" + ) val scaleBitmap = downscaleBitmap(originalBitmap, 500) scanBitmapForResult(originalBitmap).also { scaleBitmap.recycle() } } finally { @@ -112,8 +115,6 @@ class QrCodeFromFileScanner( suspend fun scan(data: Uri) = withContext(Dispatchers.Default) { doScan(data) } companion object { - private const val TAG = "QrCodeFromFileScanner" - /** * Given a reference to a file, check if this file could be parsed by this class * diff --git a/app/src/full/java/com/celzero/bravedns/util/RemoteFileTagUtil.kt b/app/src/full/java/com/celzero/bravedns/util/RemoteFileTagUtil.kt index b99a5a089..c26c8bbcf 100644 --- a/app/src/full/java/com/celzero/bravedns/util/RemoteFileTagUtil.kt +++ b/app/src/full/java/com/celzero/bravedns/util/RemoteFileTagUtil.kt @@ -15,14 +15,14 @@ */ package com.celzero.bravedns.util +import Logger.LOG_TAG_DOWNLOAD import android.content.Context -import android.util.Log import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.service.RethinkBlocklistManager -import org.koin.core.component.KoinComponent import java.io.File import java.io.IOException import java.io.InputStream +import org.koin.core.component.KoinComponent class RemoteFileTagUtil : KoinComponent { companion object { @@ -46,11 +46,7 @@ class RemoteFileTagUtil : KoinComponent { persistentState.remoteBlocklistTimestamp = Constants.PACKAGED_REMOTE_FILETAG_TIMESTAMP } catch (e: IOException) { - Log.e( - Logger.LOG_TAG_DOWNLOAD, - "Issue moving file from asset folder: ${e.message}", - e - ) + Logger.e(LOG_TAG_DOWNLOAD, "err moving file from asset folder: ${e.message}", e) persistentState.remoteBlocklistTimestamp = Constants.INIT_TIME_MS } } diff --git a/app/src/full/java/com/celzero/bravedns/util/TunnelImporter.kt b/app/src/full/java/com/celzero/bravedns/util/TunnelImporter.kt index a8f350891..7cae5bca9 100644 --- a/app/src/full/java/com/celzero/bravedns/util/TunnelImporter.kt +++ b/app/src/full/java/com/celzero/bravedns/util/TunnelImporter.kt @@ -18,13 +18,12 @@ */ package com.celzero.bravedns.util +import Logger.LOG_TAG_PROXY import android.content.ContentResolver import android.content.Context import android.net.Uri import android.provider.OpenableColumns -import android.util.Log import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.service.WireguardManager import com.celzero.bravedns.wireguard.Config import com.celzero.bravedns.wireguard.util.ErrorMessages @@ -135,7 +134,7 @@ object TunnelImporter : KoinComponent { suspend fun importTunnel(configText: String, messageCallback: (CharSequence) -> Unit) { withContext(Dispatchers.IO) { try { - if (DEBUG) Log.d(Logger.LOG_TAG_PROXY, "Importing tunnel: $configText") + Logger.d(LOG_TAG_PROXY, "Importing tunnel: $configText") val config = Config.parse( ByteArrayInputStream(configText.toByteArray(StandardCharsets.UTF_8)) @@ -156,7 +155,8 @@ object TunnelImporter : KoinComponent { for (throwable in throwables) { val error = ErrorMessages[context, throwable] message = context.getString(R.string.import_error, error) - Log.e(Logger.LOG_TAG_PROXY, message, throwable) + val ex = Logger.throwableToException(throwable) + Logger.e(LOG_TAG_PROXY, message, ex) } // trim the message and take string after ":" val idx = message.indexOf(':') diff --git a/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt b/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt index 4c1c999d4..5e3c0b52e 100644 --- a/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt +++ b/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt @@ -27,7 +27,6 @@ import android.provider.Settings import android.text.Html import android.text.Spanned import android.text.format.DateUtils -import android.util.Log import android.util.TypedValue import android.widget.Toast import androidx.core.content.getSystemService @@ -35,7 +34,6 @@ import androidx.core.net.toUri import androidx.core.text.HtmlCompat import backend.Backend import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.database.DnsLog import com.celzero.bravedns.glide.FavIconDownloader import com.celzero.bravedns.net.doh.Transaction @@ -148,7 +146,7 @@ object UIUtils { context.getString(R.string.vpn_profile_error), Toast.LENGTH_SHORT ) - Log.w(Logger.LOG_TAG_VPN, "Failure opening app info: ${e.message}", e) + Logger.w(Logger.LOG_TAG_VPN, "Failure opening app info: ${e.message}", e) } } @@ -162,7 +160,7 @@ object UIUtils { context.getString(R.string.intent_launch_error, url), Toast.LENGTH_SHORT ) - Log.w(Logger.LOG_TAG_UI, "activity not found ${e.message}", e) + Logger.w(Logger.LOG_TAG_UI, "activity not found ${e.message}", e) } } @@ -174,7 +172,7 @@ object UIUtils { } catch (e: ActivityNotFoundException) { val msg = context.getString(R.string.intent_launch_error, settings) Utilities.showToastUiCentered(context, msg, Toast.LENGTH_SHORT) - Log.w(Logger.LOG_TAG_VPN, "Failure opening network setting screen: ${e.message}", e) + Logger.w(Logger.LOG_TAG_VPN, "Failure opening network setting screen: ${e.message}", e) } } @@ -213,7 +211,7 @@ object UIUtils { intent.data = Uri.fromParts("package", packageName, null) context.startActivity(intent) } catch (e: Exception) { // ActivityNotFoundException | NullPointerException - Log.w(Logger.LOG_TAG_FIREWALL, "Failure calling app info: ${e.message}", e) + Logger.w(Logger.LOG_TAG_FIREWALL, "Failure calling app info: ${e.message}", e) Utilities.showToastUiCentered( context, context.getString(R.string.ctbs_app_info_not_available_toast), @@ -267,7 +265,7 @@ object UIUtils { if (isDgaDomain(dnsLog.queryStr)) return - if (DEBUG) Log.d(Logger.LOG_TAG_UI, "Glide - fetchFavIcon():${dnsLog.queryStr}") + Logger.d(Logger.LOG_TAG_UI, "Glide - fetchFavIcon():${dnsLog.queryStr}") // fetch fav icon in background using glide FavIconDownloader(context, dnsLog.queryStr).run() diff --git a/app/src/headless/java/com/celzero/bravedns/provider/ApplicationProvider.kt b/app/src/headless/java/com/celzero/bravedns/provider/ApplicationProvider.kt index d0fc8dc7c..186b193b6 100644 --- a/app/src/headless/java/com/celzero/bravedns/provider/ApplicationProvider.kt +++ b/app/src/headless/java/com/celzero/bravedns/provider/ApplicationProvider.kt @@ -15,17 +15,16 @@ */ package com.celzero.bravedns.provider +import Logger.LOG_PROVIDER import android.content.ContentProvider import android.content.ContentUris import android.content.ContentValues import android.content.UriMatcher import android.database.Cursor import android.net.Uri -import android.util.Log import com.celzero.bravedns.database.AppInfo import com.celzero.bravedns.database.AppInfoRepository import com.celzero.bravedns.service.FirewallManager -import com.celzero.bravedns.util.Logger import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -61,7 +60,7 @@ class ApplicationProvider : ContentProvider() { sortOrder: String? ): Cursor { if (!isValidRequest(uri)) { - Log.e(Logger.LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") + Logger.e(LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") throw java.lang.IllegalArgumentException("Invalid URI, cannot update without ID$uri") } return appInfoRepository.getAppsCursor() @@ -79,7 +78,7 @@ class ApplicationProvider : ContentProvider() { override fun insert(uri: Uri, values: ContentValues?): Uri? { if (!isValidRequest(uri)) { - Log.e(Logger.LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") + Logger.e(LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") throw java.lang.IllegalArgumentException("invalid uri, cannot update without ID$uri") } val appInfo = AppInfo(values) @@ -93,13 +92,10 @@ class ApplicationProvider : ContentProvider() { override fun delete(uri: Uri, selection: String?, selectionArgs: Array?): Int { if (!isValidRequest(uri)) { - Log.e(Logger.LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") + Logger.e(LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") throw java.lang.IllegalArgumentException("Invalid URI, cannot update without ID$uri") } - Log.i( - Logger.LOG_PROVIDER, - "request to delete app, parameters $uri, $selection, $selectionArgs" - ) + Logger.i(LOG_PROVIDER, "request to delete app, parameters $uri, $selection, $selectionArgs") val id = ContentUris.parseId(uri).toInt() val count = appInfoRepository.cpDelete(id) // update the app info cache @@ -115,7 +111,7 @@ class ApplicationProvider : ContentProvider() { selectionArgs: Array? ): Int { if (!isValidRequest(uri)) { - Log.e(Logger.LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") + Logger.e(LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") throw java.lang.IllegalArgumentException("invalid uri, cannot update without ID$uri") } @@ -133,7 +129,7 @@ class ApplicationProvider : ContentProvider() { // if the selection clause contains uid or packageName, then the selectionArgs should // contain the values for the same. if (c != (selectionArgs?.size ?: 0)) { - Log.e(Logger.LOG_PROVIDER, "invalid selection clause: $selectionClause") + Logger.e(LOG_PROVIDER, "invalid selection clause: $selectionClause") throw java.lang.IllegalArgumentException( "invalid selection clause: $selectionClause" ) @@ -143,8 +139,8 @@ class ApplicationProvider : ContentProvider() { for (i in 0 until c) { clause = clause.replaceFirst("?", selectionArgs?.get(i) ?: "") } - Log.i( - Logger.LOG_PROVIDER, + Logger.i( + LOG_PROVIDER, "selection ${appInfo.appName}, ${appInfo.uid}, ${appInfo.firewallStatus} clause: $clause" ) val count = appInfoRepository.cpUpdate(appInfo, clause) @@ -153,7 +149,7 @@ class ApplicationProvider : ContentProvider() { context.contentResolver?.notifyChange(uri, null) return count } else { - Log.e(Logger.LOG_PROVIDER, "invalid selection clause: $selectionClause") + Logger.e(LOG_PROVIDER, "invalid selection clause: $selectionClause") throw java.lang.IllegalArgumentException("invalid selection clause: $selectionClause") } } @@ -161,10 +157,7 @@ class ApplicationProvider : ContentProvider() { private fun isValidRequest(uri: Uri): Boolean { // check the calling package if (callingPackage != RESOLVER_PACKAGE_NAME) { - Log.e( - Logger.LOG_PROVIDER, - "request received from unknown package: $callingPackage" - ) + Logger.e(LOG_PROVIDER, "request received from unknown package: $callingPackage") return false } diff --git a/app/src/headless/java/com/celzero/bravedns/provider/BlocklistProvider.kt b/app/src/headless/java/com/celzero/bravedns/provider/BlocklistProvider.kt index a21c2366c..0bfd16ecb 100644 --- a/app/src/headless/java/com/celzero/bravedns/provider/BlocklistProvider.kt +++ b/app/src/headless/java/com/celzero/bravedns/provider/BlocklistProvider.kt @@ -15,16 +15,15 @@ */ package com.celzero.bravedns.provider +import Logger.LOG_PROVIDER import android.content.* import android.database.Cursor import android.net.Uri import android.os.Bundle -import android.util.Log import com.celzero.bravedns.database.RethinkLocalFileTag import com.celzero.bravedns.database.RethinkLocalFileTagRepository import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.service.RethinkBlocklistManager -import com.celzero.bravedns.util.Logger.Companion.LOG_PROVIDER import org.koin.android.ext.android.inject class BlocklistProvider : ContentProvider() { @@ -71,7 +70,7 @@ class BlocklistProvider : ContentProvider() { sortOrder: String? ): Cursor? { if (!isValidRequest(uri)) { - Log.e(LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") + Logger.e(LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") throw java.lang.IllegalArgumentException("Invalid URI, cannot update without ID$uri") } @@ -79,7 +78,7 @@ class BlocklistProvider : ContentProvider() { if (context == null) { return null } - Log.i(LOG_PROVIDER, "blocklists query with parameters $uri, $selection, $selectionArgs") + Logger.i(LOG_PROVIDER, "blocklists query with parameters $uri, $selection, $selectionArgs") uriMatcher.match(uri).let { cursor = when (it) { @@ -120,11 +119,11 @@ class BlocklistProvider : ContentProvider() { override fun insert(uri: Uri, values: ContentValues?): Uri? { if (!isValidRequest(uri)) { - Log.e(LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") + Logger.e(LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") throw java.lang.IllegalArgumentException("Invalid URI, cannot update without ID$uri") } - Log.i(LOG_PROVIDER, "request to insert new blocklist, parameters $values") + Logger.i(LOG_PROVIDER, "request to insert new blocklist, parameters $values") val localFileTags = RethinkLocalFileTag(values) val id = localFileTagRepository.contentInsert(localFileTags) context?.contentResolver?.notifyChange(uri, null) @@ -133,10 +132,10 @@ class BlocklistProvider : ContentProvider() { override fun delete(uri: Uri, selection: String?, selectionArgs: Array?): Int { if (!isValidRequest(uri)) { - Log.e(LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") + Logger.e(LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") throw java.lang.IllegalArgumentException("Invalid URI, cannot update without ID$uri") } - Log.i( + Logger.i( LOG_PROVIDER, "request to delete blocklist, parameters $uri, $selection, $selectionArgs" ) @@ -152,12 +151,12 @@ class BlocklistProvider : ContentProvider() { when (method) { METHOD_GET_STAMP -> { val stamp = persistentState.localBlocklistStamp - Log.i(LOG_PROVIDER, "request for blocklist stamp, sending: $stamp") + Logger.i(LOG_PROVIDER, "request for blocklist stamp, sending: $stamp") bundle.putString(STAMP, persistentState.localBlocklistStamp) } METHOD_UPDATE_STAMP -> { val rcvStamp = arg ?: "" - Log.i(LOG_PROVIDER, "received stamp to update local blocklist: $rcvStamp") + Logger.i(LOG_PROVIDER, "received stamp to update local blocklist: $rcvStamp") if (rcvStamp.isNotEmpty()) { persistentState.localBlocklistStamp = rcvStamp @@ -175,7 +174,7 @@ class BlocklistProvider : ContentProvider() { selectionArgs: Array? ): Int { if (!isValidRequest(uri)) { - Log.e(LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") + Logger.e(LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") throw java.lang.IllegalArgumentException("invalid uri, cannot update without ID$uri") } @@ -200,7 +199,7 @@ class BlocklistProvider : ContentProvider() { // check the calling package if (callingPackage != RESOLVER_PACKAGE_NAME) { - Log.e( + Logger.e( LOG_PROVIDER, "request received from unknown package: $callingPackage, $RESOLVER_PACKAGE_NAME" ) diff --git a/app/src/headless/java/com/celzero/bravedns/provider/DomainRuleProvider.kt b/app/src/headless/java/com/celzero/bravedns/provider/DomainRuleProvider.kt index a7fa33c5b..3c7f1a82d 100644 --- a/app/src/headless/java/com/celzero/bravedns/provider/DomainRuleProvider.kt +++ b/app/src/headless/java/com/celzero/bravedns/provider/DomainRuleProvider.kt @@ -15,19 +15,18 @@ */ package com.celzero.bravedns.provider +import Logger.LOG_PROVIDER import android.content.ContentProvider import android.content.ContentUris import android.content.ContentValues import android.content.UriMatcher import android.database.Cursor import android.net.Uri -import android.util.Log import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.database.CustomDomain import com.celzero.bravedns.database.CustomDomainRepository import com.celzero.bravedns.service.DomainRulesManager import com.celzero.bravedns.util.Constants -import com.celzero.bravedns.util.Logger import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -63,13 +62,13 @@ class DomainRuleProvider : ContentProvider() { sortOrder: String? ): Cursor { if (!isValidRequest(uri)) { - Log.e(Logger.LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") + Logger.e(LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") throw java.lang.IllegalArgumentException("Invalid URI, cannot update without ID$uri") } if (DEBUG) - Log.d( - Logger.LOG_PROVIDER, + Logger.d( + LOG_PROVIDER, "insert blocklists with uri: $uri, projection: $projection, selection: $selection, selectionArgs: $selectionArgs, sortOrder: $sortOrder" ) return customDomainRepository.getRulesCursor() @@ -87,16 +86,15 @@ class DomainRuleProvider : ContentProvider() { override fun insert(uri: Uri, values: ContentValues?): Uri? { if (!isValidRequest(uri)) { - Log.e(Logger.LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") + Logger.e(LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") throw java.lang.IllegalArgumentException("invalid uri, cannot update without ID$uri") } val customDomain = CustomDomain(values) - if (DEBUG) - Log.d( - Logger.LOG_PROVIDER, - "insert blocklists with uri: $uri, values: $values, obj: ${customDomain.domain}, ${customDomain.uid}, ${customDomain.status}" - ) + Logger.d( + LOG_PROVIDER, + "insert blocklists with uri: $uri, values: $values, obj: ${customDomain.domain}, ${customDomain.uid}, ${customDomain.status}" + ) val id = customDomainRepository.cpInsert(customDomain) context?.contentResolver?.notifyChange(uri, null) return ContentUris.withAppendedId(uri, id) @@ -104,19 +102,16 @@ class DomainRuleProvider : ContentProvider() { override fun delete(uri: Uri, selection: String?, selectionArgs: Array?): Int { if (!isValidRequest(uri)) { - Log.e(Logger.LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") + Logger.e(LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") throw java.lang.IllegalArgumentException("Invalid URI, cannot update without ID$uri") } if (selection.isNullOrEmpty()) { - Log.e(Logger.LOG_PROVIDER, "invalid selection clause: $selection") + Logger.e(LOG_PROVIDER, "invalid selection clause: $selection") throw java.lang.IllegalArgumentException("invalid selection clause: $selection") } - Log.i( - Logger.LOG_PROVIDER, - "request to delete app, parameters $uri, $selection, $selectionArgs" - ) + Logger.i(LOG_PROVIDER, "request to delete app, parameters $uri, $selection, $selectionArgs") val domain = if (selection.contains("domain")) { @@ -126,10 +121,7 @@ class DomainRuleProvider : ContentProvider() { } if (domain.isNullOrEmpty()) { - Log.e( - Logger.LOG_PROVIDER, - "required domain name on selection clause: $selection" - ) + Logger.e(LOG_PROVIDER, "required domain name on selection clause: $selection") throw java.lang.IllegalArgumentException( "required domain name on selection clause: $selection" ) @@ -139,15 +131,11 @@ class DomainRuleProvider : ContentProvider() { if (selection.contains("uid")) { selectionArgs?.get(1)?.toInt() } else { - Log.e( - Logger.LOG_PROVIDER, - "required domain name on selection clause: $selection" - ) + Logger.e(LOG_PROVIDER, "required domain name on selection clause: $selection") throw java.lang.IllegalArgumentException( "required domain name on selection clause: $selection" ) - } - ?: Constants.UID_EVERYBODY + } ?: Constants.UID_EVERYBODY val count = customDomainRepository.cpDelete(domain, uid) // update the app info cache @@ -163,7 +151,7 @@ class DomainRuleProvider : ContentProvider() { selectionArgs: Array? ): Int { if (!isValidRequest(uri)) { - Log.e(Logger.LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") + Logger.e(LOG_PROVIDER, "invalid uri, cannot update without ID: $uri") throw java.lang.IllegalArgumentException("invalid uri, cannot update without ID$uri") } @@ -180,7 +168,7 @@ class DomainRuleProvider : ContentProvider() { // if the selection clause contains uid or packageName, then the selectionArgs should // contain the values for the same. if (c != (selectionArgs?.size ?: 0)) { - Log.e(Logger.LOG_PROVIDER, "invalid selection clause: $selectionClause") + Logger.e(LOG_PROVIDER, "invalid selection clause: $selectionClause") throw java.lang.IllegalArgumentException( "invalid selection clause: $selectionClause" ) @@ -191,8 +179,7 @@ class DomainRuleProvider : ContentProvider() { clause = clause.replaceFirst("?", selectionArgs?.get(i) ?: "") } if (DEBUG) - Log.d( - Logger.LOG_PROVIDER, + Logger.d(LOG_PROVIDER, "selection ${customDomain.domain}, ${customDomain.uid}, ${customDomain.status} clause: $clause" ) val count = customDomainRepository.cpUpdate(customDomain, clause) @@ -200,7 +187,7 @@ class DomainRuleProvider : ContentProvider() { context.contentResolver?.notifyChange(uri, null) return count } else { - Log.e(Logger.LOG_PROVIDER, "invalid selection clause: $selectionClause") + Logger.e(LOG_PROVIDER, "invalid selection clause: $selectionClause") throw java.lang.IllegalArgumentException("invalid selection clause: $selectionClause") } } @@ -208,10 +195,7 @@ class DomainRuleProvider : ContentProvider() { private fun isValidRequest(uri: Uri): Boolean { // check the calling package if (callingPackage != RESOLVER_PACKAGE_NAME) { - Log.e( - Logger.LOG_PROVIDER, - "request received from unknown package: $callingPackage" - ) + Logger.e(LOG_PROVIDER, "request received from unknown package: $callingPackage") return false } diff --git a/app/src/headless/java/com/celzero/bravedns/service/ProxyManager.kt b/app/src/headless/java/com/celzero/bravedns/service/ProxyManager.kt index dab868822..5f1e1376b 100644 --- a/app/src/headless/java/com/celzero/bravedns/service/ProxyManager.kt +++ b/app/src/headless/java/com/celzero/bravedns/service/ProxyManager.kt @@ -72,4 +72,12 @@ object ProxyManager : KoinComponent { fun isIpnProxy(ipnProxyId: String): Boolean { return false } + + fun trackedApps() : MutableSet { + return mutableSetOf() + } + + fun deleteApps(apps: Collection) {} + + fun addApps(apps: Collection) {} } diff --git a/app/src/main/java/com/celzero/bravedns/backup/BackupAgent.kt b/app/src/main/java/com/celzero/bravedns/backup/BackupAgent.kt index 688421e38..fb9779d94 100644 --- a/app/src/main/java/com/celzero/bravedns/backup/BackupAgent.kt +++ b/app/src/main/java/com/celzero/bravedns/backup/BackupAgent.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.backup +import Logger.LOG_TAG_BACKUP_RESTORE import android.content.Context import android.content.SharedPreferences import android.net.Uri @@ -37,7 +38,6 @@ import com.celzero.bravedns.backup.BackupHelper.Companion.getRethinkDatabase import com.celzero.bravedns.backup.BackupHelper.Companion.getTempDir import com.celzero.bravedns.backup.BackupHelper.Companion.startVpn import com.celzero.bravedns.service.PersistentState -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_BACKUP_RESTORE import com.celzero.bravedns.util.Utilities import com.celzero.bravedns.util.Utilities.copyWithStream import org.koin.core.component.KoinComponent @@ -69,11 +69,10 @@ class BackupAgent(val context: Context, workerParams: WorkerParameters) : override fun doWork(): Result { val backupFileUri = Uri.parse(inputData.getString(DATA_BUILDER_BACKUP_URI)) - if (DEBUG) - Log.d(LOG_TAG_BACKUP_RESTORE, "begin backup process with file uri: $backupFileUri") + Logger.d(LOG_TAG_BACKUP_RESTORE, "begin backup process with file uri: $backupFileUri") val isBackupSucceed = startBackupProcess(backupFileUri) - Log.i( + Logger.i( LOG_TAG_BACKUP_RESTORE, "completed backup process, is backup successful? $isBackupSucceed" ) diff --git a/app/src/main/java/com/celzero/bravedns/backup/BackupHelper.kt b/app/src/main/java/com/celzero/bravedns/backup/BackupHelper.kt index 48300f67a..4869113b8 100644 --- a/app/src/main/java/com/celzero/bravedns/backup/BackupHelper.kt +++ b/app/src/main/java/com/celzero/bravedns/backup/BackupHelper.kt @@ -20,7 +20,6 @@ import android.util.Log import com.celzero.bravedns.R import com.celzero.bravedns.database.AppDatabase import com.celzero.bravedns.service.VpnController -import com.celzero.bravedns.util.Logger import java.io.BufferedInputStream import java.io.ByteArrayOutputStream import java.io.File @@ -98,12 +97,12 @@ class BackupHelper { } fun stopVpn(context: Context) { - Log.i(Logger.LOG_TAG_BACKUP_RESTORE, "calling vpn stop from backup helper") + Logger.i(Logger.LOG_TAG_BACKUP_RESTORE, "calling vpn stop from backup helper") VpnController.stop(context) } fun startVpn(context: Context) { - Log.i(Logger.LOG_TAG_BACKUP_RESTORE, "calling vpn start from backup helper") + Logger.i(Logger.LOG_TAG_BACKUP_RESTORE, "calling vpn start from backup helper") VpnController.start(context) } diff --git a/app/src/main/java/com/celzero/bravedns/backup/RestoreAgent.kt b/app/src/main/java/com/celzero/bravedns/backup/RestoreAgent.kt index 0e953feb2..02a49bba4 100644 --- a/app/src/main/java/com/celzero/bravedns/backup/RestoreAgent.kt +++ b/app/src/main/java/com/celzero/bravedns/backup/RestoreAgent.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.backup +import Logger.LOG_TAG_BACKUP_RESTORE import android.content.Context import android.content.SharedPreferences import android.content.pm.PackageInfo @@ -37,7 +38,6 @@ import com.celzero.bravedns.database.AppDatabase import com.celzero.bravedns.database.LogDatabase import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.service.WireguardManager -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_BACKUP_RESTORE import com.celzero.bravedns.util.Utilities import org.koin.core.component.KoinComponent import org.koin.core.component.inject @@ -61,10 +61,10 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : override suspend fun doWork(): Result { val restoreUri = Uri.parse(inputData.getString(DATA_BUILDER_RESTORE_URI)) - if (DEBUG) Log.d(LOG_TAG_BACKUP_RESTORE, "begin restore process with file uri: $restoreUri") + Logger.d(LOG_TAG_BACKUP_RESTORE, "begin restore process with file uri: $restoreUri") val result = startRestore(restoreUri) - Log.i(LOG_TAG_BACKUP_RESTORE, "completed restore process, is successful? $result") + Logger.i(LOG_TAG_BACKUP_RESTORE, "completed restore process, is successful? $result") return if (result) { Result.success() } else { @@ -79,29 +79,27 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : val tempDir = getTempDir(context) inputStream = context.contentResolver.openInputStream(importUri) - if (DEBUG) - Log.d(LOG_TAG_BACKUP_RESTORE, "restore process, temp file dir: ${tempDir.path}") + Logger.d(LOG_TAG_BACKUP_RESTORE, "restore process, temp file dir: ${tempDir.path}") // unzip the backup files to tempDir if (!unzip(inputStream, tempDir.path)) { - Log.w( + Logger.w( LOG_TAG_BACKUP_RESTORE, "failed to unzip the uri to temp dir $importUri, ${tempDir.path}, return failure" ) return false } else { - if (DEBUG) - Log.d(LOG_TAG_BACKUP_RESTORE, "restore process, unzipped the files to temp dir") + Logger.d(LOG_TAG_BACKUP_RESTORE, "restore process, unzipped the files to temp dir") // proceed } if (!validateMetadata(tempDir.path)) { - Log.w( + Logger.w( LOG_TAG_BACKUP_RESTORE, "invalid meta-data or metadata not found. maybe earlier version backup" ) return false } else { - Log.i(LOG_TAG_BACKUP_RESTORE, "metadata file validation complete") + Logger.i(LOG_TAG_BACKUP_RESTORE, "metadata file validation complete") // no-op; proceed } @@ -109,19 +107,19 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : // if shared pref copy is succeeds then proceed to database restore else // return failed if (!restoreSharedPreferencesFromFile(tempDir.path)) { - Log.w(LOG_TAG_BACKUP_RESTORE, "failed to restore shared pref, return failure") + Logger.w(LOG_TAG_BACKUP_RESTORE, "failed to restore shared pref, return failure") return false } else { - Log.i(LOG_TAG_BACKUP_RESTORE, "shared pref restored to the temp dir") + Logger.i(LOG_TAG_BACKUP_RESTORE, "shared pref restored to the temp dir") // proceed } // Copy new database file into its final directory if (!restoreDatabaseFile(tempDir)) { - Log.w(LOG_TAG_BACKUP_RESTORE, "failed to restore database, return failure") + Logger.w(LOG_TAG_BACKUP_RESTORE, "failed to restore database, return failure") return false } else { - Log.i(LOG_TAG_BACKUP_RESTORE, "database restored to the temp dir") + Logger.i(LOG_TAG_BACKUP_RESTORE, "database restored to the temp dir") // proceed } @@ -136,7 +134,7 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : return true } catch (e: Exception) { - Log.e( + Logger.e( LOG_TAG_BACKUP_RESTORE, "exception during restore process, reason? ${e.message}", e @@ -150,7 +148,7 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : private fun handleDatabaseInit() { // get writable database for logs if (!logDatabase.isOpen) { - Log.i( + Logger.i( LOG_TAG_BACKUP_RESTORE, "log database is not open, perform writableDatabase operation" ) @@ -161,7 +159,7 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : // get writable database for app if (!appDatabase.isOpen) { - Log.i( + Logger.i( LOG_TAG_BACKUP_RESTORE, "app database is not open, perform writableDatabase operation" ) @@ -175,24 +173,21 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : private fun restoreDatabaseFile(tempDir: File): Boolean { checkPoint() - if (DEBUG) - Log.d(LOG_TAG_BACKUP_RESTORE, "begin restore database to temp dir: ${tempDir.path}") + Logger.d(LOG_TAG_BACKUP_RESTORE, "begin restore database to temp dir: ${tempDir.path}") val files = tempDir.listFiles() if (files == null) { - Log.w(LOG_TAG_BACKUP_RESTORE, "files to restore is empty, path: ${tempDir.path}") + Logger.w(LOG_TAG_BACKUP_RESTORE, "files to restore is empty, path: ${tempDir.path}") return false } - if (DEBUG) - Log.d( + Logger.d( LOG_TAG_BACKUP_RESTORE, "List of files in backup folder: ${files.size}, path: ${tempDir.path}" ) for (file in files) { val currentDbFile = File(context.getDatabasePath(file.name).path) - if (DEBUG) - Log.d( + Logger.d( LOG_TAG_BACKUP_RESTORE, "db file: ${file.name} backed up from ${file.path} to ${currentDbFile.path}" ) @@ -201,14 +196,14 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : !file.name.contains(AppDatabase.DATABASE_NAME) && !file.name.contains(LogDatabase.LOGS_DATABASE_NAME) ) { - Log.w( + Logger.w( LOG_TAG_BACKUP_RESTORE, "restore process, file name is not db, file name: ${file.name}" ) continue } if (!Utilities.copy(file.path, currentDbFile.path)) { - Log.w( + Logger.w( LOG_TAG_BACKUP_RESTORE, "restore process, failure copying database file: ${file.path} to ${currentDbFile.path}" ) @@ -223,9 +218,9 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : private fun updateLatestVersion() { if (isNewVersion()) { persistentState.appVersion = getLatestVersion() - Log.i(LOG_TAG_BACKUP_RESTORE, "app version updated to ${persistentState.appVersion}") + Logger.i(LOG_TAG_BACKUP_RESTORE, "app version updated to ${persistentState.appVersion}") } else { - Log.i(LOG_TAG_BACKUP_RESTORE, "no need to update app version") + Logger.i(LOG_TAG_BACKUP_RESTORE, "no need to update app version") } } @@ -242,7 +237,7 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : } private fun checkPoint() { - Log.i(LOG_TAG_BACKUP_RESTORE, "database checkpoint() during restore process") + Logger.i(LOG_TAG_BACKUP_RESTORE, "database checkpoint() during restore process") appDatabase.checkPoint() logDatabase.checkPoint() return @@ -263,7 +258,7 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : val metadata = stream.bufferedReader().use { it.readText() } isVersionSupported(metadata) } catch (ignored: Exception) { - Log.e( + Logger.e( LOG_TAG_BACKUP_RESTORE, "error while restoring metadata, reason? ${ignored.message}", ignored @@ -273,7 +268,7 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : try { stream?.close() } catch (ignored: IOException) { - Log.e( + Logger.e( LOG_TAG_BACKUP_RESTORE, "error while restoring metadata, reason? ${ignored.message}", ignored @@ -284,11 +279,11 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : private fun wireGuardCleanup() { if (appConfig.isWireGuardEnabled()) { - Log.i(LOG_TAG_BACKUP_RESTORE, "wireGuard is enabled, reset the wireguard entries") + Logger.i(LOG_TAG_BACKUP_RESTORE, "wireGuard is enabled, reset the wireguard entries") appConfig.removeAllProxies() } // delete WireGuard related entries from database - Log.i(LOG_TAG_BACKUP_RESTORE, "wireguard cleanup process") + Logger.i(LOG_TAG_BACKUP_RESTORE, "wireguard cleanup process") WireguardManager.restoreProcessDeleteWireGuardEntries() } @@ -310,7 +305,7 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : if (key == PersistentState.APP_VERSION) { val appVersion = v as Int if (appVersion >= minVersionSupported) { - Log.w( + Logger.w( LOG_TAG_BACKUP_RESTORE, "app version is less than minAppVersion, proceed with restore" ) @@ -324,7 +319,7 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : } return false } catch (e: Exception) { - Log.e( + Logger.e( LOG_TAG_BACKUP_RESTORE, "exception while restoring shared pref, reason? ${e.message}", e @@ -348,7 +343,7 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : // there is only one database), so do not consider the backups prior to that return version >= minVersionSupported && persistentState.appVersion >= version } catch (e: Exception) { - Log.e(LOG_TAG_BACKUP_RESTORE, "error while reading metadata, reason? ${e.message}", e) + Logger.e(LOG_TAG_BACKUP_RESTORE, "error while reading metadata, reason? ${e.message}", e) return false } } @@ -359,7 +354,7 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : val currentSharedPreferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) - if (DEBUG) Log.d(LOG_TAG_BACKUP_RESTORE, "shared pref file path: ${prefsBackupFile.path}") + Logger.d(LOG_TAG_BACKUP_RESTORE, "shared pref file path: ${prefsBackupFile.path}") try { input = ObjectInputStream(FileInputStream(prefsBackupFile)) val prefsEditor = currentSharedPreferences.edit() @@ -377,13 +372,13 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : else if (v is String) prefsEditor.putString(key, v as String?) } prefsEditor.apply() - Log.i( + Logger.i( LOG_TAG_BACKUP_RESTORE, "completed restore of shared pref values, ${pref.entries}" ) return true } catch (e: Exception) { - Log.e( + Logger.e( LOG_TAG_BACKUP_RESTORE, "exception while restoring shared pref, reason? ${e.message}", e diff --git a/app/src/main/java/com/celzero/bravedns/data/AppConfig.kt b/app/src/main/java/com/celzero/bravedns/data/AppConfig.kt index e440977ec..9383d957f 100644 --- a/app/src/main/java/com/celzero/bravedns/data/AppConfig.kt +++ b/app/src/main/java/com/celzero/bravedns/data/AppConfig.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.data +import Logger.LOG_TAG_VPN import android.content.Context import android.util.Log import androidx.lifecycle.LiveData @@ -45,7 +46,6 @@ import com.celzero.bravedns.util.Constants import com.celzero.bravedns.util.Constants.Companion.MAX_ENDPOINT import com.celzero.bravedns.util.InternetProtocol import com.celzero.bravedns.util.InternetProtocol.Companion.getInternetProtocol -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_VPN import com.celzero.bravedns.util.OrbotHelper import com.celzero.bravedns.util.PcapMode import com.celzero.bravedns.util.Utilities.isAtleastQ @@ -384,7 +384,7 @@ internal constructor( DnsType.DOT.type -> DnsType.DOT DnsType.ODOH.type -> DnsType.ODOH else -> { - Log.w(LOG_TAG_VPN, "Invalid dns type mode: ${persistentState.dnsType}") + Logger.w(LOG_TAG_VPN, "Invalid dns type mode: ${persistentState.dnsType}") DnsType.DOH } } @@ -931,7 +931,7 @@ internal constructor( setProxy(ProxyType.HTTP, removeProvider) return } else { - Log.w( + Logger.w( LOG_TAG_VPN, "invalid remove proxy call, type: ${removeType.name}, provider: ${removeProvider.name}" ) @@ -962,7 +962,7 @@ internal constructor( fun getTunProxyMode(): TunProxyMode { val type = persistentState.proxyType val provider = persistentState.proxyProvider - if (DEBUG) Log.d(LOG_TAG_VPN, "selected proxy type: $type, with provider as $provider") + Logger.d(LOG_TAG_VPN, "selected proxy type: $type, with provider as $provider") if (ProxyProvider.WIREGUARD.name == provider) { return TunProxyMode.WIREGUARD diff --git a/app/src/main/java/com/celzero/bravedns/database/LogDatabase.kt b/app/src/main/java/com/celzero/bravedns/database/LogDatabase.kt index ec8cbe163..9142f178c 100644 --- a/app/src/main/java/com/celzero/bravedns/database/LogDatabase.kt +++ b/app/src/main/java/com/celzero/bravedns/database/LogDatabase.kt @@ -137,7 +137,7 @@ abstract class LogDatabase : RoomDatabase() { } db.enableWriteAheadLogging() } catch (ignored: Exception) { - Log.e( + Logger.e( "MIGRATION", "error migrating from v1to2 on log db: ${ignored.message}", ignored diff --git a/app/src/main/java/com/celzero/bravedns/database/RefreshDatabase.kt b/app/src/main/java/com/celzero/bravedns/database/RefreshDatabase.kt index 7b46308fd..ba95478f8 100644 --- a/app/src/main/java/com/celzero/bravedns/database/RefreshDatabase.kt +++ b/app/src/main/java/com/celzero/bravedns/database/RefreshDatabase.kt @@ -15,6 +15,8 @@ */ package com.celzero.bravedns.database +import Logger.LOG_TAG_APP_DB +import Logger.LOG_TAG_VPN import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent @@ -26,12 +28,10 @@ import android.content.pm.PackageManager import android.net.VpnService import android.os.Build import android.os.SystemClock -import android.util.Log import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.receiver.NotificationActionReceiver import com.celzero.bravedns.service.DomainRulesManager import com.celzero.bravedns.service.FirewallManager @@ -47,8 +47,6 @@ import com.celzero.bravedns.ui.HomeScreenActivity import com.celzero.bravedns.ui.NotificationHandlerDialog import com.celzero.bravedns.util.AndroidUidConfig import com.celzero.bravedns.util.Constants -import com.celzero.bravedns.util.Logger -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_APP_DB import com.celzero.bravedns.util.PlayStoreCategory import com.celzero.bravedns.util.UIUtils import com.celzero.bravedns.util.Utilities @@ -118,7 +116,7 @@ internal constructor( try { val action = a.action val uid = a.uid // may be -1 - if (DEBUG) Log.d(LOG_TAG_APP_DB, "Initiated refresh application info $a") + Logger.d(LOG_TAG_APP_DB, "Initiated refresh application info $a") if (action == ACTION_INSERT_NEW_APP) { // ignore invalid uid (app source could not be determined) // ignore missing uid (protocol unknown or connectivity mgr missing) @@ -133,7 +131,7 @@ internal constructor( current - latestRefreshTime < FULL_REFRESH_INTERVAL && (action == ACTION_REFRESH_AUTO || action == ACTION_REFRESH_INTERACTIVE) ) { - Log.i(LOG_TAG_APP_DB, "no-op auto refresh") + Logger.i(LOG_TAG_APP_DB, "no-op auto refresh") return } latestRefreshTime = current @@ -146,7 +144,7 @@ internal constructor( val wgm = WireguardManager.load() val tcpm = TcpProxyHelper.load() - Log.i( + Logger.i( LOG_TAG_APP_DB, "reload: fm: ${fm}; ip: ${ipm}; dom: ${dm}; px: ${pxm}; wg: ${wgm}; t: ${tcpm}" ) @@ -178,7 +176,7 @@ internal constructor( printAll(packagesToDelete, "packagesToDelete") printAll(packagesToUpdate, "packagesToUpdate") - Log.i( + Logger.i( LOG_TAG_APP_DB, "sizes: rmv: ${packagesToDelete.size}; add: ${packagesToAdd.size}; update: ${packagesToUpdate.size}" ) @@ -196,7 +194,7 @@ internal constructor( // must be called after updateExistingPackagesIfNeeded refreshDomainRules(packagesToUpdate) } catch (e: RuntimeException) { - Log.e(LOG_TAG_APP_DB, e.message, e) + Logger.e(LOG_TAG_APP_DB, e.message ?: "refresh err", e) throw e } finally { notifyEmptyFirewallRulesIfNeeded() @@ -340,12 +338,12 @@ internal constructor( private suspend fun maybeInsertApp(uid: Int) { val knownUid = FirewallManager.hasUid(uid) if (knownUid) { - Log.i(LOG_TAG_APP_DB, "insertApp: $uid already tracked") + Logger.i(LOG_TAG_APP_DB, "insertApp: $uid already tracked") return } val ai = maybeFetchAppInfo(uid) val pkg = ai?.packageName ?: "" - Log.i(LOG_TAG_APP_DB, "insert app; uid: $uid, pkg: ${pkg}") + Logger.i(LOG_TAG_APP_DB, "insert app; uid: $uid, pkg: ${pkg}") if (ai != null) { // uid may be different from the one in ai, if the app is installed in a different user insertApp(ai) @@ -375,7 +373,7 @@ internal constructor( if (rmv) { WireguardManager.restoreProcessDeleteWireGuardEntries() } else { - if (DEBUG) Log.d(LOG_TAG_APP_DB, "removeWireGuardProfilesIfNeeded: no-op") + Logger.d(LOG_TAG_APP_DB, "removeWireGuardProfilesIfNeeded: no-op") } } @@ -386,7 +384,7 @@ internal constructor( // trackedApps is empty, the installed apps are yet to be added to the database; and so, // there's no need to refresh these mappings as apps tracked by FirewallManager is empty if (trackedApps.isEmpty()) { - Log.i(LOG_TAG_APP_DB, "refreshProxyMapping: trackedApps is empty") + Logger.i(LOG_TAG_APP_DB, "refreshProxyMapping: trackedApps is empty") return } @@ -408,7 +406,7 @@ internal constructor( findPackagesToAdd(pxm, trackedApps).map { FirewallManager.getAppInfoByUid(it.uid) } ProxyManager.deleteApps(del) ProxyManager.addApps(add) - Log.i( + Logger.i( "AppDatabase", "refreshing proxy mapping, size: ${pxm.size}, trackedApps: ${trackedApps.size}" ) @@ -440,7 +438,7 @@ internal constructor( } private suspend fun updateApp(oldUid: Int, newUid: Int, pkg: String) { - Log.i(LOG_TAG_APP_DB, "update app; oldUid: $oldUid, newUid: $newUid, pkg: $pkg") + Logger.i(LOG_TAG_APP_DB, "update app; oldUid: $oldUid, newUid: $newUid, pkg: $pkg") FirewallManager.updateUid(oldUid, newUid, pkg) } @@ -468,7 +466,7 @@ internal constructor( entry.appCategory = determineAppCategory(ai) - Log.i(LOG_TAG_APP_DB, "insert app: $ai") + Logger.i(LOG_TAG_APP_DB, "insert app: $ai") FirewallManager.persistAppInfo(entry) ProxyManager.addNewApp(entry) } @@ -494,7 +492,7 @@ internal constructor( val notificationManager = ctx.getSystemService(VpnService.NOTIFICATION_SERVICE) as NotificationManager - if (DEBUG) Log.d(Logger.LOG_TAG_VPN, "Number of new apps: $appSize, show notification") + Logger.d(LOG_TAG_VPN, "Number of new apps: $appSize, show notification") val intent = Intent(ctx, NotificationHandlerDialog::class.java) intent.putExtra( @@ -568,7 +566,7 @@ internal constructor( val notificationManager = ctx.getSystemService(VpnService.NOTIFICATION_SERVICE) as NotificationManager - if (DEBUG) Log.d(Logger.LOG_TAG_VPN, "New app installed: $appName, show notification") + Logger.d(LOG_TAG_VPN, "New app installed: $appName, show notification") val intent = Intent(ctx, NotificationHandlerDialog::class.java) intent.putExtra( @@ -782,7 +780,7 @@ internal constructor( } private fun printAll(c: Collection, tag: String) { - c.forEach { Log.i(LOG_TAG_APP_DB, "$tag: ${it.uid}, ${it.packageName}") } + c.forEach { Logger.i(LOG_TAG_APP_DB, "$tag: ${it.uid}, ${it.packageName}") } } /** Below code to fetch the google play service-application category Not in use as of now. */ diff --git a/app/src/main/java/com/celzero/bravedns/glide/FavIconDownloader.kt b/app/src/main/java/com/celzero/bravedns/glide/FavIconDownloader.kt index fd35e6475..4d89e39a2 100644 --- a/app/src/main/java/com/celzero/bravedns/glide/FavIconDownloader.kt +++ b/app/src/main/java/com/celzero/bravedns/glide/FavIconDownloader.kt @@ -15,14 +15,12 @@ limitations under the License. */ package com.celzero.bravedns.glide +import Logger.LOG_TAG_DNS import android.content.Context import android.os.Process -import android.util.Log import com.bumptech.glide.Glide import com.bumptech.glide.request.FutureTarget import com.bumptech.glide.request.target.Target.SIZE_ORIGINAL -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_DNS_LOG import com.celzero.bravedns.util.Utilities import com.google.common.cache.Cache import com.google.common.cache.CacheBuilder @@ -95,10 +93,10 @@ class FavIconDownloader(val context: Context, private val url: String) : Runnabl .submit(SIZE_ORIGINAL, SIZE_ORIGINAL) try { futureTarget.get() - if (DEBUG) Log.d(LOG_TAG_DNS_LOG, "Glide, load success from nextdns for url: $url") + Logger.d(LOG_TAG_DNS, "Glide, load success from nextdns for url: $url") } catch (e: Exception) { // on exception, initiate the download of fav icon from duckduckgo - Log.i(LOG_TAG_DNS_LOG, "Glide, load failure from nextdns $subUrl") + Logger.i(LOG_TAG_DNS, "Glide, load failure from nextdns $subUrl") updateImage( url, constructFavUrlDuckDuckGo(url), @@ -120,12 +118,12 @@ class FavIconDownloader(val context: Context, private val url: String) : Runnabl .submit(SIZE_ORIGINAL, SIZE_ORIGINAL) try { futureTarget.get() - if (DEBUG) Log.d(LOG_TAG_DNS_LOG, "Glide, downloaded from duckduckgo $subUrl, $url") + Logger.d(LOG_TAG_DNS, "Glide, downloaded from duckduckgo $subUrl, $url") } catch (e: Exception) { // In case of failure the FutureTarget will throw an exception. // Will initiate the download of fav icon for the top level domain. if (retry) { - if (DEBUG) Log.d(LOG_TAG_DNS_LOG, "Glide, download failed from duckduckgo $subUrl") + Logger.d(LOG_TAG_DNS, "Glide, download failed from duckduckgo $subUrl") updateImage(fdqnUrl, url, "", false) } else { // add failed urls to a local cache, no need to attempt again and again @@ -133,7 +131,7 @@ class FavIconDownloader(val context: Context, private val url: String) : Runnabl // FIXME: add metadata instead of boolean failedFavIconUrls.put(fdqnUrl, true) } - Log.e(LOG_TAG_DNS_LOG, "Glide, no fav icon available for the url: $subUrl") + Logger.e(LOG_TAG_DNS, "Glide, no fav icon available for the url: $subUrl") } finally { Glide.with(context.applicationContext).clear(futureTarget) } diff --git a/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt b/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt index 62d492a11..de60353c2 100644 --- a/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt +++ b/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt @@ -16,10 +16,10 @@ */ package com.celzero.bravedns.net.go +import Logger.LOG_TAG_VPN import android.content.Context import android.content.res.Resources import android.os.ParcelFileDescriptor -import android.util.Log import android.widget.Toast import backend.Backend import com.celzero.bravedns.R @@ -46,7 +46,6 @@ import com.celzero.bravedns.util.Constants.Companion.RETHINK_BASE_URL_SKY import com.celzero.bravedns.util.Constants.Companion.UNSPECIFIED_IP_IPV4 import com.celzero.bravedns.util.Constants.Companion.UNSPECIFIED_IP_IPV6 import com.celzero.bravedns.util.InternetProtocol -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_VPN import com.celzero.bravedns.util.Utilities import com.celzero.bravedns.util.Utilities.blocklistDir import com.celzero.bravedns.util.Utilities.blocklistFile @@ -86,7 +85,7 @@ class GoVpnAdapter : KoinComponent { val defaultDns = newDefaultTransport(appConfig.getDefaultDns()) // no need to connect tunnel if already connected, just reset the tunnel with new // parameters - Log.i(LOG_TAG_VPN, "connect tunnel with new params") + Logger.i(LOG_TAG_VPN, "connect tunnel with new params") this.tunnel = Intra.connect( tunFd.fd.toLong(), @@ -100,7 +99,7 @@ class GoVpnAdapter : KoinComponent { suspend fun initResolverProxiesPcap(opts: TunnelOptions) { if (!tunnel.isConnected) { - Log.i(LOG_TAG_VPN, "Tunnel NOT connected, skip init resolver proxies") + Logger.i(LOG_TAG_VPN, "Tunnel NOT connected, skip init resolver proxies") return } @@ -121,10 +120,10 @@ class GoVpnAdapter : KoinComponent { suspend fun setPcapMode(pcapFilePath: String) { try { - Log.i(LOG_TAG_VPN, "set pcap mode: $pcapFilePath") + Logger.i(LOG_TAG_VPN, "set pcap mode: $pcapFilePath") tunnel.setPcap(pcapFilePath) } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "err setting pcap: ${e.message}", e) + Logger.e(LOG_TAG_VPN, "err setting pcap: ${e.message}", e) } } @@ -142,15 +141,15 @@ class GoVpnAdapter : KoinComponent { tunnelOptions.tunFirewallMode.mode, tunnelOptions.ptMode.id ) - Log.i(LOG_TAG_VPN, "set route: ${InternetProtocol.IPv46.value()}") + Logger.i(LOG_TAG_VPN, "set route: ${InternetProtocol.IPv46.value()}") } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "err setting route: ${e.message}", e) + Logger.e(LOG_TAG_VPN, "err setting route: ${e.message}", e) } } suspend fun addTransport() { if (!tunnel.isConnected) { - Log.i(LOG_TAG_VPN, "Tunnel NOT connected, skip add transport") + Logger.i(LOG_TAG_VPN, "Tunnel NOT connected, skip add transport") return } @@ -185,18 +184,18 @@ class GoVpnAdapter : KoinComponent { val blockfreeUrl = appConfig.getBlockFreeRethinkEndpoint() if (blockfreeUrl.isNotEmpty()) { - Log.i(LOG_TAG_VPN, "adding blockfree url: $blockfreeUrl") + Logger.i(LOG_TAG_VPN, "adding blockfree url: $blockfreeUrl") addRdnsTransport(Backend.BlockFree, blockfreeUrl) } else { - Log.i(LOG_TAG_VPN, "no blockfree url found") + Logger.i(LOG_TAG_VPN, "no blockfree url found") // if blockfree url is not available, do not proceed further return } if (!rdnsRemoteUrl.isNullOrEmpty()) { - Log.i(LOG_TAG_VPN, "adding rdns remote url: $rdnsRemoteUrl") + Logger.i(LOG_TAG_VPN, "adding rdns remote url: $rdnsRemoteUrl") addRdnsTransport(Backend.Preferred, rdnsRemoteUrl) } else { - Log.i(LOG_TAG_VPN, "no rdns remote url found") + Logger.i(LOG_TAG_VPN, "no rdns remote url found") } } } @@ -209,16 +208,16 @@ class GoVpnAdapter : KoinComponent { url = doh?.dohURL // change the url from https to http if the isSecure is false if (doh?.isSecure == false) { - if (DEBUG) Log.d(LOG_TAG_VPN, "changing url from https to http for $url") + Logger.d(LOG_TAG_VPN, "changing url from https to http for $url") url = url?.replace("https", "http") } val ips: String = getIpString(context, url) // add replaces the existing transport with the same id if successful // so no need to remove the transport before adding Intra.addDoHTransport(tunnel, id, url, ips) - Log.i(LOG_TAG_VPN, "new doh: $id (${doh?.dohName}), url: $url, ips: $ips") + Logger.i(LOG_TAG_VPN, "new doh: $id (${doh?.dohName}), url: $url, ips: $ips") } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "connect-tunnel: doh failure", e) + Logger.e(LOG_TAG_VPN, "connect-tunnel: doh failure", e) getResolver()?.remove(id) showDnsFailureToast(url ?: "") } @@ -230,7 +229,7 @@ class GoVpnAdapter : KoinComponent { val dot = appConfig.getDOTDetails() url = dot?.url if (dot?.isSecure == true && url?.startsWith("tls") == false) { - if (DEBUG) Log.d(LOG_TAG_VPN, "adding tls to url for $url") + Logger.d(LOG_TAG_VPN, "adding tls to url for $url") // add tls to the url if isSecure is true and the url does not start with tls url = "tls://$url" } @@ -238,9 +237,9 @@ class GoVpnAdapter : KoinComponent { // add replaces the existing transport with the same id if successful // so no need to remove the transport before adding Intra.addDoTTransport(tunnel, id, url, ips) - Log.i(LOG_TAG_VPN, "new dot: $id (${dot?.name}), url: $url, ips: $ips") + Logger.i(LOG_TAG_VPN, "new dot: $id (${dot?.name}), url: $url, ips: $ips") } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "connect-tunnel: dot failure", e) + Logger.e(LOG_TAG_VPN, "connect-tunnel: dot failure", e) getResolver()?.remove(id) showDnsFailureToast(url ?: "") } @@ -256,9 +255,9 @@ class GoVpnAdapter : KoinComponent { // add replaces the existing transport with the same id if successful // so no need to remove the transport before adding Intra.addODoHTransport(tunnel, id, proxy, resolver, proxyIps) - Log.i(LOG_TAG_VPN, "new odoh: $id (${odoh?.name}), p: $proxy, r: $resolver") + Logger.i(LOG_TAG_VPN, "new odoh: $id (${odoh?.name}), p: $proxy, r: $resolver") } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "connect-tunnel: odoh failure", e) + Logger.e(LOG_TAG_VPN, "connect-tunnel: odoh failure", e) getResolver()?.remove(id) showDnsFailureToast(resolver ?: "") } @@ -271,11 +270,10 @@ class GoVpnAdapter : KoinComponent { // add replaces the existing transport with the same id if successful // so no need to remove the transport before adding Intra.addDNSCryptTransport(tunnel, id, url) - Log.i(LOG_TAG_VPN, "new dnscrypt: $id (${dc.dnsCryptName}), url: $url") - // setDnscryptRelaysIfAny() is expected to catch exceptions - setDnscryptRelaysIfAny() + Logger.i(LOG_TAG_VPN, "new dnscrypt: $id (${dc.dnsCryptName}), url: $url") + setDnscryptRelaysIfAny() // is expected to catch exceptions } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "connect-tunnel: dns crypt failure for $id", e) + Logger.e(LOG_TAG_VPN, "connect-tunnel: dns crypt failure for $id", e) getResolver()?.remove(id) removeDnscryptRelaysIfAny() showDnscryptConnectionFailureToast() @@ -288,12 +286,12 @@ class GoVpnAdapter : KoinComponent { // add replaces the existing transport with the same id if successful // so no need to remove the transport before adding Intra.addDNSProxy(tunnel, id, dnsProxy.proxyIP, dnsProxy.proxyPort.toString()) - Log.i( + Logger.i( LOG_TAG_VPN, "new dns proxy: $id(${dnsProxy.proxyName}), ip: ${dnsProxy.proxyIP}, port: ${dnsProxy.proxyPort}" ) } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "connect-tunnel: dns proxy failure", e) + Logger.e(LOG_TAG_VPN, "connect-tunnel: dns proxy failure", e) getResolver()?.remove(id) showDnsProxyConnectionFailureToast() } @@ -306,13 +304,13 @@ class GoVpnAdapter : KoinComponent { val convertedUrl = getRdnsUrl(url) ?: return if (url.contains(RETHINK_BASE_URL_SKY) || !useDot) { Intra.addDoHTransport(tunnel, id, convertedUrl, ips) - Log.i(LOG_TAG_VPN, "new doh (rdns): $id, url: $convertedUrl, ips: $ips") + Logger.i(LOG_TAG_VPN, "new doh (rdns): $id, url: $convertedUrl, ips: $ips") } else { Intra.addDoTTransport(tunnel, id, convertedUrl, ips) - Log.i(LOG_TAG_VPN, "new dot (rdns): $id, url: $convertedUrl, ips: $ips") + Logger.i(LOG_TAG_VPN, "new dot (rdns): $id, url: $convertedUrl, ips: $ips") } } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "connect-tunnel: rdns creation failure", e) + Logger.e(LOG_TAG_VPN, "connect-tunnel: rdns creation failure", e) getResolver()?.remove(id) showDnsFailureToast(url) } @@ -376,7 +374,7 @@ class GoVpnAdapter : KoinComponent { val flags = r?.stampToFlags(stamp) b32Stamp = r?.flagsToStamp(flags, Backend.EB32) } catch (e: Exception) { - Log.w(LOG_TAG_VPN, "err get base32 stamp: ${e.message}") + Logger.w(LOG_TAG_VPN, "err get base32 stamp: ${e.message}") } return b32Stamp ?: stamp } @@ -391,7 +389,7 @@ class GoVpnAdapter : KoinComponent { suspend fun setTunMode(tunnelOptions: TunnelOptions) { if (!tunnel.isConnected) { - Log.i(LOG_TAG_VPN, "Tunnel NOT connected, skip set-tun-mode") + Logger.i(LOG_TAG_VPN, "Tunnel NOT connected, skip set-tun-mode") return } try { @@ -401,13 +399,13 @@ class GoVpnAdapter : KoinComponent { tunnelOptions.ptMode.id ) } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "err set tun mode: ${e.message}", e) + Logger.e(LOG_TAG_VPN, "err set tun mode: ${e.message}", e) } } suspend fun setRDNS() { // Set brave dns to tunnel - Local/Remote - if (DEBUG) Log.d(LOG_TAG_VPN, "set brave dns to tunnel (local/remote)") + Logger.d(LOG_TAG_VPN, "set brave dns to tunnel (local/remote)") // enable local blocklist if enabled if (persistentState.blocklistEnabled) { @@ -422,7 +420,7 @@ class GoVpnAdapter : KoinComponent { } private fun setRDNSRemote() { - if (DEBUG) Log.d(LOG_TAG_VPN, "init remote rdns mode") + Logger.d(LOG_TAG_VPN, "init remote rdns mode") try { val remoteDir = blocklistDir( @@ -434,12 +432,12 @@ class GoVpnAdapter : KoinComponent { blocklistFile(remoteDir.absolutePath, ONDEVICE_BLOCKLIST_FILE_TAG) ?: return if (remoteFile.exists()) { getRDNSResolver()?.setRdnsRemote(remoteFile.absolutePath) - Log.i(LOG_TAG_VPN, "remote-rdns enabled") + Logger.i(LOG_TAG_VPN, "remote-rdns enabled") } else { - Log.w(LOG_TAG_VPN, "filetag.json for remote-rdns missing") + Logger.w(LOG_TAG_VPN, "filetag.json for remote-rdns missing") } } catch (ex: Exception) { - Log.e(LOG_TAG_VPN, "cannot set remote-rdns: ${ex.message}", ex) + Logger.e(LOG_TAG_VPN, "cannot set remote-rdns: ${ex.message}", ex) } } @@ -448,11 +446,11 @@ class GoVpnAdapter : KoinComponent { routes.split(",").forEach { if (it.isBlank()) return@forEach - Log.i(LOG_TAG_VPN, "new dnscrypt relay: $it") + Logger.i(LOG_TAG_VPN, "new dnscrypt relay: $it") try { Intra.addDNSCryptRelay(tunnel, it) // entire url is the id } catch (ex: Exception) { - Log.e(LOG_TAG_VPN, "connect-tunnel: dnscrypt failure", ex) + Logger.e(LOG_TAG_VPN, "connect-tunnel: dnscrypt failure", ex) appConfig.removeDnscryptRelay(it) getResolver()?.remove(it) } @@ -464,27 +462,27 @@ class GoVpnAdapter : KoinComponent { routes.split(",").forEach { if (it.isBlank()) return@forEach - Log.i(LOG_TAG_VPN, "remove dnscrypt relay: $it") + Logger.i(LOG_TAG_VPN, "remove dnscrypt relay: $it") try { // remove from appConfig, as this is not from ui, but from the tunnel start up appConfig.removeDnscryptRelay(it) getResolver()?.remove(it) } catch (ex: Exception) { - Log.e(LOG_TAG_VPN, "connect-tunnel: dnscrypt rmv failure", ex) + Logger.e(LOG_TAG_VPN, "connect-tunnel: dnscrypt rmv failure", ex) } } } suspend fun addDnscryptRelay(relay: DnsCryptRelayEndpoint) { if (!tunnel.isConnected) { - Log.i(LOG_TAG_VPN, "Tunnel NOT connected, skip add dnscrypt relay") + Logger.i(LOG_TAG_VPN, "Tunnel NOT connected, skip add dnscrypt relay") return } try { Intra.addDNSCryptRelay(tunnel, relay.dnsCryptRelayURL) - Log.i(LOG_TAG_VPN, "new dnscrypt relay: ${relay.dnsCryptRelayURL}") + Logger.i(LOG_TAG_VPN, "new dnscrypt relay: ${relay.dnsCryptRelayURL}") } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "connect-tunnel: dnscrypt add failure", e) + Logger.e(LOG_TAG_VPN, "connect-tunnel: dnscrypt add failure", e) appConfig.removeDnscryptRelay(relay.dnsCryptRelayURL) getResolver()?.remove(relay.dnsCryptRelayURL) } @@ -492,15 +490,15 @@ class GoVpnAdapter : KoinComponent { suspend fun removeDnscryptRelay(relay: DnsCryptRelayEndpoint) { if (!tunnel.isConnected) { - Log.i(LOG_TAG_VPN, "Tunnel NOT connected, skip remove dnscrypt relay") + Logger.i(LOG_TAG_VPN, "Tunnel NOT connected, skip remove dnscrypt relay") return } try { // no need to remove from appConfig, as it is already removed getResolver()?.remove(relay.dnsCryptRelayURL) - Log.i(LOG_TAG_VPN, "remove dnscrypt relay: ${relay.dnsCryptRelayURL}") + Logger.i(LOG_TAG_VPN, "remove dnscrypt relay: ${relay.dnsCryptRelayURL}") } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "connect-tunnel: dnscrypt rmv failure", e) + Logger.e(LOG_TAG_VPN, "connect-tunnel: dnscrypt rmv failure", e) } } @@ -524,9 +522,9 @@ class GoVpnAdapter : KoinComponent { ProxyManager.ID_S5_BASE } val result = getProxies()?.addProxy(id, url) - Log.i(LOG_TAG_VPN, "Proxy mode set with tunnel url($id): $url, result: $result") + Logger.i(LOG_TAG_VPN, "Proxy mode set with tunnel url($id): $url, result: $result") } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "connect-tunnel: err start proxy $userName@$ipAddress:$port", e) + Logger.e(LOG_TAG_VPN, "connect-tunnel: err start proxy $userName@$ipAddress:$port", e) } } @@ -595,7 +593,7 @@ class GoVpnAdapter : KoinComponent { val wgConfigs: List = WireguardManager.getEnabledConfigs() if (wgConfigs.isEmpty()) { - Log.i(LOG_TAG_VPN, "no active wireguard configs found") + Logger.i(LOG_TAG_VPN, "no active wireguard configs found") return } wgConfigs.forEach { @@ -608,12 +606,12 @@ class GoVpnAdapter : KoinComponent { try { val p = getProxies()?.getProxy(id) if (p == null) { - Log.w(LOG_TAG_VPN, "wireguard proxy not found for id: $id") + Logger.w(LOG_TAG_VPN, "wireguard proxy not found for id: $id") return } Intra.addProxyDNS(tunnel, p) // dns transport has same id as the proxy (p) } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "wireguard dns failure", e) + Logger.e(LOG_TAG_VPN, "wireguard dns failure", e) getResolver()?.remove(id) showDnsFailureToast(id) } @@ -635,7 +633,7 @@ class GoVpnAdapter : KoinComponent { appConfig.getSocks5ProxyDetails() } if (socks5 == null) { - Log.w(LOG_TAG_VPN, "could not fetch socks5 details for proxyMode: $tunProxyMode") + Logger.w(LOG_TAG_VPN, "could not fetch socks5 details for proxyMode: $tunProxyMode") return } setSocks5Proxy( @@ -645,16 +643,16 @@ class GoVpnAdapter : KoinComponent { socks5.proxyIP, socks5.proxyPort ) - Log.i(LOG_TAG_VPN, "Socks5 mode set: " + socks5.proxyIP + "," + socks5.proxyPort) + Logger.i(LOG_TAG_VPN, "Socks5 mode set: " + socks5.proxyIP + "," + socks5.proxyPort) } fun getProxyStatusById(id: String): Long? { return try { val status = getProxyById(id)?.status() - if (DEBUG) Log.d(LOG_TAG_VPN, "proxy status($id): $status") + Logger.d(LOG_TAG_VPN, "proxy status($id): $status") status } catch (ignored: Exception) { - Log.i(LOG_TAG_VPN, "err getProxy($id) ignored: ${ignored.message}") + Logger.i(LOG_TAG_VPN, "err getProxy($id) ignored: ${ignored.message}") null } } @@ -663,7 +661,7 @@ class GoVpnAdapter : KoinComponent { return try { getProxies()?.getProxy(id) } catch (ignored: Exception) { - Log.i(LOG_TAG_VPN, "err getProxy($id) ignored: ${ignored.message}") + Logger.i(LOG_TAG_VPN, "err getProxy($id) ignored: ${ignored.message}") null } } @@ -683,7 +681,7 @@ class GoVpnAdapter : KoinComponent { } val httpProxyUrl = endpoint.proxyIP ?: return - Log.i(LOG_TAG_VPN, "Http mode set with url: $httpProxyUrl") + Logger.i(LOG_TAG_VPN, "Http mode set with url: $httpProxyUrl") getProxies()?.addProxy(id, httpProxyUrl) } catch (e: Exception) { if (tunProxyMode.isTunProxyOrbot()) { @@ -691,13 +689,13 @@ class GoVpnAdapter : KoinComponent { } else { appConfig.removeProxy(AppConfig.ProxyType.HTTP, AppConfig.ProxyProvider.CUSTOM) } - Log.e(LOG_TAG_VPN, "error setting http proxy: ${e.message}", e) + Logger.e(LOG_TAG_VPN, "error setting http proxy: ${e.message}", e) } } fun removeWgProxy(id: Int) { if (!tunnel.isConnected) { - Log.i(LOG_TAG_VPN, "Tunnel NOT connected, skip refreshing wg") + Logger.i(LOG_TAG_VPN, "Tunnel NOT connected, skip refreshing wg") return } try { @@ -708,21 +706,21 @@ class GoVpnAdapter : KoinComponent { if (isDnsNeeded) { getResolver()?.remove(id0) } - Log.i(LOG_TAG_VPN, "remove wireguard proxy with id: $id") + Logger.i(LOG_TAG_VPN, "remove wireguard proxy with id: $id") } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "error removing wireguard proxy: ${e.message}", e) + Logger.e(LOG_TAG_VPN, "error removing wireguard proxy: ${e.message}", e) } } suspend fun addWgProxy(id: String) { if (!tunnel.isConnected) { - Log.i(LOG_TAG_VPN, "Tunnel NOT connected, skip add wg") + Logger.i(LOG_TAG_VPN, "Tunnel NOT connected, skip add wg") return } try { val proxyId: Int? = id.substring(ID_WG_BASE.length).toIntOrNull() if (proxyId == null) { - Log.e(LOG_TAG_VPN, "invalid wireguard proxy id: $id") + Logger.e(LOG_TAG_VPN, "invalid wireguard proxy id: $id") return } @@ -731,9 +729,9 @@ class GoVpnAdapter : KoinComponent { val wgUserSpaceString = wgConfig?.toWgUserspaceString() getProxies()?.addProxy(id, wgUserSpaceString) if (withDNS) setWireGuardDns(id) - Log.i(LOG_TAG_VPN, "add wireguard proxy with $id; dns? $withDNS") + Logger.i(LOG_TAG_VPN, "add wireguard proxy with $id; dns? $withDNS") } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "error adding wireguard proxy: ${e.message}", e) + Logger.e(LOG_TAG_VPN, "error adding wireguard proxy: ${e.message}", e) // do not auto remove failed wg proxy, let the user decide via UI // WireguardManager.disableConfig(id) showWireguardFailureToast( @@ -744,48 +742,48 @@ class GoVpnAdapter : KoinComponent { fun closeConnections(connIds: List) { if (!tunnel.isConnected) { - Log.i(LOG_TAG_VPN, "Tunnel not connected, skip disconnecting connection") + Logger.i(LOG_TAG_VPN, "Tunnel not connected, skip disconnecting connection") return } val connIdsStr = connIds.joinToString(",") val res = tunnel.closeConns(connIdsStr) - Log.i(LOG_TAG_VPN, "close connection: $connIds, res: $res") + Logger.i(LOG_TAG_VPN, "close connection: $connIds, res: $res") } fun refreshProxies() { if (!tunnel.isConnected) { - Log.i(LOG_TAG_VPN, "Tunnel NOT connected, skip refreshing proxies") + Logger.i(LOG_TAG_VPN, "Tunnel NOT connected, skip refreshing proxies") return } try { val res = getProxies()?.refreshProxies() - Log.i(LOG_TAG_VPN, "refresh proxies: $res") + Logger.i(LOG_TAG_VPN, "refresh proxies: $res") } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "error refreshing proxies: ${e.message}", e) + Logger.e(LOG_TAG_VPN, "error refreshing proxies: ${e.message}", e) } } fun refreshProxy(id: String) { if (!tunnel.isConnected) { - Log.i(LOG_TAG_VPN, "Tunnel NOT connected, skip refreshing proxy") + Logger.i(LOG_TAG_VPN, "Tunnel NOT connected, skip refreshing proxy") return } try { val res = getProxies()?.getProxy(id)?.refresh() - Log.i(LOG_TAG_VPN, "refresh proxy($id): $res") + Logger.i(LOG_TAG_VPN, "refresh proxy($id): $res") } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "error refreshing proxy($id): ${e.message}", e) + Logger.e(LOG_TAG_VPN, "error refreshing proxy($id): ${e.message}", e) } } fun getProxyStats(id: String): backend.Stats? { return try { val stats = getProxies()?.getProxy(id)?.router()?.stat() - Log.i(LOG_TAG_VPN, "proxy stats($id): $stats") + Logger.i(LOG_TAG_VPN, "proxy stats($id): $stats") stats } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "error getting proxy stats($id): ${e.message}", e) + Logger.e(LOG_TAG_VPN, "error getting proxy stats($id): ${e.message}", e) null } } @@ -803,7 +801,7 @@ class GoVpnAdapter : KoinComponent { } return status } catch (e: Exception) { - Log.w(LOG_TAG_VPN, "err dns status($id): ${e.message}") + Logger.w(LOG_TAG_VPN, "err dns status($id): ${e.message}") } return null } @@ -816,7 +814,7 @@ class GoVpnAdapter : KoinComponent { getRDNSResolver()?.rdnsRemote } } catch (e: Exception) { - Log.w(LOG_TAG_VPN, "err getRDNS($type): ${e.message}", e) + Logger.w(LOG_TAG_VPN, "err getRDNS($type): ${e.message}", e) } return null } @@ -824,32 +822,31 @@ class GoVpnAdapter : KoinComponent { // v055, unused suspend fun setTcpProxy() { if (!appConfig.isTcpProxyEnabled()) { - Log.i(LOG_TAG_VPN, "tcp proxy not enabled") + Logger.i(LOG_TAG_VPN, "tcp proxy not enabled") return } val u = TcpProxyHelper.getActiveTcpProxy() if (u == null) { - Log.w(LOG_TAG_VPN, "could not fetch tcp proxy details") + Logger.w(LOG_TAG_VPN, "could not fetch tcp proxy details") return } val ips = getIpString(context, "https://sky.rethinkdns.com/") - Log.d(LOG_TAG_VPN, "ips: $ips") + Logger.d(LOG_TAG_VPN, "ips: $ips") // svc.rethinkdns.com / duplex.deno.dev val testpipwsurl = "pipws://proxy.nile.workers.dev/ws/nosig" val ok = getProxies()?.addProxy(ProxyManager.ID_TCP_BASE, testpipwsurl) - if (DEBUG) Log.d(LOG_TAG_VPN, "tcp-mode(${ProxyManager.ID_TCP_BASE}): ${u.url}, ok? $ok") + Logger.d(LOG_TAG_VPN, "tcp-mode(${ProxyManager.ID_TCP_BASE}): ${u.url}, ok? $ok") val secWarp = WireguardManager.getSecWarpConfig() if (secWarp == null) { - Log.w(LOG_TAG_VPN, "no sec warp config found") + Logger.w(LOG_TAG_VPN, "no sec warp config found") return } val wgUserSpaceString = secWarp.toWgUserspaceString() val ok2 = getProxies()?.addProxy(ID_WG_BASE + secWarp.getId(), wgUserSpaceString) - if (DEBUG) - Log.d( + Logger.d( LOG_TAG_VPN, "tcp-mode(wg) set(${ID_WG_BASE+ secWarp.getId()}): ${secWarp.getName()}, res: $ok2" ) @@ -865,10 +862,10 @@ class GoVpnAdapter : KoinComponent { fun closeTun() { if (tunnel.isConnected) { - Log.i(LOG_TAG_VPN, "Tunnel disconnect") + Logger.i(LOG_TAG_VPN, "Tunnel disconnect") tunnel.disconnect() } else { - Log.i(LOG_TAG_VPN, "Tunnel already disconnected") + Logger.i(LOG_TAG_VPN, "Tunnel already disconnected") } } @@ -877,18 +874,18 @@ class GoVpnAdapter : KoinComponent { try { // when the url is empty, set the default transport to 8.8.4.4:53 if (url.isEmpty()) { - Log.i(LOG_TAG_VPN, "set default transport to $defaultDns, as url is empty") + Logger.i(LOG_TAG_VPN, "set default transport to $defaultDns, as url is empty") return Intra.newDefaultDNS(Backend.DNS53, defaultDns, "") } val ips: String = getIpString(context, url) - if (DEBUG) Log.d(LOG_TAG_VPN, "default transport url: $url ips: $ips") + Logger.d(LOG_TAG_VPN, "default transport url: $url ips: $ips") if (url.contains("http")) { return Intra.newDefaultDNS(Backend.DOH, url, ips) } // no need to set ips for dns53 return Intra.newDefaultDNS(Backend.DNS53, url, "") } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "err new default transport: ${e.message}", e) + Logger.e(LOG_TAG_VPN, "err new default transport: ${e.message}", e) // most of the android devices have google dns, so add it as default transport // TODO: notify the user that the default transport could not be set return Intra.newDefaultDNS(Backend.DNS53, defaultDns, "") @@ -899,27 +896,27 @@ class GoVpnAdapter : KoinComponent { val defaultDns = FALLBACK_DNS try { if (!tunnel.isConnected) { - Log.i(LOG_TAG_VPN, "Tunnel not connected, skip new default transport") + Logger.i(LOG_TAG_VPN, "Tunnel not connected, skip new default transport") return } // when the url is empty, set the default transport to DEFAULT_DNS_IP // default transport is always sent to Ipn.Exit in the go code and so dns // request sent to the default transport will not be looped back into the tunnel if (url.isNullOrEmpty()) { - Log.i(LOG_TAG_VPN, "url empty, set default trans to $defaultDns") + Logger.i(LOG_TAG_VPN, "url empty, set default trans to $defaultDns") Intra.addDefaultTransport(tunnel, Backend.DNS53, defaultDns, "") return } val ips: String = getIpString(context, url) - if (DEBUG) Log.d(LOG_TAG_VPN, "default transport url: $url ips: $ips") + Logger.d(LOG_TAG_VPN, "default transport url: $url ips: $ips") if (url.contains("http")) { Intra.addDefaultTransport(tunnel, Backend.DOH, url, ips) } else { Intra.addDefaultTransport(tunnel, Backend.DNS53, url, "") } } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "err new default transport: ${e.message}", e) + Logger.e(LOG_TAG_VPN, "err new default transport: ${e.message}", e) // most of the android devices have google dns, so add it as default transport // TODO: notify the user that the default transport could not be set Intra.addDefaultTransport(tunnel, Backend.DNS53, defaultDns, "") @@ -928,7 +925,7 @@ class GoVpnAdapter : KoinComponent { suspend fun setSystemDns(systemDns: List) { if (!tunnel.isConnected) { - Log.i(LOG_TAG_VPN, "Tunnel NOT connected, skip setting system-dns") + Logger.i(LOG_TAG_VPN, "Tunnel NOT connected, skip setting system-dns") } // for Rethink within rethink mode, the system dns is system dns is always set to Ipn.Base // in go and so dns request sent to the system dns will be looped back into the tunnel @@ -939,11 +936,11 @@ class GoVpnAdapter : KoinComponent { // below code is commented out, add the code to set the system dns via resolver // val transport = Intra.newDNSProxy("ID", dnsProxy.host, dnsProxy.port.toString()) // tunnel?.resolver?.addSystemDNS(transport) - Log.i(LOG_TAG_VPN, "set system dns: $sysDnsStr") + Logger.i(LOG_TAG_VPN, "set system dns: $sysDnsStr") // no need to send the dnsProxy.port for the below method, as it is not expecting port Intra.setSystemDNS(tunnel, sysDnsStr) } catch (e: Exception) { // this is not expected to happen - Log.e(LOG_TAG_VPN, "set system dns: could not parse system dns", e) + Logger.e(LOG_TAG_VPN, "set system dns: could not parse system dns", e) // remove the system dns, if it could not be set tunnel.resolver.remove(Backend.System) } @@ -955,15 +952,15 @@ class GoVpnAdapter : KoinComponent { proto: Long ): Boolean { if (!tunnel.isConnected) { - Log.e(LOG_TAG_VPN, "updateLink: tunFd is null, returning") + Logger.e(LOG_TAG_VPN, "updateLink: tunFd is null, returning") return false } - Log.i(LOG_TAG_VPN, "updateLink with fd(${tunFd.fd}) mtu: ${opts.mtu}") + Logger.i(LOG_TAG_VPN, "updateLink with fd(${tunFd.fd}) mtu: ${opts.mtu}") return try { tunnel.setLinkAndRoutes(tunFd.fd.toLong(), opts.mtu.toLong(), proto) true } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "err update tun: ${e.message}", e) + Logger.e(LOG_TAG_VPN, "err update tun: ${e.message}", e) false } } @@ -977,11 +974,11 @@ class GoVpnAdapter : KoinComponent { // changes made in connectTunnel() if (!tunnel.isConnected) { // Adapter is closed. - Log.e(LOG_TAG_VPN, "updateTun: tunnel is not connected, returning") + Logger.e(LOG_TAG_VPN, "updateTun: tunnel is not connected, returning") return false } - Log.i(LOG_TAG_VPN, "received update tun with opts: $tunnelOptions") + Logger.i(LOG_TAG_VPN, "received update tun with opts: $tunnelOptions") // ok to init again, as updateTun is called to handle edge cases initResolverProxiesPcap(tunnelOptions) return tunnel.isConnected @@ -991,12 +988,12 @@ class GoVpnAdapter : KoinComponent { // set translate to false for dns mode (regardless of setting in dns screen), // since apps cannot understand alg ips if (appConfig.getBraveMode().isDnsMode()) { - Log.i(LOG_TAG_VPN, "dns mode, set translate to false") + Logger.i(LOG_TAG_VPN, "dns mode, set translate to false") getRDNSResolver()?.translate(false) return } - Log.i(LOG_TAG_VPN, "set dns alg: ${persistentState.enableDnsAlg}") + Logger.i(LOG_TAG_VPN, "set dns alg: ${persistentState.enableDnsAlg}") getRDNSResolver()?.translate(persistentState.enableDnsAlg) } @@ -1004,13 +1001,13 @@ class GoVpnAdapter : KoinComponent { try { val rl = getRDNS(RethinkBlocklistManager.RethinkBlocklistType.LOCAL) if (rl != null) { - Log.i(LOG_TAG_VPN, "set local stamp: ${persistentState.localBlocklistStamp}") + Logger.i(LOG_TAG_VPN, "set local stamp: ${persistentState.localBlocklistStamp}") rl.stamp = persistentState.localBlocklistStamp } else { - Log.w(LOG_TAG_VPN, "mode is not local, this should not happen") + Logger.w(LOG_TAG_VPN, "mode is not local, this should not happen") } } catch (e: java.lang.Exception) { - Log.e(LOG_TAG_VPN, "could not set local stamp: ${e.message}", e) + Logger.e(LOG_TAG_VPN, "could not set local stamp: ${e.message}", e) } finally { resetLocalBlocklistStampFromTunnel() } @@ -1020,16 +1017,16 @@ class GoVpnAdapter : KoinComponent { try { val rl = getRDNS(RethinkBlocklistManager.RethinkBlocklistType.LOCAL) if (rl == null) { - Log.i(LOG_TAG_VPN, "mode is not local, no need to reset local stamp") + Logger.i(LOG_TAG_VPN, "mode is not local, no need to reset local stamp") return } persistentState.localBlocklistStamp = rl.stamp // throws exception if stamp is invalid if (DEBUG) - Log.d(LOG_TAG_VPN, "reset local stamp: ${persistentState.localBlocklistStamp}") + Logger.d(LOG_TAG_VPN, "reset local stamp: ${persistentState.localBlocklistStamp}") } catch (e: Exception) { persistentState.localBlocklistStamp = "" - Log.e(LOG_TAG_VPN, "could not reset local stamp: ${e.message}", e) + Logger.e(LOG_TAG_VPN, "could not reset local stamp: ${e.message}", e) } } @@ -1037,7 +1034,7 @@ class GoVpnAdapter : KoinComponent { try { val stamp: String = persistentState.localBlocklistStamp val rdns = getRDNSResolver() - Log.i(LOG_TAG_VPN, "local blocklist stamp: $stamp, rdns? ${rdns != null}") + Logger.i(LOG_TAG_VPN, "local blocklist stamp: $stamp, rdns? ${rdns != null}") val path: String = Utilities.blocklistDownloadBasePath( @@ -1052,7 +1049,7 @@ class GoVpnAdapter : KoinComponent { path + ONDEVICE_BLOCKLIST_FILE_TAG ) rdns?.rdnsLocal?.stamp = stamp - Log.i(LOG_TAG_VPN, "local brave dns object is set with stamp: $stamp") + Logger.i(LOG_TAG_VPN, "local brave dns object is set with stamp: $stamp") } catch (ex: Exception) { // Set local blocklist enabled to false and reset the timestamp // if there is a failure creating bravedns @@ -1060,7 +1057,7 @@ class GoVpnAdapter : KoinComponent { // Set local blocklist enabled to false and reset the timestamp to make sure // user is prompted to download blocklists again on the next try persistentState.localBlocklistTimestamp = Constants.INIT_TIME_MS - Log.e(LOG_TAG_VPN, "could not set local-brave dns: ${ex.message}", ex) + Logger.e(LOG_TAG_VPN, "could not set local-brave dns: ${ex.message}", ex) } } @@ -1098,19 +1095,19 @@ class GoVpnAdapter : KoinComponent { val p50 = transport?.p50() ?: return persistentState.setMedianLatency(p50) } catch (e: Exception) { - Log.w(LOG_TAG_VPN, "err getP50($tid): ${e.message}") + Logger.w(LOG_TAG_VPN, "err getP50($tid): ${e.message}") } } private fun getResolver(): backend.DNSResolver? { try { if (!tunnel.isConnected) { - Log.i(LOG_TAG_VPN, "Tunnel NOT connected, skip get resolver") + Logger.i(LOG_TAG_VPN, "Tunnel NOT connected, skip get resolver") return null } return tunnel.resolver } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "err get resolver: ${e.message}", e) + Logger.e(LOG_TAG_VPN, "err get resolver: ${e.message}", e) } return null } @@ -1118,12 +1115,12 @@ class GoVpnAdapter : KoinComponent { private fun getRDNSResolver(): backend.DNSResolver? { try { if (!tunnel.isConnected) { - Log.w(LOG_TAG_VPN, "Tunnel NOT connected, skip get resolver") + Logger.w(LOG_TAG_VPN, "Tunnel NOT connected, skip get resolver") return null } return tunnel.resolver } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "err get resolver: ${e.message}", e) + Logger.e(LOG_TAG_VPN, "err get resolver: ${e.message}", e) } return null } @@ -1131,12 +1128,12 @@ class GoVpnAdapter : KoinComponent { private fun getProxies(): backend.Proxies? { try { if (!tunnel.isConnected) { - Log.w(LOG_TAG_VPN, "Tunnel NOT connected, skip get proxies") + Logger.w(LOG_TAG_VPN, "Tunnel NOT connected, skip get proxies") return null } return tunnel.proxies } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "err get proxies: ${e.message}", e) + Logger.e(LOG_TAG_VPN, "err get proxies: ${e.message}", e) } return null } @@ -1145,10 +1142,10 @@ class GoVpnAdapter : KoinComponent { return try { val router = tunnel.proxies.getProxy(wgId).router() val res = router.contains(ip) - Log.i(LOG_TAG_VPN, "canRouteIp($wgId, $ip), res? $res") + Logger.i(LOG_TAG_VPN, "canRouteIp($wgId, $ip), res? $res") res } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "err canRouteIp($wgId, $ip): ${e.message}", e) + Logger.e(LOG_TAG_VPN, "err canRouteIp($wgId, $ip): ${e.message}", e) default } } @@ -1158,10 +1155,10 @@ class GoVpnAdapter : KoinComponent { val router = tunnel.proxies.getProxy(proxyId).router() val has4 = router.iP4() val has6 = router.iP6() - Log.i(LOG_TAG_VPN, "supported ip version($proxyId): has4? $has4, has6? $has6") + Logger.i(LOG_TAG_VPN, "supported ip version($proxyId): has4? $has4, has6? $has6") return Pair(has4, has6) } catch (e: Exception) { - Log.w(LOG_TAG_VPN, "err supported ip version($proxyId): ${e.message}") + Logger.w(LOG_TAG_VPN, "err supported ip version($proxyId): ${e.message}") } return Pair(false, false) } @@ -1183,13 +1180,13 @@ class GoVpnAdapter : KoinComponent { false } - Log.i( + Logger.i( LOG_TAG_VPN, "split tunnel proxy($proxyId): ipv4? ${pair.first}, ipv6? ${pair.second}, res? $res" ) res } catch (e: Exception) { - Log.w(LOG_TAG_VPN, "err isSplitTunnelProxy($proxyId): ${e.message}") + Logger.w(LOG_TAG_VPN, "err isSplitTunnelProxy($proxyId): ${e.message}") false } } @@ -1201,10 +1198,10 @@ class GoVpnAdapter : KoinComponent { val has6 = router.iP6() val failOpen = !router.iP4() && !router.iP6() val mtu = router.mtu().toInt() - Log.i(LOG_TAG_VPN, "proxy ip version, has4? $has4, has6? $has6, failOpen? $failOpen") + Logger.i(LOG_TAG_VPN, "proxy ip version, has4? $has4, has6? $has6, failOpen? $failOpen") return BraveVPNService.OverlayNetworks(has4, has6, failOpen, mtu) } catch (e: Exception) { - Log.w(LOG_TAG_VPN, "err proxy ip version: ${e.message}") + Logger.w(LOG_TAG_VPN, "err proxy ip version: ${e.message}") } return BraveVPNService.OverlayNetworks() } diff --git a/app/src/main/java/com/celzero/bravedns/net/manager/ConnectionTracer.kt b/app/src/main/java/com/celzero/bravedns/net/manager/ConnectionTracer.kt index f79272556..0559a491b 100644 --- a/app/src/main/java/com/celzero/bravedns/net/manager/ConnectionTracer.kt +++ b/app/src/main/java/com/celzero/bravedns/net/manager/ConnectionTracer.kt @@ -1,14 +1,12 @@ package com.celzero.bravedns.net.manager +import Logger.LOG_TAG_VPN import android.annotation.TargetApi import android.content.Context import android.net.ConnectivityManager import android.os.Build import android.text.TextUtils -import android.util.Log -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.util.Constants -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_VPN import com.celzero.bravedns.util.Protocol import com.celzero.bravedns.util.Utilities.isUnspecifiedIp import com.google.common.cache.Cache @@ -81,21 +79,20 @@ class ConnectionTracer(ctx: Context) { // must be called from io thread to avoid the NetworkOnMainThreadException issue#853 uid = cm.getConnectionOwnerUid(protocol, local, remote) - if (DEBUG) - Log.d( - LOG_TAG_VPN, - "getConnectionOwnerUid(): $uid, $key, ${uidCache.getIfPresent(key)}, ${local.address.hostAddress}, ${remote.address.hostAddress}" - ) + Logger.d( + LOG_TAG_VPN, + "getConnectionOwnerUid(): $uid, $key, ${uidCache.getIfPresent(key)}, ${local.address.hostAddress}, ${remote.address.hostAddress}" + ) if (uid != Constants.INVALID_UID) { addUidToCache(key, uid) return uid } } catch (secEx: SecurityException) { - Log.e(LOG_TAG_VPN, "err getUidQ: " + secEx.message, secEx) + Logger.e(LOG_TAG_VPN, "err getUidQ: " + secEx.message, secEx) } catch (ex: InterruptedException) { // InterruptedException is thrown by runBlocking - Log.e(LOG_TAG_VPN, "err getUidQ: " + ex.message, ex) + Logger.e(LOG_TAG_VPN, "err getUidQ: " + ex.message, ex) } catch (ex: Exception) { - Log.e(LOG_TAG_VPN, "err getUidQ: " + ex.message, ex) + Logger.e(LOG_TAG_VPN, "err getUidQ: " + ex.message, ex) } if (retryRequired(uid, protocol, destIp)) { @@ -108,11 +105,10 @@ class ConnectionTracer(ctx: Context) { } val dport = 0 val res = getUidQ(protocol, sourceIp, sourcePort, dip, dport) - if (DEBUG) - Log.d( - LOG_TAG_VPN, - "retrying with: $protocol, $sourceIp, $sourcePort, $dip, $dport old($destIp, $destPort), res: $res" - ) + Logger.d( + LOG_TAG_VPN, + "retrying with: $protocol, $sourceIp, $sourcePort, $dip, $dport old($destIp, $destPort), res: $res" + ) return res } @@ -139,7 +135,7 @@ class ConnectionTracer(ctx: Context) { // do not cache the DNS request (key: 17|10.111.222.1|10.111.222.3|53) if (key == DNS_KEY) return - if (DEBUG) Log.d(LOG_TAG_VPN, "getConnectionOwnerUid(): $uid, $key") + Logger.d(LOG_TAG_VPN, "getConnectionOwnerUid(): $uid, $key") uidCache.put(key, uid) } diff --git a/app/src/main/java/com/celzero/bravedns/scheduler/DataUsageUpdater.kt b/app/src/main/java/com/celzero/bravedns/scheduler/DataUsageUpdater.kt index 865e8b538..33fa81183 100644 --- a/app/src/main/java/com/celzero/bravedns/scheduler/DataUsageUpdater.kt +++ b/app/src/main/java/com/celzero/bravedns/scheduler/DataUsageUpdater.kt @@ -15,16 +15,14 @@ */ package com.celzero.bravedns.scheduler +import Logger.LOG_TAG_SCHEDULER import android.content.Context -import android.util.Log import androidx.work.CoroutineWorker import androidx.work.WorkerParameters -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.database.AppInfoRepository import com.celzero.bravedns.database.ConnectionTrackerRepository import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.util.Constants -import com.celzero.bravedns.util.Logger import org.koin.core.component.KoinComponent import org.koin.core.component.inject @@ -52,14 +50,13 @@ class DataUsageUpdater(context: Context, workerParams: WorkerParameters) : val currentDataUsage = appInfoRepository.getDataUsageByUid(it.uid) val upload = currentDataUsage.uploadBytes + it.uploadBytes val download = currentDataUsage.downloadBytes + it.downloadBytes - if (DEBUG) - Log.d(Logger.LOG_TAG_SCHEDULER, "Data usage for ${it.uid}, $upload, $download") + Logger.d(LOG_TAG_SCHEDULER, "Data usage for ${it.uid}, $upload, $download") appInfoRepository.updateDataUsageByUid(it.uid, upload, download) } catch (e: Exception) { - Log.e(Logger.LOG_TAG_SCHEDULER, "Exception in data usage updater: ${e.message}", e) + Logger.e(LOG_TAG_SCHEDULER, "Exception in data usage updater: ${e.message}", e) } } persistentState.prevDataUsageCheck = currentTimestamp - Log.i(Logger.LOG_TAG_SCHEDULER, "Data usage updated for all apps at $currentTimestamp") + Logger.i(LOG_TAG_SCHEDULER, "Data usage updated for all apps at $currentTimestamp") } } diff --git a/app/src/main/java/com/celzero/bravedns/scheduler/RefreshAppsJob.kt b/app/src/main/java/com/celzero/bravedns/scheduler/RefreshAppsJob.kt index 10d64b027..b0cf3e32b 100644 --- a/app/src/main/java/com/celzero/bravedns/scheduler/RefreshAppsJob.kt +++ b/app/src/main/java/com/celzero/bravedns/scheduler/RefreshAppsJob.kt @@ -15,13 +15,11 @@ */ package com.celzero.bravedns.scheduler +import Logger.LOG_TAG_SCHEDULER import android.content.Context -import android.util.Log import androidx.work.CoroutineWorker import androidx.work.WorkerParameters -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.database.RefreshDatabase -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_SCHEDULER import org.koin.core.component.KoinComponent import org.koin.core.component.inject @@ -31,7 +29,7 @@ class RefreshAppsJob(val context: Context, workerParameters: WorkerParameters) : private val refreshDatabase by inject() override suspend fun doWork(): Result { - if (DEBUG) Log.d(LOG_TAG_SCHEDULER, "starting refresh-database job") + Logger.d(LOG_TAG_SCHEDULER, "starting refresh-database job") refreshDatabase.refresh(RefreshDatabase.ACTION_REFRESH_AUTO) return Result.success() } diff --git a/app/src/main/java/com/celzero/bravedns/scheduler/ScheduleManager.kt b/app/src/main/java/com/celzero/bravedns/scheduler/ScheduleManager.kt index 973e95e08..fd5f5d549 100644 --- a/app/src/main/java/com/celzero/bravedns/scheduler/ScheduleManager.kt +++ b/app/src/main/java/com/celzero/bravedns/scheduler/ScheduleManager.kt @@ -15,13 +15,12 @@ */ package com.celzero.bravedns.scheduler +import Logger.LOG_TAG_SCHEDULER import android.content.Context -import android.util.Log import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.PeriodicWorkRequest import androidx.work.WorkInfo import androidx.work.WorkManager -import com.celzero.bravedns.util.Logger import com.google.common.util.concurrent.ListenableFuture import java.util.concurrent.ExecutionException import java.util.concurrent.TimeUnit @@ -38,7 +37,7 @@ class ScheduleManager(val context: Context) { fun isWorkScheduled(context: Context, tag: String): Boolean { val instance = WorkManager.getInstance(context) val statuses: ListenableFuture> = instance.getWorkInfosByTag(tag) - Log.i(Logger.LOG_TAG_SCHEDULER, "Job $tag already scheduled check") + Logger.i(LOG_TAG_SCHEDULER, "Job $tag already scheduled check") return try { var running = false val workInfos = statuses.get() @@ -50,13 +49,13 @@ class ScheduleManager(val context: Context) { workStatus.state == WorkInfo.State.RUNNING || workStatus.state == WorkInfo.State.ENQUEUED } - Log.i(Logger.LOG_TAG_SCHEDULER, "Job $tag already scheduled? $running") + Logger.i(LOG_TAG_SCHEDULER, "Job $tag already scheduled? $running") running } catch (e: ExecutionException) { - Log.e(Logger.LOG_TAG_SCHEDULER, "error on status check ${e.message}", e) + Logger.e(LOG_TAG_SCHEDULER, "error on status check ${e.message}", e) false } catch (e: InterruptedException) { - Log.e(Logger.LOG_TAG_SCHEDULER, "error on status check ${e.message}", e) + Logger.e(LOG_TAG_SCHEDULER, "error on status check ${e.message}", e) false } } @@ -66,7 +65,7 @@ class ScheduleManager(val context: Context) { fun scheduleDatabaseRefreshJob() { if (isWorkScheduled(context, REFRESH_APPS_JOB_TAG)) return - Log.i(Logger.LOG_TAG_SCHEDULER, "Refresh database job scheduled") + Logger.i(LOG_TAG_SCHEDULER, "Refresh database job scheduled") val refreshAppsJob = PeriodicWorkRequest.Builder( RefreshAppsJob::class.java, diff --git a/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt b/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt index 56f85ec7f..eeb10b22c 100644 --- a/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt +++ b/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt @@ -16,6 +16,7 @@ */ package com.celzero.bravedns.service +import Logger.LOG_TAG_VPN import android.app.ActivityManager import android.app.ForegroundServiceStartNotAllowedException import android.app.ForegroundServiceTypeException @@ -80,7 +81,6 @@ import com.celzero.bravedns.util.Constants.Companion.UID_EVERYBODY import com.celzero.bravedns.util.IPUtil import com.celzero.bravedns.util.InternetProtocol import com.celzero.bravedns.util.KnownPorts -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_VPN import com.celzero.bravedns.util.NotificationActionType import com.celzero.bravedns.util.OrbotHelper import com.celzero.bravedns.util.Protocol @@ -237,7 +237,7 @@ class BraveVPNService : } private fun logd(msg: String) { - if (DEBUG) Log.d(LOG_TAG_VPN, msg) + Logger.d(LOG_TAG_VPN, msg) } override fun bind4(who: String, addrPort: String, fid: Long) { @@ -321,7 +321,7 @@ class BraveVPNService : net.bindSocket(pfd.fileDescriptor) true } catch (e: IOException) { - Log.e(LOG_TAG_VPN, "err bindToNw, ${e.message}, $e") + Logger.e(LOG_TAG_VPN, "err bindToNw, ${e.message}, $e") false } } @@ -556,7 +556,7 @@ class BraveVPNService : } } catch (iex: Exception) { // TODO: show alerts to user on such exceptions, in a separate ui? - Log.e(LOG_TAG_VPN, "err blocking conn, block anyway", iex) + Logger.e(LOG_TAG_VPN, "err blocking conn, block anyway", iex) return FirewallRuleset.RULE1C } @@ -773,7 +773,7 @@ class BraveVPNService : private fun isIfaceMetered(dst: String): Boolean { val dest = IPAddressString(dst) if (dest.isEmpty) { - Log.e(LOG_TAG_VPN, "invalid destination IP: $dst") + Logger.e(LOG_TAG_VPN, "invalid destination IP: $dst") return isActiveIfaceMetered() } @@ -796,7 +796,7 @@ class BraveVPNService : // if there are no network to be bound given a destination IP, fallback to active network if (cap == null) { - Log.e(LOG_TAG_VPN, "no network to be bound for $dst, use active network") + Logger.e(LOG_TAG_VPN, "no network to be bound for $dst, use active network") return isActiveIfaceMetered() } return !cap.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED) @@ -831,7 +831,7 @@ class BraveVPNService : if (!persistentState.getBlockAppWhenBackground()) return false if (!accessibilityServiceFunctional()) { - Log.w(LOG_TAG_VPN, "accessibility service not functional, disable bg-block") + Logger.w(LOG_TAG_VPN, "accessibility service not functional, disable bg-block") handleAccessibilityFailure() return false } @@ -848,7 +848,7 @@ class BraveVPNService : } private fun showAccessibilityStoppedNotification() { - Log.i(LOG_TAG_VPN, "app not in use failure, show notification") + Logger.i(LOG_TAG_VPN, "app not in use failure, show notification") val intent = Intent(this, NotificationHandlerDialog::class.java) intent.putExtra( @@ -964,7 +964,7 @@ class BraveVPNService : var builder = Builder() if (canAllowBypass()) { - Log.i(LOG_TAG_VPN, "allow apps to bypass vpn on-demand") + Logger.i(LOG_TAG_VPN, "allow apps to bypass vpn on-demand") builder = builder.allowBypass() // TODO: should allowFamily be set? // family must be either AF_INET (for IPv4) or AF_INET6 (for IPv6) @@ -1002,18 +1002,18 @@ class BraveVPNService : if (!persistentState.routeRethinkInRethink) { addDisallowedApplication(builder, this.packageName) } else { - Log.i(LOG_TAG_VPN, "builder: route rethink traffic in rethink") + Logger.i(LOG_TAG_VPN, "builder: route rethink traffic in rethink") // no-op } if (isAppPaused()) { // exclude all non-firewalled apps and be done if (VpnController.isVpnLockdown()) { - Log.i(LOG_TAG_VPN, "paused but vpn is lockdown; cannot exclude apps") + Logger.i(LOG_TAG_VPN, "paused but vpn is lockdown; cannot exclude apps") return builder } val nonFirewalledApps = FirewallManager.getNonFirewalledAppsPackageNames() val packages = nonFirewalledApps.map { it.packageName } - Log.i(LOG_TAG_VPN, "paused, exclude non-firewalled apps, size: ${packages.count()}") + Logger.i(LOG_TAG_VPN, "paused, exclude non-firewalled apps, size: ${packages.count()}") addDisallowedApplication(builder, packages) return builder } @@ -1028,7 +1028,7 @@ class BraveVPNService : if (!VpnController.isVpnLockdown()) { addDisallowedApplication(builder, excludedApps) } else { - Log.w(LOG_TAG_VPN, "builder, vpn is lockdown, ignoring exclude-apps list") + Logger.w(LOG_TAG_VPN, "builder, vpn is lockdown, ignoring exclude-apps list") } } return builder @@ -1038,7 +1038,7 @@ class BraveVPNService : try { builder.addDisallowedApplication(pkg) } catch (e: PackageManager.NameNotFoundException) { - Log.w(LOG_TAG_VPN, "skip adding disallowed app ($pkg)", e) + Logger.w(LOG_TAG_VPN, "skip adding disallowed app ($pkg)", e) } } @@ -1051,7 +1051,7 @@ class BraveVPNService : try { builder.addAllowedApplication(it) } catch (e: PackageManager.NameNotFoundException) { - Log.w(LOG_TAG_VPN, "skip adding allowed app ($it)", e) + Logger.w(LOG_TAG_VPN, "skip adding allowed app ($it)", e) } } } @@ -1082,7 +1082,7 @@ class BraveVPNService : persistentState.orbotConnectionStatus.observeForever(orbotStartStatusObserver) dnscryptRelayObserver = makeDnscryptRelayObserver() persistentState.dnsCryptRelays.observeForever(dnscryptRelayObserver) - Log.i(LOG_TAG_VPN, "observe pref, dnscrypt relay, app list changes") + Logger.i(LOG_TAG_VPN, "observe pref, dnscrypt relay, app list changes") } private fun makeDnscryptRelayObserver(): Observer { @@ -1118,11 +1118,11 @@ class BraveVPNService : if (Sets.symmetricDifference(excludedApps, latestExcludedApps).isEmpty()) return@Observer - Log.i(LOG_TAG_VPN, "excluded-apps list changed, restart vpn") + Logger.i(LOG_TAG_VPN, "excluded-apps list changed, restart vpn") io("excludeApps") { restartVpnWithNewAppConfig(reason = "excludeApps") } } catch (e: Exception) { // NoSuchElementException, ConcurrentModification - Log.e(LOG_TAG_VPN, "error retrieving value from appInfos observer ${e.message}", e) + Logger.e(LOG_TAG_VPN, "error retrieving value from appInfos observer ${e.message}", e) } } } @@ -1244,7 +1244,7 @@ class BraveVPNService : builder.setContentTitle(contentTitle) } NotificationActionType.NONE -> { - Log.i(LOG_TAG_VPN, "No notification action") + Logger.i(LOG_TAG_VPN, "No notification action") } } @@ -1296,7 +1296,7 @@ class BraveVPNService : override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { rethinkUid = getRethinkUid() val pid = Process.myPid() - Log.i( + Logger.i( LOG_TAG_VPN, "onStartCommand, us: $rethinkUid / pid: $pid, primary? ${isPrimaryUser()}" ) @@ -1312,11 +1312,11 @@ class BraveVPNService : if (isAtleastU()) { var ok = startForegroundService(FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED) if (!ok) { - Log.i(LOG_TAG_VPN, "start service failed, retrying with connected device") + Logger.i(LOG_TAG_VPN, "start service failed, retrying with connected device") ok = startForegroundService(FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE) } if (!ok) { - Log.i(LOG_TAG_VPN, "start service failed, stopping service") + Logger.i(LOG_TAG_VPN, "start service failed, stopping service") signalStopService(userInitiated = false) // notify and stop return@ui } @@ -1333,7 +1333,7 @@ class BraveVPNService : var isNewVpn = false if (!isVpnStarted) { - Log.i(LOG_TAG_VPN, "new vpn") + Logger.i(LOG_TAG_VPN, "new vpn") isVpnStarted = true isNewVpn = true connectionMonitor.onVpnStart(this) @@ -1352,7 +1352,7 @@ class BraveVPNService : mtu ) - Log.i(LOG_TAG_VPN, "start-foreground with opts $opts (for new-vpn? $isNewVpn)") + Logger.i(LOG_TAG_VPN, "start-foreground with opts $opts (for new-vpn? $isNewVpn)") if (!isNewVpn) { io("tunUpdate") { // may call signalStopService(userInitiated=false) if go-vpn-adapter is missing @@ -1387,15 +1387,15 @@ class BraveVPNService : ) return true } catch (e: ForegroundServiceStartNotAllowedException) { - Log.e(LOG_TAG_VPN, "startForeground failed, start not allowed exception", e) + Logger.e(LOG_TAG_VPN, "startForeground failed, start not allowed exception", e) } catch (e: ForegroundServiceTypeException) { - Log.e(LOG_TAG_VPN, "startForeground failed, service type exception", e) + Logger.e(LOG_TAG_VPN, "startForeground failed, service type exception", e) } catch (e: SecurityException) { - Log.e(LOG_TAG_VPN, "startForeground failed, security exception", e) + Logger.e(LOG_TAG_VPN, "startForeground failed, security exception", e) } catch (e: IllegalArgumentException) { - Log.e(LOG_TAG_VPN, "startForeground failed, illegal argument", e) + Logger.e(LOG_TAG_VPN, "startForeground failed, illegal argument", e) } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "startForeground failed", e) + Logger.e(LOG_TAG_VPN, "startForeground failed", e) } return false } @@ -1404,10 +1404,10 @@ class BraveVPNService : val overlayMtu = overlayNetworks.mtu val underlyingMtu = underlyingNetworks?.minMtu ?: VPN_INTERFACE_MTU val minMtu = min(overlayMtu, underlyingMtu) - Log.i(LOG_TAG_VPN, "mtu; proxy: $overlayMtu, underlying: $underlyingMtu, min: $minMtu") + Logger.i(LOG_TAG_VPN, "mtu; proxy: $overlayMtu, underlying: $underlyingMtu, min: $minMtu") // min mtu should be at least MIN_MTU (1280) if (minMtu < MIN_MTU) { - Log.w(LOG_TAG_VPN, "mtu less than $MIN_MTU, using $MIN_MTU") + Logger.w(LOG_TAG_VPN, "mtu less than $MIN_MTU, using $MIN_MTU") return MIN_MTU } return minMtu @@ -1461,13 +1461,13 @@ class BraveVPNService : } private suspend fun updateTun(tunnelOptions: AppConfig.TunnelOptions) { - Log.i(LOG_TAG_VPN, "update-tun with new pre-set tunnel options") + Logger.i(LOG_TAG_VPN, "update-tun with new pre-set tunnel options") if (!persistentState.getVpnEnabled()) { // when persistent-state "thinks" vpn is disabled, stop the service, especially when // we could be here via onStartCommand -> updateTun -> handleVpnAdapterChange while // conn-monitor and go-vpn-adapter exist, but persistent-state tracking vpn goes out // of sync - Log.e(LOG_TAG_VPN, "stop-vpn(updateTun), tracking vpn is out of sync") + Logger.e(LOG_TAG_VPN, "stop-vpn(updateTun), tracking vpn is out of sync") io("outOfSync") { signalStopService(userInitiated = false) } return } @@ -1477,7 +1477,7 @@ class BraveVPNService : // TODO: like Intra, call VpnController#stop instead? see // VpnController#onStartComplete if (ok == false) { - Log.w(LOG_TAG_VPN, "Cannot handle vpn adapter changes, no tunnel") + Logger.w(LOG_TAG_VPN, "Cannot handle vpn adapter changes, no tunnel") io("noTunnel") { signalStopService(userInitiated = false) } return } @@ -1571,7 +1571,7 @@ class BraveVPNService : notificationManager.notify(SERVICE_ID, updateNotificationBuilder()) } PersistentState.NETWORK -> { - Log.i(LOG_TAG_VPN, "network change, ${persistentState.useMultipleNetworks}") + Logger.i(LOG_TAG_VPN, "network change, ${persistentState.useMultipleNetworks}") io("useAllNetworks") { notifyConnectionMonitor() } } PersistentState.NOTIFICATION_ACTION -> { @@ -1608,7 +1608,7 @@ class BraveVPNService : } } PersistentState.CONNECTIVITY_CHECKS -> { - Log.i( + Logger.i( LOG_TAG_VPN, "connectivity checks changed, ${persistentState.connectivityChecks}" ) @@ -1616,7 +1616,7 @@ class BraveVPNService : } PersistentState.NOTIFICATION_PERMISSION -> { if (persistentState.shouldRequestNotificationPermission) { - Log.i(LOG_TAG_VPN, "notification permission allowed, show notification") + Logger.i(LOG_TAG_VPN, "notification permission allowed, show notification") notificationManager.notify(SERVICE_ID, updateNotificationBuilder()) } else { // no-op @@ -1627,7 +1627,7 @@ class BraveVPNService : private suspend fun disableAllowBypassIfNeeded() { if (appConfig.isProxyEnabled() && persistentState.allowBypass) { - Log.i(LOG_TAG_VPN, "disabling allowBypass, as proxy is set.") + Logger.i(LOG_TAG_VPN, "disabling allowBypass, as proxy is set.") // inform user about the change in allow bypass setting by showing a toast ui { val message = @@ -1667,7 +1667,7 @@ class BraveVPNService : } private suspend fun handleIPProtoChanges() { - Log.i(LOG_TAG_VPN, "handle ip proto changes") + Logger.i(LOG_TAG_VPN, "handle ip proto changes") if (InternetProtocol.isAuto(persistentState.internetProtocolType)) { // initiates connectivity checks if Auto mode and calls onNetworkConnected // or onNetworkDisconnected. onNetworkConnected may call restartVpn and setRoute on @@ -1681,7 +1681,7 @@ class BraveVPNService : private suspend fun handleProxyChange() { val tunProxyMode = appConfig.getTunProxyMode() val proxy = AppConfig.ProxyProvider.getProxyProvider(appConfig.getProxyProvider()) - Log.i(LOG_TAG_VPN, "handle proxy change, proxy: $proxy, mode: $tunProxyMode") + Logger.i(LOG_TAG_VPN, "handle proxy change, proxy: $proxy, mode: $tunProxyMode") when (proxy) { AppConfig.ProxyProvider.NONE -> { // no-op @@ -1719,18 +1719,18 @@ class BraveVPNService : if (!userInitiated) notifyUserOnVpnFailure() stopVpnAdapter() stopSelf() - Log.i(LOG_TAG_VPN, "stopped vpn adapter and vpn service") + Logger.i(LOG_TAG_VPN, "stopped vpn adapter and vpn service") } private fun stopVpnAdapter() { io("stopVpn") { if (vpnAdapter == null) { - Log.i(LOG_TAG_VPN, "vpn adapter already stopped") + Logger.i(LOG_TAG_VPN, "vpn adapter already stopped") return@io } vpnAdapter?.closeTun() vpnAdapter = null - Log.i(LOG_TAG_VPN, "stop vpn adapter") + Logger.i(LOG_TAG_VPN, "stop vpn adapter") } } @@ -1755,7 +1755,7 @@ class BraveVPNService : private suspend fun setPcapMode() { val pcapPath = appConfig.getPcapFilePath() - Log.i(LOG_TAG_VPN, "pcap mode enabled, path: $pcapPath") + Logger.i(LOG_TAG_VPN, "pcap mode enabled, path: $pcapPath") vpnAdapter?.setPcapMode(pcapPath) } @@ -1767,7 +1767,7 @@ class BraveVPNService : appConfig.getProtocolTranslationMode(), mtu() ) - Log.i( + Logger.i( LOG_TAG_VPN, "set tun mode with dns: ${tunnelOptions.tunDnsMode}, firewall: ${tunnelOptions.tunFirewallMode}, proxy: ${tunnelOptions.tunProxyMode}, pt: ${tunnelOptions.ptMode}" ) @@ -1810,10 +1810,10 @@ class BraveVPNService : private suspend fun logAndToastIfNeeded(msg: String, logLevel: Int = Log.WARN) { when (logLevel) { - Log.WARN -> Log.w(LOG_TAG_VPN, msg) - Log.ERROR -> Log.e(LOG_TAG_VPN, msg) - Log.INFO -> Log.i(LOG_TAG_VPN, msg) - else -> Log.d(LOG_TAG_VPN, msg) + Log.WARN -> Logger.w(LOG_TAG_VPN, msg) + Log.ERROR -> Logger.e(LOG_TAG_VPN, msg) + Log.INFO -> Logger.i(LOG_TAG_VPN, msg) + else -> Logger.d(LOG_TAG_VPN, msg) } uiCtx("toast") { if (DEBUG) showToastUiCentered(this, msg, Toast.LENGTH_LONG) } } @@ -1835,7 +1835,7 @@ class BraveVPNService : } suspend fun refreshResolvers() { - Log.i(LOG_TAG_VPN, "refresh resolvers") + Logger.i(LOG_TAG_VPN, "refresh resolvers") vpnAdapter?.refreshResolvers() } @@ -1849,10 +1849,10 @@ class BraveVPNService : val protos = InternetProtocol.byProtos(p.first, p.second).value() try { if (vpnAdapter != null) { - Log.i(LOG_TAG_VPN, "vpn-adapter exists, use it") + Logger.i(LOG_TAG_VPN, "vpn-adapter exists, use it") // in case, if vpn-adapter exists, update the existing vpn-adapter if (vpnAdapter?.updateLinkAndRoutes(tunFd, opts, protos) == false) { - Log.e(LOG_TAG_VPN, "err update vpn-adapter") + Logger.e(LOG_TAG_VPN, "err update vpn-adapter") return noTun } return ok @@ -1864,13 +1864,13 @@ class BraveVPNService : return ok } } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "err new vpn-adapter: ${e.message}", e) + Logger.e(LOG_TAG_VPN, "err new vpn-adapter: ${e.message}", e) return noTun } finally { try { // close the tunFd as GoVpnAdapter has its own copy tunFd.close() } catch (ignored: IOException) { - Log.e(LOG_TAG_VPN, "err closing tunFd: ${ignored.message}", ignored) + Logger.e(LOG_TAG_VPN, "err closing tunFd: ${ignored.message}", ignored) } } } @@ -1879,7 +1879,7 @@ class BraveVPNService : // failing. override fun onNetworkDisconnected(networks: ConnectionMonitor.UnderlyingNetworks) { underlyingNetworks = networks - Log.i(LOG_TAG_VPN, "onNetworkDisconnected: state: z, $networks") + Logger.i(LOG_TAG_VPN, "onNetworkDisconnected: state: z, $networks") if (FAIL_OPEN_ON_NO_NETWORK) { setUnderlyingNetworks(null) } else { @@ -1892,7 +1892,7 @@ class BraveVPNService : } override fun onNetworkRegistrationFailed() { - Log.i(LOG_TAG_VPN, "recd nw registration failed, stop vpn service with notification") + Logger.i(LOG_TAG_VPN, "recd nw registration failed, stop vpn service with notification") signalStopService(userInitiated = false) } @@ -1903,7 +1903,7 @@ class BraveVPNService : val isBoundNetworksChanged = out.netChanged val isMtuChanged = out.mtuChanged underlyingNetworks = networks - Log.i(LOG_TAG_VPN, "onNetworkConnected: changes: $out for new: $networks") + Logger.i(LOG_TAG_VPN, "onNetworkConnected: changes: $out for new: $networks") // always reset the system dns server ip of the active network with the tunnel setNetworkAndDefaultDnsIfNeeded() @@ -1911,7 +1911,7 @@ class BraveVPNService : if (networks.useActive) { setUnderlyingNetworks(null) } else if (networks.ipv4Net.isEmpty() && networks.ipv6Net.isEmpty()) { - Log.w(LOG_TAG_VPN, "network changed but empty ipv4/ipv6 networks w connectivity") + Logger.w(LOG_TAG_VPN, "network changed but empty ipv4/ipv6 networks w connectivity") if (FAIL_OPEN_ON_NO_NETWORK) { setUnderlyingNetworks(null) } else { @@ -1984,7 +1984,7 @@ class BraveVPNService : val underlyingMtuChanged = old.minMtu != new.minMtu val overlayMtuChanged = overlayNetworks.mtu != aux.mtu - Log.d( + Logger.d( LOG_TAG_VPN, "old: ${old.minMtu}, new: ${new.minMtu}, oldaux: ${overlayNetworks.mtu} newaux: ${aux.mtu}" ) @@ -2049,7 +2049,7 @@ class BraveVPNService : ) { val dl: MutableList = mutableListOf() dl.addAll(currNet?.dnsServers?.keys?.toList() ?: emptyList()) - Log.i(LOG_TAG_VPN, "dns servers ipv4,ipv6: $dl") + Logger.i(LOG_TAG_VPN, "dns servers ipv4,ipv6: $dl") dl } else { // get dns servers from the first network or active network @@ -2070,17 +2070,17 @@ class BraveVPNService : // route, netstack will make use of the dns servers dns4?.let { dl.addAll(it) } dns6?.let { dl.addAll(it) } - Log.i(LOG_TAG_VPN, "dns servers for network: $dl") + Logger.i(LOG_TAG_VPN, "dns servers for network: $dl") dl } else { - Log.i(LOG_TAG_VPN, "dns servers for network: $dnsServers") + Logger.i(LOG_TAG_VPN, "dns servers for network: $dnsServers") dnsServers } } if (dnsServers.isNullOrEmpty()) { // TODO: send an alert/notification instead? - Log.w(LOG_TAG_VPN, "No system dns servers found") + Logger.w(LOG_TAG_VPN, "No system dns servers found") if (appConfig.isSystemDns()) { // on null dns servers, show toast ui { @@ -2095,7 +2095,7 @@ class BraveVPNService : } } io("setSystemAndDefaultDns") { - Log.i(LOG_TAG_VPN, "Setting dns servers: $dnsServers") + Logger.i(LOG_TAG_VPN, "Setting dns servers: $dnsServers") val dns = determineSystemDns(dnsServers) // set system dns whenever there is a change in network vpnAdapter?.setSystemDns(dns) @@ -2113,7 +2113,7 @@ class BraveVPNService : // no dns servers found, return empty list return emptyList() } - if (DEBUG) Log.d(LOG_TAG_VPN, "System dns: $list") + Logger.d(LOG_TAG_VPN, "System dns: $list") return list } @@ -2125,7 +2125,7 @@ class BraveVPNService : private fun handleVpnLockdownStateAsync() { if (!syncLockdownState()) return - Log.i(LOG_TAG_VPN, "vpn lockdown mode change, restarting") + Logger.i(LOG_TAG_VPN, "vpn lockdown mode change, restarting") io("lockdownSync") { restartVpnWithNewAppConfig(reason = "lockdownSync") } } @@ -2181,7 +2181,7 @@ class BraveVPNService : unregisterAccessibilityServiceState() orbotHelper.unregisterReceiver() } catch (e: IllegalArgumentException) { - Log.w(LOG_TAG_VPN, "Unregister receiver error: ${e.message}") + Logger.w(LOG_TAG_VPN, "Unregister receiver error: ${e.message}") } persistentState.setVpnEnabled(false) @@ -2202,7 +2202,7 @@ class BraveVPNService : vpnScope.cancel("vpnDestroy") } catch (ignored: IllegalStateException) {} - Log.w(LOG_TAG_VPN, "Destroying VPN service") + Logger.w(LOG_TAG_VPN, "Destroying VPN service") // stop foreground service will take care of stopping the service for both // version >= 24 and < 24 @@ -2293,11 +2293,11 @@ class BraveVPNService : // no route available for both v4 and v6, add all routes // connectivity manager is expected to retry when no route is available // see ConnectionMonitor#repopulateTrackedNetworks - Log.i(LOG_TAG_VPN, "No routes, fail-open? $FAIL_OPEN_ON_NO_NETWORK") + Logger.i(LOG_TAG_VPN, "No routes, fail-open? $FAIL_OPEN_ON_NO_NETWORK") has4 = FAIL_OPEN_ON_NO_NETWORK has6 = FAIL_OPEN_ON_NO_NETWORK } else { - Log.i(LOG_TAG_VPN, "Building vpn for v4? $has4, v6? $has6") + Logger.i(LOG_TAG_VPN, "Building vpn for v4? $has4, v6? $has6") } return Pair(has4, has6) @@ -2342,7 +2342,7 @@ class BraveVPNService : } else { // when not routing all traffic (firewall inactive) allow v4/v6 families // to be routed based on the underlying network (bypassing the tunnel) - Log.i(LOG_TAG_VPN, "dns-only mode, allowFamily: v4: $has4, v6: $has6") + Logger.i(LOG_TAG_VPN, "dns-only mode, allowFamily: v4: $has4, v6: $has6") if (has4) { builder.allowFamily(AF_INET) } @@ -2352,7 +2352,7 @@ class BraveVPNService : } return builder.establish() } catch (e: Exception) { - Log.e(LOG_TAG_VPN, e.message, e) + Logger.e(LOG_TAG_VPN, e.message ?: "err establishVpn", e) return null } } @@ -2381,10 +2381,10 @@ class BraveVPNService : if (underlay?.useActive != true) { val underlayIpv6 = (underlay?.ipv6Net?.size ?: 0) > 0 return if (!underlayIpv6) { - Log.i(LOG_TAG_VPN, "r6: No IPv6 networks available") + Logger.i(LOG_TAG_VPN, "r6: No IPv6 networks available") false } else { - Log.i(LOG_TAG_VPN, "r6: IPv6 available, overlay: $overlayIpv6") + Logger.i(LOG_TAG_VPN, "r6: IPv6 available, overlay: $overlayIpv6") // underlay network is available, check if overlay network is available overlayIpv6 } @@ -2392,18 +2392,18 @@ class BraveVPNService : val activeNetwork = connectivityManager.activeNetwork if (activeNetwork == null) { - Log.i(LOG_TAG_VPN, "r6: missing active network, use the first network") + Logger.i(LOG_TAG_VPN, "r6: missing active network, use the first network") return underlay.ipv6Net.isNotEmpty() && overlayIpv6 } underlay.ipv6Net.forEach { val underlayIpv6 = isNetworkSame(it.network, activeNetwork) if (underlayIpv6) { - Log.i(LOG_TAG_VPN, "r6: Active network ok: ov: $overlayIpv6") + Logger.i(LOG_TAG_VPN, "r6: Active network ok: ov: $overlayIpv6") // underlay network is available, check if overlay network is available return overlayIpv6 } } - Log.i(LOG_TAG_VPN, "r6: active network not available") + Logger.i(LOG_TAG_VPN, "r6: active network not available") return false } } @@ -2416,10 +2416,10 @@ class BraveVPNService : val interestingNet = interestingNetworkChanges(aux = nw) val isRoutesChanged = interestingNet.routesChanged val isMtuChanged = interestingNet.mtuChanged - Log.i(LOG_TAG_VPN, "overlay: routes changed? $isRoutesChanged, mtu changed? $isMtuChanged") + Logger.i(LOG_TAG_VPN, "overlay: routes changed? $isRoutesChanged, mtu changed? $isMtuChanged") overlayNetworks = nw if (isRoutesChanged || isMtuChanged) { - Log.i(LOG_TAG_VPN, "overlay changed $overlayNetworks, restart vpn") + Logger.i(LOG_TAG_VPN, "overlay changed $overlayNetworks, restart vpn") // There may be cases where both overlay and underlay networks have the same routes. // In such scenarios, no restart is required. However, here the routeChange is // considered @@ -2432,7 +2432,7 @@ class BraveVPNService : ) } } else { - Log.i(LOG_TAG_VPN, "overlay routes or mtu not changed, no restart needed") + Logger.i(LOG_TAG_VPN, "overlay routes or mtu not changed, no restart needed") } } @@ -2460,24 +2460,24 @@ class BraveVPNService : if (underlay?.useActive != true) { val underlayIpv4 = (underlay?.ipv4Net?.size ?: 0) > 0 if (!underlayIpv4) { - Log.i(LOG_TAG_VPN, "r4: No IPv4 networks available") + Logger.i(LOG_TAG_VPN, "r4: No IPv4 networks available") return false } else { - Log.i(LOG_TAG_VPN, "r4: IPv4 networks available") + Logger.i(LOG_TAG_VPN, "r4: IPv4 networks available") // underlay network is available, check if overlay network is available return overlayIpv4 } } else { val activeNetwork = connectivityManager.activeNetwork if (activeNetwork == null) { - Log.i(LOG_TAG_VPN, "r4: missing active network, use the first network") + Logger.i(LOG_TAG_VPN, "r4: missing active network, use the first network") return underlay.ipv4Net.isNotEmpty() && overlayIpv4 } underlay.ipv4Net.forEach { val underlayIpv4 = isNetworkSame(it.network, activeNetwork) if (underlayIpv4) { - Log.i(LOG_TAG_VPN, "r4: reachable, ov: $overlayIpv4") + Logger.i(LOG_TAG_VPN, "r4: reachable, ov: $overlayIpv4") // underlay network is available, check if overlay network is available return overlayIpv4 } @@ -2490,7 +2490,7 @@ class BraveVPNService : private fun addRoute6(b: Builder): Builder { if (persistentState.privateIps) { - Log.i(LOG_TAG_VPN, "addRoute6: privateIps is true, adding routes") + Logger.i(LOG_TAG_VPN, "addRoute6: privateIps is true, adding routes") // exclude LAN traffic, add only unicast routes // add only unicast routes // range 0000:0000:0000:0000:0000:0000:0000:0000- @@ -2513,7 +2513,7 @@ class BraveVPNService : // not considering 100::/64 and other reserved ranges } else { // no need to exclude LAN traffic, add default route which is ::/0 - Log.i(LOG_TAG_VPN, "addRoute6: privateIps is false, adding default route") + Logger.i(LOG_TAG_VPN, "addRoute6: privateIps is false, adding default route") b.addRoute(Constants.UNSPECIFIED_IP_IPV6, Constants.UNSPECIFIED_PORT) } @@ -2522,7 +2522,7 @@ class BraveVPNService : private fun addRoute4(b: Builder): Builder { if (persistentState.privateIps) { - Log.i(LOG_TAG_VPN, "addRoute4: privateIps is true, adding routes") + Logger.i(LOG_TAG_VPN, "addRoute4: privateIps is true, adding routes") // https://developer.android.com/reference/android/net/VpnService.Builder.html#addRoute(java.lang.String,%20int) // Adds a route to the VPN's routing table. The VPN will forward all traffic to the // destination through the VPN interface. The destination is specified by address and @@ -2552,21 +2552,21 @@ class BraveVPNService : try { it.address?.let { it1 -> b.addRoute(it1, it.prefix) } } catch (ex: Exception) { - Log.e(LOG_TAG_VPN, "exception while adding route: ${ex.message}", ex) + Logger.e(LOG_TAG_VPN, "exception while adding route: ${ex.message}", ex) } } start = IPUtil.plus1(exclude.end) } } catch (ex: SocketException) { - Log.e(LOG_TAG_VPN, "addRoute4: ${ex.message}", ex) + Logger.e(LOG_TAG_VPN, "addRoute4: ${ex.message}", ex) } catch (ex: UnknownHostException) { - Log.e(LOG_TAG_VPN, "addRoute4: ${ex.message}", ex) + Logger.e(LOG_TAG_VPN, "addRoute4: ${ex.message}", ex) } b.addRoute(LanIp.GATEWAY.make(IPV4_TEMPLATE), 32) b.addRoute(LanIp.DNS.make(IPV4_TEMPLATE), 32) b.addRoute(LanIp.ROUTER.make(IPV4_TEMPLATE), 32) } else { - Log.i(LOG_TAG_VPN, "addRoute4: privateIps is false, adding default route") + Logger.i(LOG_TAG_VPN, "addRoute4: privateIps is false, adding default route") // no need to exclude LAN traffic, add default route which is 0.0.0.0/0 b.addRoute(Constants.UNSPECIFIED_IP_IPV4, Constants.UNSPECIFIED_PORT) } @@ -2637,7 +2637,7 @@ class BraveVPNService : // queryType: see ResourceRecordTypes.kt logd("onQuery: rcvd query: $fqdn, qtype: $qtype") if (fqdn == null) { - Log.e(LOG_TAG_VPN, "onQuery: fqdn is null") + Logger.e(LOG_TAG_VPN, "onQuery: fqdn is null") // return block all, as it is not expected to reach here return@runBlocking makeNsOpts(Backend.BlockAll) } @@ -2655,7 +2655,7 @@ class BraveVPNService : } val res = makeNsOpts(Backend.Preferred) // should not reach here - Log.e( + Logger.e( LOG_TAG_VPN, "onQuery: unknown mode ${appConfig.getBraveMode()}, $fqdn, returning $res" ) @@ -2807,7 +2807,7 @@ class BraveVPNService : override fun onResponse(summary: backend.DNSSummary?) { if (summary == null) { - Log.i(LOG_TAG_VPN, "received null summary for dns") + Logger.i(LOG_TAG_VPN, "received null summary for dns") return } @@ -2872,7 +2872,7 @@ class BraveVPNService : override fun onSocketClosed(s: SocketSummary?) { if (s == null) { - Log.i(LOG_TAG_VPN, "received null summary for socket") + Logger.i(LOG_TAG_VPN, "received null summary for socket") return } @@ -2893,7 +2893,7 @@ class BraveVPNService : logd("onSocketClosed: $s") if (s.uid.isNullOrEmpty()) { - Log.e(LOG_TAG_VPN, "onSocketClosed: missing uid, summary: $s") + Logger.e(LOG_TAG_VPN, "onSocketClosed: missing uid, summary: $s") return } @@ -2912,7 +2912,7 @@ class BraveVPNService : netLogTracker.updateIpSummary(connectionSummary) } } catch (e: NumberFormatException) { - Log.e(LOG_TAG_VPN, "onSocketClosed: ${e.message}", e) + Logger.e(LOG_TAG_VPN, "onSocketClosed: ${e.message}", e) } } @@ -3029,16 +3029,16 @@ class BraveVPNService : val key = CidKey(cm.connId, uid) trackedCids.add(key) - // TODO: set dup as true for now (v055e), need to handle dup properly in future - val d = dup || true + // TODO: set dup as true for now (v055f), need to handle dup properly in future + val duplicate = dup || DEBUG // if the connection is Rethink's uid and if the dup is false, then the connections // are rethink's own connections, so add it in network log as well - if (!d) { + if (!duplicate) { // no need to consider return value as the function is called only for logging persistAndConstructFlowResponse(cm, proxy, connId, uid) } // make the cm obj to null so that the db write will not happen - val c = if (d) cm else null + val c = if (duplicate) cm else null return@runBlocking persistAndConstructFlowResponse(c, proxy, connId, uid, isRethink) } @@ -3171,9 +3171,9 @@ class BraveVPNService : } // carry out this check after wireguard, because wireguard has catchAll and lockdown - // if no proxy is enabled, return Ipn.Base - if (!appConfig.isProxyEnabled()) { - logd("flow: no proxy enabled, returning Ipn.Base, $connId, $uid") + // if no proxy or dns proxy is enabled, return baseOrExit + if (!appConfig.isProxyEnabled() && !appConfig.isDnsProxyActive()) { + logd("flow: no proxy/dnsproxy enabled, returning Ipn.Base, $connId, $uid") return persistAndConstructFlowResponse(connTracker, baseOrExit, connId, uid) } @@ -3218,7 +3218,7 @@ class BraveVPNService : val activeId = ProxyManager.getProxyIdForApp(uid) if (!activeId.contains(ProxyManager.ID_ORBOT_BASE)) { - Log.e(LOG_TAG_VPN, "flow: orbot proxy is enabled but app is not included") + Logger.e(LOG_TAG_VPN, "flow: orbot proxy is enabled but app is not included") // pass-through } else { logd("flow: orbot proxy for $uid, $connId") @@ -3310,10 +3310,10 @@ class BraveVPNService : // if the last handshake is older than the timeout, refresh the proxy if (durationMs > wgHandshakeTimeout) { wgHandShakeCheckpoints[id] = realtime - Log.i(LOG_TAG_VPN, "flow: handshake timeout for $id, $durationSecs, refreshing") + Logger.i(LOG_TAG_VPN, "flow: handshake timeout for $id, $durationSecs, refreshing") io("proxyHandshake") { vpnAdapter?.refreshProxy(id) } } else { - Log.i(LOG_TAG_VPN, "flow: handshake is within timeout for $id, $durationSecs") + Logger.i(LOG_TAG_VPN, "flow: handshake is within timeout for $id, $durationSecs") wgHandShakeCheckpoints[id] = realtime } } @@ -3380,12 +3380,12 @@ class BraveVPNService : mark.uid = uid.toString() } if (cm == null) { - Log.i( + Logger.i( LOG_TAG_VPN, "flow: returning mark: $mark for connId: $connId, uid: $uid, cm: null" ) } else { - Log.i( + Logger.i( LOG_TAG_VPN, "flow: returning mark: $mark for src(${cm.sourceIP}: ${cm.sourcePort}), dest(${cm.destIP}:${cm.destPort})" ) @@ -3457,7 +3457,7 @@ class BraveVPNService : val status = vpnAdapter?.getProxyStatusById(id) status } else { - Log.w(LOG_TAG_VPN, "error while fetching proxy status: vpnAdapter is null") + Logger.w(LOG_TAG_VPN, "error while fetching proxy status: vpnAdapter is null") null } } @@ -3466,7 +3466,7 @@ class BraveVPNService : return if (vpnAdapter != null) { vpnAdapter?.getProxyStats(id) } else { - Log.w(LOG_TAG_VPN, "error while fetching proxy stats: vpnAdapter is null") + Logger.w(LOG_TAG_VPN, "error while fetching proxy stats: vpnAdapter is null") null } } @@ -3475,7 +3475,7 @@ class BraveVPNService : return if (vpnAdapter != null) { vpnAdapter?.getSupportedIpVersion(id) } else { - Log.w(LOG_TAG_VPN, "error while fetching protocol status: vpnAdapter is null") + Logger.w(LOG_TAG_VPN, "error while fetching protocol status: vpnAdapter is null") null } } diff --git a/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt b/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt index e334ce1e2..6b0ca4045 100644 --- a/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt +++ b/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.service +import Logger.LOG_TAG_CONNECTION import android.content.Context import android.net.ConnectivityManager import android.net.LinkProperties @@ -29,17 +30,11 @@ import android.os.Message import android.os.SystemClock import android.system.ErrnoException import android.system.OsConstants.ECONNREFUSED -import android.util.Log -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.util.InternetProtocol -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_CONNECTION import com.celzero.bravedns.util.Utilities.isAtleastQ import com.celzero.bravedns.util.Utilities.isAtleastS import com.celzero.bravedns.util.Utilities.isNetworkSame import com.google.common.collect.Sets -import kotlinx.coroutines.runBlocking -import org.koin.core.component.KoinComponent -import org.koin.core.component.inject import java.io.Closeable import java.io.IOException import java.net.DatagramSocket @@ -53,6 +48,9 @@ import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit import kotlin.math.max import kotlin.math.min +import kotlinx.coroutines.runBlocking +import org.koin.core.component.KoinComponent +import org.koin.core.component.inject class ConnectionMonitor(private val networkListener: NetworkListener) : ConnectivityManager.NetworkCallback(), KoinComponent { @@ -123,34 +121,30 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : override fun onAvailable(network: Network) { networkSet.add(network) val cap = connectivityManager.getNetworkCapabilities(network) - if (DEBUG) - Log.d( - LOG_TAG_CONNECTION, - "onAvailable: ${network.networkHandle}, $network, ${networkSet.size}, ${networkType(cap)}" - ) + Logger.d( + LOG_TAG_CONNECTION, + "onAvailable: ${network.networkHandle}, $network, ${networkSet.size}, ${networkType(cap)}" + ) handleNetworkChange() } override fun onLost(network: Network) { networkSet.remove(network) val cap = connectivityManager.getNetworkCapabilities(network) - if (DEBUG) - Log.d( - LOG_TAG_CONNECTION, - "onLost: ${network.networkHandle}, $network, ${networkSet.size}, ${networkType(cap)}" - ) + Logger.d( + LOG_TAG_CONNECTION, + "onLost: ${network.networkHandle}, $network, ${networkSet.size}, ${networkType(cap)}" + ) handleNetworkChange() } override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) { - if (DEBUG) - Log.d(LOG_TAG_CONNECTION, "onCapabilitiesChanged, ${network.networkHandle}, $network") + Logger.d(LOG_TAG_CONNECTION, "onCapabilitiesChanged, ${network.networkHandle}, $network") handleNetworkChange(isForceUpdate = false, TimeUnit.SECONDS.toMillis(3)) } override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) { - if (DEBUG) - Log.d(LOG_TAG_CONNECTION, "onLinkPropertiesChanged: ${network.networkHandle}, $network") + Logger.d(LOG_TAG_CONNECTION, "onLinkPropertiesChanged: ${network.networkHandle}, $network") handleNetworkChange(isForceUpdate = true, TimeUnit.SECONDS.toMillis(3)) } @@ -159,7 +153,7 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : * networks, or just one (the active network). */ fun onUserPreferenceChanged() { - if (DEBUG) Log.d(LOG_TAG_CONNECTION, "onUserPreferenceChanged") + Logger.d(LOG_TAG_CONNECTION, "onUserPreferenceChanged") handleNetworkChange(isForceUpdate = true) } @@ -169,18 +163,18 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : */ fun onVpnStart(context: Context) { if (this.serviceHandler != null) { - Log.w(LOG_TAG_CONNECTION, "connection monitor is already running") + Logger.w(LOG_TAG_CONNECTION, "connection monitor is already running") return } - Log.i(LOG_TAG_CONNECTION, "new vpn is created force update the network") + Logger.i(LOG_TAG_CONNECTION, "new vpn is created force update the network") connectivityManager = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager try { connectivityManager.registerNetworkCallback(networkRequest, this) } catch (e: Exception) { - Log.w(LOG_TAG_CONNECTION, "Exception while registering network callback", e) + Logger.w(LOG_TAG_CONNECTION, "Exception while registering network callback", e) networkListener.onNetworkRegistrationFailed() return } @@ -319,7 +313,7 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : val newNetworks = createNetworksSet(newActiveNetwork, opPrefs.networkSet) val isNewNetwork = hasDifference(currentNetworks, newNetworks) - Log.i( + Logger.i( LOG_TAG_CONNECTION, "Connected network: ${newActiveNetwork?.networkHandle} ${networkType(newActiveNetworkCap) }, new? $isNewNetwork, force? ${opPrefs.isForceUpdate}, test? ${opPrefs.testReachability}" @@ -340,7 +334,7 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : val newNetworks = createNetworksSet(newActiveNetwork, opPrefs.networkSet) val isNewNetwork = hasDifference(currentNetworks, newNetworks) - Log.i( + Logger.i( LOG_TAG_CONNECTION, "process message MESSAGE_AVAILABLE_NETWORK, ${currentNetworks}, ${newNetworks}; new? $isNewNetwork, force? ${opPrefs.isForceUpdate}, test? ${opPrefs.testReachability}" ) @@ -359,7 +353,7 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : // TODO: use currentNetworks instead of trackedIpv4Networks and trackedIpv6Networks // to determine whether to call onNetworkConnected or onNetworkDisconnected val sz = trackedIpv4Networks.size + trackedIpv6Networks.size - Log.i( + Logger.i( LOG_TAG_CONNECTION, "inform network change: ${sz}, all? $useActiveNetwork, metered? $isActiveNetworkMetered" ) @@ -381,13 +375,11 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : SystemClock.elapsedRealtime(), Collections.unmodifiableMap(dnsServers) ) - if (DEBUG) { - trackedIpv4Networks.forEach { - Log.d(LOG_TAG_CONNECTION, "inform4: ${it.network}, ${it.networkType}, $sz") - } - trackedIpv6Networks.forEach { - Log.d(LOG_TAG_CONNECTION, "inform6: ${it.network}, ${it.networkType}, $sz") - } + trackedIpv4Networks.forEach { + Logger.d(LOG_TAG_CONNECTION, "inform4: ${it.network}, ${it.networkType}, $sz") + } + trackedIpv6Networks.forEach { + Logger.d(LOG_TAG_CONNECTION, "inform6: ${it.network}, ${it.networkType}, $sz") } listener.onNetworkConnected(underlyingNetworks) } else { @@ -452,7 +444,7 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : } // set mtu to MIN_MTU (1280) if mtu4/mtu6 are less than MIN_MTU val mtu = max(min(minMtu4, minMtu6), MIN_MTU) - Log.i(LOG_TAG_CONNECTION, "mtu4: $minMtu4, mtu6: $minMtu6; final mtu: $mtu") + Logger.i(LOG_TAG_CONNECTION, "mtu4: $minMtu4, mtu6: $minMtu6; final mtu: $mtu") return mtu } @@ -489,13 +481,13 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : val lp = connectivityManager.getLinkProperties(network) if (lp == null) { - Log.i(LOG_TAG_CONNECTION, "skipping: $network; no link properties") + Logger.i(LOG_TAG_CONNECTION, "skipping: $network; no link properties") return@outer } val isActive = isNetworkSame(network, activeNetwork) if (isActive) { - if (DEBUG) Log.d(LOG_TAG_CONNECTION, "processing active network: $network") + Logger.d(LOG_TAG_CONNECTION, "processing active network: $network") } if (testReachability) { @@ -508,7 +500,7 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : val has6 = probeConnectivity(ip6probes, network, useIcmp) if (has4) trackedIpv4Networks.add(prop) if (has6) trackedIpv6Networks.add(prop) - Log.i(LOG_TAG_CONNECTION, "nw: has4? $has4, has6? $has6, $prop") + Logger.i(LOG_TAG_CONNECTION, "nw: has4? $has4, has6? $has6, $prop") if (has4 || has6) return@outer // else: fall-through to check reachability with network capabilities } @@ -538,18 +530,18 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : trackedIpv4Networks.add(prop) } - Log.i( + Logger.i( LOG_TAG_CONNECTION, "nw: default4? $hasDefaultRoute4, default6? $hasDefaultRoute6 for $prop" ) } else { - Log.i(LOG_TAG_CONNECTION, "skip: $network; no internet capability") + Logger.i(LOG_TAG_CONNECTION, "skip: $network; no internet capability") } } redoReachabilityIfNeeded(trackedIpv4Networks, trackedIpv6Networks, opPrefs) - Log.d( + Logger.d( LOG_TAG_CONNECTION, "repopulate v6: $trackedIpv6Networks,\nv4: $trackedIpv4Networks" ) @@ -564,7 +556,7 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : ) { if (ipv4.isEmpty() && ipv6.isEmpty()) { reachabilityCount++ - Log.i(LOG_TAG_CONNECTION, "redo reachability, try: $reachabilityCount") + Logger.i(LOG_TAG_CONNECTION, "redo reachability, try: $reachabilityCount") if (reachabilityCount > maxReachabilityCount) return val message = Message.obtain() // assume opPrefs is immutable @@ -573,7 +565,7 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : val delay = TimeUnit.SECONDS.toMillis(10 * reachabilityCount) this.sendMessageDelayed(message, delay) } else { - Log.d(LOG_TAG_CONNECTION, "reset reachability count, prev: $reachabilityCount") + Logger.d(LOG_TAG_CONNECTION, "reset reachability count, prev: $reachabilityCount") // reset the reachability count reachabilityCount = 0 } @@ -644,10 +636,10 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : } val networks = if (networkSet.isEmpty()) { - if (DEBUG) Log.d(LOG_TAG_CONNECTION, "networkSet is empty") + Logger.d(LOG_TAG_CONNECTION, "networkSet is empty") connectivityManager.allNetworks } else { - if (DEBUG) Log.d(LOG_TAG_CONNECTION, "networkSet size: ${networkSet.size}") + Logger.d(LOG_TAG_CONNECTION, "networkSet size: ${networkSet.size}") networkSet.toTypedArray() } @@ -702,10 +694,10 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : val yes = tcp80(nw, host) || udp53(nw, host) || tcp53(nw, host) - if (DEBUG) Log.d(LOG_TAG_CONNECTION, "$host isReachable on network($nw): $yes") + Logger.d(LOG_TAG_CONNECTION, "$host isReachable on network($nw): $yes") return yes } catch (e: Exception) { - Log.w(LOG_TAG_CONNECTION, "err isReachable: ${e.message}") + Logger.w(LOG_TAG_CONNECTION, "err isReachable: ${e.message}") } return false } @@ -727,10 +719,10 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : // InetAddress.getByName() will bind the socket to the default active network. val yes = InetAddress.getByName(host).isReachable(timeout) - if (DEBUG) Log.d(LOG_TAG_CONNECTION, "$host isReachable on network: $yes") + Logger.d(LOG_TAG_CONNECTION, "$host isReachable on network: $yes") return yes } catch (e: Exception) { - Log.w(LOG_TAG_CONNECTION, "err isReachable: ${e.message}") + Logger.w(LOG_TAG_CONNECTION, "err isReachable: ${e.message}") } return false } @@ -748,20 +740,19 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : socket.connect(s, timeout) val c = socket.isConnected val b = socket.isBound - if (DEBUG) - Log.d(LOG_TAG_CONNECTION, "tcpEcho80: $host, ${nw?.networkHandle}: $c, $b") + Logger.d(LOG_TAG_CONNECTION, "tcpEcho80: $host, ${nw?.networkHandle}: $c, $b") return true } catch (e: IOException) { - Log.w(LOG_TAG_CONNECTION, "err tcpEcho80: ${e.message}, ${e.cause}") + Logger.w(LOG_TAG_CONNECTION, "err tcpEcho80: ${e.message}, ${e.cause}") val cause: Throwable = e.cause ?: return false return (cause is ErrnoException && cause.errno == ECONNREFUSED) } catch (e: IllegalArgumentException) { - Log.w(LOG_TAG_CONNECTION, "err tcpEcho80: ${e.message}, ${e.cause}") + Logger.w(LOG_TAG_CONNECTION, "err tcpEcho80: ${e.message}, ${e.cause}") return false } catch (e: SecurityException) { - Log.w(LOG_TAG_CONNECTION, "err tcpEcho80: ${e.message}, ${e.cause}") + Logger.w(LOG_TAG_CONNECTION, "err tcpEcho80: ${e.message}, ${e.cause}") return false } finally { clos(socket) @@ -780,18 +771,17 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : socket.connect(s, timeout) val c = socket.isConnected val b = socket.isBound - if (DEBUG) - Log.d(LOG_TAG_CONNECTION, "tcpEcho53: $host, ${nw?.networkHandle}: $c, $b") + Logger.d(LOG_TAG_CONNECTION, "tcpEcho53: $host, ${nw?.networkHandle}: $c, $b") return true } catch (e: IOException) { - Log.w(LOG_TAG_CONNECTION, "err tcpEcho53: ${e.message}, ${e.cause}") + Logger.w(LOG_TAG_CONNECTION, "err tcpEcho53: ${e.message}, ${e.cause}") val cause: Throwable = e.cause ?: return false return (cause is ErrnoException && cause.errno == ECONNREFUSED) } catch (e: IllegalArgumentException) { - Log.w(LOG_TAG_CONNECTION, "err tcpEcho53: ${e.message}, ${e.cause}") + Logger.w(LOG_TAG_CONNECTION, "err tcpEcho53: ${e.message}, ${e.cause}") } catch (e: SecurityException) { - Log.w(LOG_TAG_CONNECTION, "err tcpEcho53: ${e.message}, ${e.cause}") + Logger.w(LOG_TAG_CONNECTION, "err tcpEcho53: ${e.message}, ${e.cause}") } finally { clos(socket) } @@ -811,17 +801,17 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : socket.connect(s) val c = socket.isConnected val b = socket.isBound - if (DEBUG) Log.d(LOG_TAG_CONNECTION, "udpEcho: $host, ${nw?.networkHandle}: $c, $b") + Logger.d(LOG_TAG_CONNECTION, "udpEcho: $host, ${nw?.networkHandle}: $c, $b") return true } catch (e: IOException) { - Log.w(LOG_TAG_CONNECTION, "err udpEcho: ${e.message}, ${e.cause}") + Logger.w(LOG_TAG_CONNECTION, "err udpEcho: ${e.message}, ${e.cause}") val cause: Throwable = e.cause ?: return false return (cause is ErrnoException && cause.errno == ECONNREFUSED) } catch (e: IllegalArgumentException) { - Log.w(LOG_TAG_CONNECTION, "err udpEcho: ${e.message}, ${e.cause}") + Logger.w(LOG_TAG_CONNECTION, "err udpEcho: ${e.message}, ${e.cause}") } catch (e: SecurityException) { - Log.w(LOG_TAG_CONNECTION, "err udpEcho: ${e.message}, ${e.cause}") + Logger.w(LOG_TAG_CONNECTION, "err udpEcho: ${e.message}, ${e.cause}") } finally { clos(socket) } diff --git a/app/src/main/java/com/celzero/bravedns/service/DomainRulesManager.kt b/app/src/main/java/com/celzero/bravedns/service/DomainRulesManager.kt index a92cc65ea..a48c3c9dc 100644 --- a/app/src/main/java/com/celzero/bravedns/service/DomainRulesManager.kt +++ b/app/src/main/java/com/celzero/bravedns/service/DomainRulesManager.kt @@ -15,8 +15,8 @@ */ package com.celzero.bravedns.service +import Logger.LOG_TAG_DNS import android.content.Context -import android.util.Log import android.util.Patterns import androidx.lifecycle.LiveData import backend.Backend @@ -24,7 +24,6 @@ import com.celzero.bravedns.R import com.celzero.bravedns.database.CustomDomain import com.celzero.bravedns.database.CustomDomainRepository import com.celzero.bravedns.util.Constants -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_DNS import org.koin.core.component.KoinComponent import org.koin.core.component.inject import java.net.MalformedURLException @@ -95,7 +94,7 @@ object DomainRulesManager : KoinComponent { } // update the cache with the domain and its status based on the domain type - private fun updateTrie(cd: CustomDomain) { + fun updateTrie(cd: CustomDomain) { val key = mkTrieKey(cd.domain, cd.uid) trie.set(key, cd.status.toString()) } @@ -308,7 +307,7 @@ object DomainRulesManager : KoinComponent { suspend fun deleteRulesByUid(uid: Int) { db.deleteRulesByUid(uid) val rulesDeleted = trie.delAll(uid.toString()) - Log.i(LOG_TAG_DNS, "rules deleted from trie for $uid: $rulesDeleted") + Logger.i(LOG_TAG_DNS, "rules deleted from trie for $uid: $rulesDeleted") clearTrustedMap(uid) } @@ -354,11 +353,11 @@ object DomainRulesManager : KoinComponent { private suspend fun rehydrateFromDB(uid: Int) { val doms = db.getDomainsByUID(uid) if (doms.isEmpty()) { - Log.w(LOG_TAG_DNS, "rehydrate: zero domains for uid: $uid in db") + Logger.w(LOG_TAG_DNS, "rehydrate: zero domains for uid: $uid in db") return } - Log.i(LOG_TAG_DNS, "rehydrate: rehydrating ${doms.size} domains for uid: $uid") + Logger.i(LOG_TAG_DNS, "rehydrate: rehydrating ${doms.size} domains for uid: $uid") // process longer domains first val selector: (String) -> Int = { str -> str.length } val desc = doms.sortedByDescending { selector(it.domain) } diff --git a/app/src/main/java/com/celzero/bravedns/service/EncryptedFileManager.kt b/app/src/main/java/com/celzero/bravedns/service/EncryptedFileManager.kt index 86f1b3a14..a52d9a9d0 100644 --- a/app/src/main/java/com/celzero/bravedns/service/EncryptedFileManager.kt +++ b/app/src/main/java/com/celzero/bravedns/service/EncryptedFileManager.kt @@ -16,12 +16,9 @@ package com.celzero.bravedns.service import android.content.Context -import android.util.Log import androidx.security.crypto.EncryptedFile import androidx.security.crypto.MasterKey -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.util.Constants.Companion.WIREGUARD_FOLDER_NAME -import com.celzero.bravedns.util.Logger import com.celzero.bravedns.wireguard.Config import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream @@ -39,7 +36,7 @@ object EncryptedFileManager { var config: Config? = null try { val dir = File(fileToRead) - Log.d(Logger.LOG_TAG_PROXY, "Encrypted File Read1: $fileToRead, ${dir.absolutePath}") + Logger.d(Logger.LOG_TAG_PROXY, "Encrypted File Read1: $fileToRead, ${dir.absolutePath}") val masterKey = MasterKey.Builder(ctx.applicationContext) .setKeyScheme(MasterKey.KeyScheme.AES256_GCM) @@ -53,9 +50,7 @@ object EncryptedFileManager { ) .build() - if (DEBUG) { - Log.d(Logger.LOG_TAG_PROXY, "Encrypted File Read: ${dir.absolutePath}, $fileToRead") - } + Logger.d(Logger.LOG_TAG_PROXY, "Encrypted File Read: ${dir.absolutePath}, $fileToRead") val inputStream = encryptedFile.openFileInput() val byteArrayOutputStream = ByteArrayOutputStream() var nextByte: Int = inputStream.read() @@ -73,7 +68,7 @@ object EncryptedFileManager { ist.close() byteArrayOutputStream.close() } catch (e: Exception) { - Log.e(Logger.LOG_TAG_PROXY, "Encrypted File Read: ${e.message}", e) + Logger.e(Logger.LOG_TAG_PROXY, "Encrypted File Read: ${e.message}", e) } return config @@ -99,7 +94,7 @@ object EncryptedFileManager { val inputStream = encryptedFile.openFileInput() content = inputStream.readBytes().toString(Charset.defaultCharset()) } catch (e: Exception) { - Log.e(Logger.LOG_TAG_PROXY, "Encrypted File Read: ${e.message}") + Logger.e(Logger.LOG_TAG_PROXY, "Encrypted File Read: ${e.message}") } return content } @@ -119,7 +114,7 @@ object EncryptedFileManager { val fileToWrite = File(dir, fileName) return write(ctx, cfg, fileToWrite) } catch (e: Exception) { - Log.e(Logger.LOG_TAG_PROXY, "Encrypted File Write: ${e.message}") + Logger.e(Logger.LOG_TAG_PROXY, "Encrypted File Write: ${e.message}") } return false } @@ -140,14 +135,14 @@ object EncryptedFileManager { val fileToWrite = File(dir, fileName) write(ctx, cfg, fileToWrite) } catch (e: Exception) { - Log.e(Logger.LOG_TAG_PROXY, "Encrypted File Write: ${e.message}") + Logger.e(Logger.LOG_TAG_PROXY, "Encrypted File Write: ${e.message}") } return false } fun write(ctx: Context, data: String, file: File): Boolean { try { - if (DEBUG) Log.d(Logger.LOG_TAG_PROXY, "write into $file") + Logger.d(Logger.LOG_TAG_PROXY, "write into $file") val masterKey = MasterKey.Builder(ctx.applicationContext) .setKeyScheme(MasterKey.KeyScheme.AES256_GCM) @@ -173,7 +168,7 @@ object EncryptedFileManager { } return true } catch (e: Exception) { - Log.e(Logger.LOG_TAG_PROXY, "Encrypted File Write: ${e.message}") + Logger.e(Logger.LOG_TAG_PROXY, "Encrypted File Write: ${e.message}") } return false } diff --git a/app/src/main/java/com/celzero/bravedns/service/FirewallManager.kt b/app/src/main/java/com/celzero/bravedns/service/FirewallManager.kt index c8b53ccce..14088e0df 100644 --- a/app/src/main/java/com/celzero/bravedns/service/FirewallManager.kt +++ b/app/src/main/java/com/celzero/bravedns/service/FirewallManager.kt @@ -15,12 +15,11 @@ */ package com.celzero.bravedns.service +import Logger.LOG_TAG_FIREWALL import android.app.KeyguardManager import android.content.Context -import android.util.Log import androidx.lifecycle.MutableLiveData import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.database.AppInfo import com.celzero.bravedns.database.AppInfoRepository import com.celzero.bravedns.service.FirewallManager.GlobalVariable.appInfos @@ -28,7 +27,6 @@ import com.celzero.bravedns.service.FirewallManager.GlobalVariable.appInfosLiveD import com.celzero.bravedns.service.FirewallManager.GlobalVariable.foregroundUids import com.celzero.bravedns.util.AndroidUidConfig import com.celzero.bravedns.util.Constants.Companion.RETHINK_PACKAGE -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_FIREWALL import com.celzero.bravedns.util.OrbotHelper import com.google.common.collect.HashMultimap import com.google.common.collect.ImmutableList @@ -461,7 +459,7 @@ object FirewallManager : KoinComponent { } // Delete the uninstalled apps from database val dbok = db.updateUid(olduid, uid, pkg) - Log.d("FirewallManager", "update: $pkg; $olduid -> $uid; c? $cacheok; db? $dbok") + Logger.d(LOG_TAG_FIREWALL, "update: $pkg; $olduid -> $uid; c? $cacheok; db? $dbok") informObservers() } @@ -475,7 +473,7 @@ object FirewallManager : KoinComponent { suspend fun load(): Int { val apps = db.getAppInfo() if (apps.isEmpty()) { - Log.w(LOG_TAG_FIREWALL, "no apps found in db, no app-based rules to load") + Logger.w(LOG_TAG_FIREWALL, "no apps found in db, no app-based rules to load") return 0 } @@ -488,7 +486,7 @@ object FirewallManager : KoinComponent { } fun untrackForegroundApps() { - Log.i( + Logger.i( LOG_TAG_FIREWALL, "launcher in the foreground, clear foreground uids: $foregroundUids" ) @@ -501,12 +499,15 @@ object FirewallManager : KoinComponent { val appInfo = appInfos[uid] if (appInfo.isNullOrEmpty()) { - Log.i(LOG_TAG_FIREWALL, "No such app $uid to update 'dis/allow' firewall rule") + Logger.i( + LOG_TAG_FIREWALL, + "No such app $uid to update 'dis/allow' firewall rule" + ) return@io } } val isAppUid = AndroidUidConfig.isUidAppRange(uid) - if (DEBUG) Log.d(LOG_TAG_FIREWALL, "app in foreground with uid? $isAppUid") + Logger.d(LOG_TAG_FIREWALL, "app in foreground with uid? $isAppUid") // Only track packages within app uid range. if (!isAppUid) return@io @@ -522,11 +523,10 @@ object FirewallManager : KoinComponent { // should be blocked. val locked = keyguardManager?.isKeyguardLocked == false val isForeground = foregroundUids.contains(uid) - if (DEBUG) - Log.d( - LOG_TAG_FIREWALL, - "is app $uid foreground? ${locked && isForeground}, isLocked? $locked, is available in foreground list? $isForeground" - ) + Logger.d( + LOG_TAG_FIREWALL, + "is app $uid foreground? ${locked && isForeground}, isLocked? $locked, is available in foreground list? $isForeground" + ) return locked && isForeground } @@ -540,7 +540,7 @@ object FirewallManager : KoinComponent { firewallStatus: FirewallStatus, connectionStatus: ConnectionStatus ) { - Log.i( + Logger.i( LOG_TAG_FIREWALL, "Apply firewall rule for uid: ${uid}, ${firewallStatus.name}, ${connectionStatus.name}" ) diff --git a/app/src/main/java/com/celzero/bravedns/service/IPTracker.kt b/app/src/main/java/com/celzero/bravedns/service/IPTracker.kt index a2f86078c..40ff8a593 100644 --- a/app/src/main/java/com/celzero/bravedns/service/IPTracker.kt +++ b/app/src/main/java/com/celzero/bravedns/service/IPTracker.kt @@ -15,8 +15,8 @@ */ package com.celzero.bravedns.service +import Logger.LOG_TAG_FIREWALL import android.content.Context -import android.util.Log import com.celzero.bravedns.R import com.celzero.bravedns.data.ConnTrackerMetaData import com.celzero.bravedns.data.ConnectionSummary @@ -27,7 +27,6 @@ import com.celzero.bravedns.database.RethinkLogRepository import com.celzero.bravedns.util.AndroidUidConfig import com.celzero.bravedns.util.Constants.Companion.INVALID_UID import com.celzero.bravedns.util.IPUtil -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_FIREWALL_LOG import com.celzero.bravedns.util.Utilities import com.celzero.bravedns.util.Utilities.getCountryCode import com.celzero.bravedns.util.Utilities.getFlag @@ -155,8 +154,8 @@ internal constructor( appNameForUidOrPackage(uid, pkgs[0]) } else { // For UNKNOWN or Non-App. val androidUidConfig = AndroidUidConfig.fromFileSystemUid(uid) - Log.i( - LOG_TAG_FIREWALL_LOG, + Logger.i( + LOG_TAG_FIREWALL, "android-uid for ${uid} is uid: ${androidUidConfig.uid}, n: ${androidUidConfig.name}" ) @@ -175,7 +174,7 @@ internal constructor( if (appName.isNullOrEmpty()) { val appInfo = Utilities.getApplicationInfo(ctx, packageName) ?: return "" - Log.i(LOG_TAG_FIREWALL_LOG, "app, $appName, not tracked by FirewallManager") + Logger.i(LOG_TAG_FIREWALL, "app, $appName, not tracked by FirewallManager") appName = ctx.packageManager.getApplicationLabel(appInfo).toString() } return appName diff --git a/app/src/main/java/com/celzero/bravedns/service/IpRulesManager.kt b/app/src/main/java/com/celzero/bravedns/service/IpRulesManager.kt index 3496d2246..bf8cae4ad 100644 --- a/app/src/main/java/com/celzero/bravedns/service/IpRulesManager.kt +++ b/app/src/main/java/com/celzero/bravedns/service/IpRulesManager.kt @@ -15,8 +15,8 @@ */ package com.celzero.bravedns.service +import Logger.LOG_TAG_FIREWALL import android.content.Context -import android.util.Log import androidx.lifecycle.LiveData import backend.Backend import com.celzero.bravedns.R @@ -24,8 +24,6 @@ import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.database.CustomIp import com.celzero.bravedns.database.CustomIpRepository import com.celzero.bravedns.util.Constants -import com.celzero.bravedns.util.Logger -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_FIREWALL import com.google.common.cache.Cache import com.google.common.cache.CacheBuilder import inet.ipaddr.AddressStringException @@ -94,7 +92,7 @@ object IpRulesManager : KoinComponent { } private fun logd(msg: String) { - if (DEBUG) Log.d(LOG_TAG_FIREWALL, msg) + Logger.d(LOG_TAG_FIREWALL, msg) } suspend fun load(): Long { @@ -110,7 +108,7 @@ object IpRulesManager : KoinComponent { logd("iptree.add($k, $v)") iptree.add(k, v) } catch (e: Exception) { - Log.e(LOG_TAG_FIREWALL, "err iptree.add($k, $v)", e) + Logger.e(LOG_TAG_FIREWALL, "err iptree.add($k, $v)", e) } } } @@ -169,7 +167,7 @@ object IpRulesManager : KoinComponent { } return IpRuleStatus.getStatus(items[2].toIntOrNull()) } catch (e: Exception) { - Log.e(LOG_TAG_FIREWALL, "err treeValStatus: ${e.message}") + Logger.e(LOG_TAG_FIREWALL, "err treeValStatus: ${e.message}") return IpRuleStatus.NONE } } @@ -183,7 +181,7 @@ object IpRulesManager : KoinComponent { } suspend fun removeIpRule(uid: Int, ipstr: String, port: Int) { - Log.i(LOG_TAG_FIREWALL, "ip rule, rmv: $ipstr for uid: $uid") + Logger.i(LOG_TAG_FIREWALL, "ip rule, rmv: $ipstr for uid: $uid") if (ipstr.isEmpty()) { return } @@ -197,7 +195,7 @@ object IpRulesManager : KoinComponent { } private suspend fun updateRule(uid: Int, ipaddr: String, port: Int, status: IpRuleStatus) { - Log.i(LOG_TAG_FIREWALL, "ip rule, update: $ipaddr for uid: $uid; status: ${status.name}") + Logger.i(LOG_TAG_FIREWALL, "ip rule, update: $ipaddr for uid: $uid; status: ${status.name}") // ipaddr is expected to be normalized val c = makeCustomIp(uid, ipaddr, port, status) db.update(c) @@ -367,7 +365,7 @@ object IpRulesManager : KoinComponent { val pair = hostAddr(ipStr) return normalize(pair.first) ?: "" } catch (ignored: NullPointerException) { - Log.e(Logger.LOG_TAG_VPN, "Invalid IP address added", ignored) + Logger.e(Logger.LOG_TAG_VPN, "Invalid IP address added", ignored) } return "" // empty ips mean its a port-only rule } @@ -415,7 +413,7 @@ object IpRulesManager : KoinComponent { } suspend fun addIpRule(uid: Int, ipstr: IPAddress, port: Int?, status: IpRuleStatus) { - Log.i( + Logger.i( LOG_TAG_FIREWALL, "ip rule, add rule for ($uid) ip: $ipstr, $port with status: ${status.name}" ) @@ -438,7 +436,7 @@ object IpRulesManager : KoinComponent { } resultsCache.invalidateAll() load() - Log.i(LOG_TAG_FIREWALL, "ip rules updated") + Logger.i(LOG_TAG_FIREWALL, "ip rules updated") } suspend fun replaceIpRule( @@ -452,7 +450,7 @@ object IpRulesManager : KoinComponent { val prevPort = pair.second val prevIpAddrStr = normalize(prevIpaddr) val newIpAddrStr = padAndNormalize(ipaddr) - Log.i( + Logger.i( LOG_TAG_FIREWALL, "ip rule, replace (${prevRule.uid}); ${prevIpAddrStr}:${prevPort}; new: $ipaddr:$port, ${newStatus.name}" ) @@ -553,7 +551,7 @@ object IpRulesManager : KoinComponent { ips.validate() ipNet = ips.address } catch (e: AddressStringException) { - Log.w(LOG_TAG_FIREWALL, "err: getIpNetPort, ${e.message}", e) + Logger.w(LOG_TAG_FIREWALL, "err: getIpNetPort, ${e.message}", e) } } else { ipNet = IPAddressString(h.first).address diff --git a/app/src/main/java/com/celzero/bravedns/service/PauseTimer.kt b/app/src/main/java/com/celzero/bravedns/service/PauseTimer.kt index 37b284942..6eac7e594 100644 --- a/app/src/main/java/com/celzero/bravedns/service/PauseTimer.kt +++ b/app/src/main/java/com/celzero/bravedns/service/PauseTimer.kt @@ -15,12 +15,11 @@ */ package com.celzero.bravedns.service -import android.util.Log +import Logger.LOG_TAG_UI +import Logger.LOG_TAG_VPN import androidx.lifecycle.MutableLiveData import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.util.Constants.Companion.INIT_TIME_MS -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_UI -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_VPN import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay @@ -42,7 +41,7 @@ object PauseTimer { val PAUSE_VPN_EXTRA_MILLIS = TimeUnit.MINUTES.toMillis(1) fun start(durationMs: Long) { - if (DEBUG) Log.d(LOG_TAG_UI, "timer started, duration: $durationMs") + Logger.d(LOG_TAG_UI, "timer started, duration: $durationMs") io { try { setCountdown(durationMs) @@ -51,7 +50,7 @@ object PauseTimer { addCountdown(-COUNT_DOWN_INTERVAL) } } finally { - if (DEBUG) Log.d(LOG_TAG_VPN, "pause timer complete") + Logger.d(LOG_TAG_VPN, "pause timer complete") VpnController.resumeApp() setCountdown(INIT_TIME_MS) } diff --git a/app/src/main/java/com/celzero/bravedns/service/RethinkBlocklistManager.kt b/app/src/main/java/com/celzero/bravedns/service/RethinkBlocklistManager.kt index a7f6bb985..3757f3068 100644 --- a/app/src/main/java/com/celzero/bravedns/service/RethinkBlocklistManager.kt +++ b/app/src/main/java/com/celzero/bravedns/service/RethinkBlocklistManager.kt @@ -15,12 +15,12 @@ */ package com.celzero.bravedns.service +import Logger.LOG_TAG_DNS +import Logger.LOG_TAG_VPN import android.content.Context -import android.util.Log import backend.Backend import backend.RDNS import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.data.FileTag import com.celzero.bravedns.data.FileTagDeserializer import com.celzero.bravedns.database.LocalBlocklistPacksMap @@ -34,7 +34,6 @@ import com.celzero.bravedns.database.RethinkRemoteFileTagRepository import com.celzero.bravedns.util.Constants.Companion.LOCAL_BLOCKLIST_DOWNLOAD_FOLDER_NAME import com.celzero.bravedns.util.Constants.Companion.ONDEVICE_BLOCKLIST_FILE_TAG import com.celzero.bravedns.util.Constants.Companion.REMOTE_BLOCKLIST_DOWNLOAD_FOLDER_NAME -import com.celzero.bravedns.util.Logger import com.celzero.bravedns.util.Utilities import com.google.common.collect.HashMultimap import com.google.common.collect.Multimap @@ -186,11 +185,10 @@ object RethinkBlocklistManager : KoinComponent { ) } ) - Log.i(Logger.LOG_TAG_DNS, "New Local blocklist files inserted into database") + Logger.i(LOG_TAG_DNS, "New Local blocklist files inserted into database") return true } catch (ioException: IOException) { - Log.e( - Logger.LOG_TAG_DNS, + Logger.e(LOG_TAG_DNS, "Failure reading json file, blocklist type: remote, timestamp: $timestamp", ioException ) @@ -245,8 +243,8 @@ object RethinkBlocklistManager : KoinComponent { } dbFileTagRemote.add(r) // if (DEBUG) Log.d(Logger.LOG_TAG_DNS, "Remote file tag: $r") - Log.i( - Logger.LOG_TAG_DNS, + Logger.i( + LOG_TAG_DNS, "Remote file tag: ${r.group}, ${r.pack}, ${r.simpleTagId}, ${r.level}, ${r.value}, ${r.entries}, ${r.isSelected}, ${r.show}, ${r.subg}, ${r.uname}, ${r.url}, ${r.vname}" ) } @@ -270,11 +268,10 @@ object RethinkBlocklistManager : KoinComponent { ) } ) - Log.i(Logger.LOG_TAG_DNS, "New Remote blocklist files inserted into database") + Logger.i(LOG_TAG_DNS, "New Remote blocklist files inserted into database") return true } catch (ioException: IOException) { - Log.e( - Logger.LOG_TAG_DNS, + Logger.e(LOG_TAG_DNS, "Failure reading json file, blocklist type: remote, timestamp: $timestamp", ioException ) @@ -373,14 +370,13 @@ object RethinkBlocklistManager : KoinComponent { suspend fun getStamp(fileValues: Set, type: RethinkBlocklistType): String { return try { val flags = convertListToCsv(fileValues) - if (DEBUG) - Log.d( - Logger.LOG_TAG_VPN, + Logger.d( + LOG_TAG_VPN, "${type.name} flags: $flags, ${getRDNS(type)?.flagsToStamp(flags, Backend.EB32)}" ) getRDNS(type)?.flagsToStamp(flags, Backend.EB32) ?: "" } catch (e: java.lang.Exception) { - Log.e(Logger.LOG_TAG_VPN, "err stamp2tags: ${e.message}, $e") + Logger.e(LOG_TAG_VPN, "err stamp2tags: ${e.message}, $e") "" } } @@ -389,7 +385,7 @@ object RethinkBlocklistManager : KoinComponent { return try { convertCsvToList(getRDNS(type)?.stampToFlags(stamp)) } catch (e: Exception) { - Log.e(Logger.LOG_TAG_VPN, "err tags2stamp: ${e.message}, $e") + Logger.e(LOG_TAG_VPN, "err tags2stamp: ${e.message}, $e") setOf() } } diff --git a/app/src/main/java/com/celzero/bravedns/service/VpnController.kt b/app/src/main/java/com/celzero/bravedns/service/VpnController.kt index 95547bcc9..48efb9432 100644 --- a/app/src/main/java/com/celzero/bravedns/service/VpnController.kt +++ b/app/src/main/java/com/celzero/bravedns/service/VpnController.kt @@ -16,10 +16,10 @@ */ package com.celzero.bravedns.service +import Logger.LOG_TAG_VPN import android.content.Context import android.content.Intent import android.os.SystemClock -import android.util.Log import androidx.core.content.ContextCompat import androidx.lifecycle.MutableLiveData import backend.RDNS @@ -27,7 +27,6 @@ import backend.Stats import com.celzero.bravedns.R import com.celzero.bravedns.service.BraveVPNService.Companion.FAIL_OPEN_ON_NO_NETWORK import com.celzero.bravedns.util.Constants.Companion.INVALID_UID -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_VPN import com.celzero.bravedns.util.Utilities import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -122,7 +121,7 @@ object VpnController : KoinComponent { fun start(context: Context) { // if the tunnel has the go-adapter then there's nothing to do if (hasTunnel()) { - Log.w(LOG_TAG_VPN, "braveVPNService is already on, resending vpn enabled state") + Logger.w(LOG_TAG_VPN, "braveVPNService is already on, resending vpn enabled state") return } // else: resend/send the start-command to the vpn service which handles both false-start @@ -136,11 +135,11 @@ object VpnController : KoinComponent { ContextCompat.startForegroundService(context, startServiceIntent) onConnectionStateChanged(connectionState) - Log.i(LOG_TAG_VPN, "VPNController - Start(Synchronized) executed - $context") + Logger.i(LOG_TAG_VPN, "VPNController - Start(Synchronized) executed - $context") } fun stop(context: Context) { - Log.i(LOG_TAG_VPN, "VPN Controller stop with context: $context") + Logger.i(LOG_TAG_VPN, "VPN Controller stop with context: $context") connectionState = null onConnectionStateChanged(connectionState) braveVpnService?.signalStopService(userInitiated = true) @@ -231,7 +230,7 @@ object VpnController : KoinComponent { fun protocols(): String { val ipv4 = protocol.first val ipv6 = protocol.second - Log.d(LOG_TAG_VPN, "protocols - ipv4: $ipv4, ipv6: $ipv6") + Logger.d(LOG_TAG_VPN, "protocols - ipv4: $ipv4, ipv6: $ipv6") return if (ipv4 && ipv6) { "IPv4, IPv6" } else if (ipv6) { @@ -250,7 +249,7 @@ object VpnController : KoinComponent { fun updateProtocol(proto: Pair) { if (!proto.first && !proto.second) { - Log.i(LOG_TAG_VPN, "both v4 and v6 false, setting $FAIL_OPEN_ON_NO_NETWORK") + Logger.i(LOG_TAG_VPN, "both v4 and v6 false, setting $FAIL_OPEN_ON_NO_NETWORK") protocol = Pair(FAIL_OPEN_ON_NO_NETWORK, FAIL_OPEN_ON_NO_NETWORK) return } diff --git a/app/src/main/java/com/celzero/bravedns/util/IPUtil.kt b/app/src/main/java/com/celzero/bravedns/util/IPUtil.kt index 35db41847..24624643f 100644 --- a/app/src/main/java/com/celzero/bravedns/util/IPUtil.kt +++ b/app/src/main/java/com/celzero/bravedns/util/IPUtil.kt @@ -15,7 +15,7 @@ */ package com.celzero.bravedns.util -import android.util.Log +import Logger.LOG_TAG_VPN import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import inet.ipaddr.IPAddress import inet.ipaddr.IPAddressString @@ -122,11 +122,7 @@ class IPUtil { if (start == null || end == null) return null val listResult: MutableList = ArrayList() - if (DEBUG) - Log.d( - Logger.LOG_TAG_VPN, - "toCIDR(" + start.hostAddress + "," + end.hostAddress + ")" - ) + Logger.d(LOG_TAG_VPN, "toCIDR(" + start.hostAddress + "," + end.hostAddress + ")") var from: Long = inet2long(start) val to: Long = inet2long(end) while (to >= from) { @@ -142,7 +138,7 @@ class IPUtil { from += 2.0.pow((32 - prefix).toDouble()).toLong() } if (DEBUG) { - for (cidr in listResult) Log.d(Logger.LOG_TAG_VPN, cidr.toString()) + for (cidr in listResult) Logger.d(LOG_TAG_VPN, cidr.toString()) } return listResult } @@ -195,7 +191,7 @@ class IPUtil { address = InetAddress.getByName(ip) this.prefix = prefix } catch (ex: UnknownHostException) { - Log.e(Logger.LOG_TAG_VPN, "error parsing CIDR, $ip, $prefix, $ex") + Logger.e(LOG_TAG_VPN, "error parsing CIDR, $ip, $prefix, $ex") } } diff --git a/app/src/main/java/com/celzero/bravedns/util/Logger.kt b/app/src/main/java/com/celzero/bravedns/util/Logger.kt index 976d2bcc6..d53a2870f 100644 --- a/app/src/main/java/com/celzero/bravedns/util/Logger.kt +++ b/app/src/main/java/com/celzero/bravedns/util/Logger.kt @@ -13,55 +13,77 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.celzero.bravedns.util - import android.util.Log import com.celzero.bravedns.service.PersistentState import org.koin.core.component.KoinComponent import org.koin.core.component.inject -class Logger : KoinComponent { +object Logger : KoinComponent { private val persistentState by inject() - private var configuredLogLevel = persistentState.goLoggerLevel + private var logLevel = persistentState.goLoggerLevel - companion object { - const val LOG_TAG_APP_UPDATE = "NonStoreAppUpdater" - const val LOG_TAG_FIREWALL_LOG = "FirewallLogs" - const val LOG_TAG_DNS_LOG = "DnsLogs" - const val LOG_TAG_VPN = "VpnLifecycle" - const val LOG_TAG_CONNECTION = "ConnectivityEvents" - const val LOG_TAG_DNS = "DnsManager" - const val LOG_TAG_FIREWALL = "FirewallManager" - const val LOG_BATCH_LOGGER = "BatchLogger" - const val LOG_TAG_APP_DB = "AppDatabase" - const val LOG_TAG_DOWNLOAD = "DownloadManager" - const val LOG_TAG_UI = "ActivityManager" - const val LOG_TAG_SCHEDULER = "JobScheduler" - const val LOG_TAG_BACKUP_RESTORE = "BackupRestore" - const val LOG_PROVIDER = "BlocklistProvider" - const val LOG_TAG_PROXY = "ProxyLogs" - } + const val LOG_TAG_APP_UPDATE = "NonStoreAppUpdater" + const val LOG_TAG_VPN = "VpnLifecycle" + const val LOG_TAG_CONNECTION = "ConnectivityEvents" + const val LOG_TAG_DNS = "DnsManager" + const val LOG_TAG_FIREWALL = "FirewallManager" + const val LOG_BATCH_LOGGER = "BatchLogger" + const val LOG_TAG_APP_DB = "AppDatabase" + const val LOG_TAG_DOWNLOAD = "DownloadManager" + const val LOG_TAG_UI = "ActivityManager" + const val LOG_TAG_SCHEDULER = "JobScheduler" + const val LOG_TAG_BACKUP_RESTORE = "BackupRestore" + const val LOG_PROVIDER = "BlocklistProvider" + const val LOG_TAG_PROXY = "ProxyLogs" + const val LOG_QR_CODE = "QrCodeFromFileScanner" enum class LoggerType(val id: Int) { VERBOSE(0), - INFO(1), - DEBUG(2), + DEBUG(1), + INFO(2), WARN(3), ERROR(4) } - fun log(logger: String, message: String, type: LoggerType, e: Exception? = null) { + fun v(tag: String, message: String) { + log(tag, message, LoggerType.VERBOSE) + } + + fun d(tag: String, message: String) { + log(tag, message, LoggerType.DEBUG) + } + + fun i(tag: String, message: String) { + log(tag, message, LoggerType.INFO) + } + + fun w(tag: String, message: String, e: Exception? = null) { + log(tag, message, LoggerType.WARN, e) + } + + fun e(tag: String, message: String, e: Exception? = null) { + log(tag, message, LoggerType.ERROR, e) + } + + fun updateConfigLevel(level: Long) { + logLevel = level + } + + fun throwableToException(throwable: Throwable): Exception { + return if (throwable is Exception) { + throwable + } else { + Exception(throwable) + } + } + + private fun log(tag: String, message: String, type: LoggerType, e: Exception? = null) { when (type) { - LoggerType.VERBOSE -> - if (configuredLogLevel <= LoggerType.VERBOSE.id) Log.v(logger, message, e) - LoggerType.INFO -> - if (configuredLogLevel <= LoggerType.INFO.id) Log.i(logger, message, e) - LoggerType.DEBUG -> - if (configuredLogLevel <= LoggerType.DEBUG.id) Log.d(logger, message, e) - LoggerType.WARN -> - if (configuredLogLevel <= LoggerType.WARN.id) Log.w(logger, message, e) - LoggerType.ERROR -> - if (configuredLogLevel <= LoggerType.ERROR.id) Log.e(logger, message, e) + LoggerType.VERBOSE -> if (logLevel <= LoggerType.VERBOSE.id) Log.v(tag, message) + LoggerType.DEBUG -> if (logLevel <= LoggerType.DEBUG.id) Log.d(tag, message) + LoggerType.INFO -> if (logLevel <= LoggerType.INFO.id) Log.i(tag, message) + LoggerType.WARN -> if (logLevel <= LoggerType.WARN.id) Log.w(tag, message, e) + LoggerType.ERROR -> if (logLevel <= LoggerType.ERROR.id) Log.e(tag, message, e) } } } diff --git a/app/src/main/java/com/celzero/bravedns/util/NetLogBatcher.kt b/app/src/main/java/com/celzero/bravedns/util/NetLogBatcher.kt index 7b7206ab9..729b8a9c9 100644 --- a/app/src/main/java/com/celzero/bravedns/util/NetLogBatcher.kt +++ b/app/src/main/java/com/celzero/bravedns/util/NetLogBatcher.kt @@ -16,9 +16,7 @@ package com.celzero.bravedns.util -import android.util.Log -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG -import com.celzero.bravedns.util.Logger.Companion.LOG_BATCH_LOGGER +import Logger.LOG_BATCH_LOGGER import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.DelicateCoroutinesApi @@ -74,7 +72,7 @@ class NetLogBatcher( private var updates = mutableListOf() fun begin(scope: CoroutineScope) { - Log.i(LOG_BATCH_LOGGER, "begin") + Logger.i(LOG_BATCH_LOGGER, "begin") // launch suspend fns sig and consume asynchronously scope.async { sig() } scope.async { consumeAdd() } @@ -93,7 +91,7 @@ class NetLogBatcher( signal.close() buffersCh.close() updatesCh.close() - Log.i(LOG_BATCH_LOGGER, "end") + Logger.i(LOG_BATCH_LOGGER, "end") } } } @@ -121,12 +119,12 @@ class NetLogBatcher( updates = mutableListOf() updatesCh.send(u) - if (DEBUG) Log.d(LOG_BATCH_LOGGER, "transfer and swap (${lsn}) u: ${u.size}, b: ${b.size}") + Logger.d(LOG_BATCH_LOGGER, "transfer and swap (${lsn}) u: ${u.size}, b: ${b.size}") lsn = (lsn + 1) } - suspend fun add(payload: T) = + suspend fun add(payload: T) = withContext(looper + nprod) { batches.add(payload) // if the batch size is met, dispatch it to the consumer @@ -152,26 +150,25 @@ class NetLogBatcher( // consume all signals for (tracklsn in signal) { if (tracklsn < lsn) { - if (DEBUG) Log.d(LOG_BATCH_LOGGER, "dup signal skip $tracklsn") + Logger.d(LOG_BATCH_LOGGER, "dup signal skip $tracklsn") continue } // do not honor the signal for 'l' if a[l] is empty // this can happen if the signal for 'l' is processed // after the fact that 'l' has been swapped out by 'batch' if (batches.size <= 0 && updates.size <= 0) { - if (DEBUG) Log.d(LOG_BATCH_LOGGER, "signal continue") + Logger.d(LOG_BATCH_LOGGER, "signal continue") continue } else { - if (DEBUG) Log.d(LOG_BATCH_LOGGER, "signal sleep $waitms ms") + Logger.d(LOG_BATCH_LOGGER, "signal sleep $waitms ms") } // wait for 'batch' to dispatch delay(waitms) - if (DEBUG) - Log.d( - LOG_BATCH_LOGGER, - "signal wait over, sz(b: ${batches.size}, u: ${updates.size}) / cur-buf(${lsn})" - ) + Logger.d( + LOG_BATCH_LOGGER, + "signal wait over, sz(b: ${batches.size}, u: ${updates.size}) / cur-buf(${lsn})" + ) // 'l' is the current buffer, that is, 'l == i', // and 'batch' hasn't dispatched it, diff --git a/app/src/main/java/com/celzero/bravedns/util/OrbotHelper.kt b/app/src/main/java/com/celzero/bravedns/util/OrbotHelper.kt index 2f37b1fb4..2bf3653b4 100644 --- a/app/src/main/java/com/celzero/bravedns/util/OrbotHelper.kt +++ b/app/src/main/java/com/celzero/bravedns/util/OrbotHelper.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.util +import Logger.LOG_TAG_VPN import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent @@ -27,13 +28,11 @@ import android.content.pm.PackageManager import android.net.Uri import android.net.VpnService import android.text.TextUtils -import android.util.Log import android.widget.Toast import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat import androidx.core.net.toUri import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.data.AppConfig import com.celzero.bravedns.database.ProxyEndpoint import com.celzero.bravedns.receiver.NotificationActionReceiver @@ -42,7 +41,6 @@ import com.celzero.bravedns.service.ProxyManager import com.celzero.bravedns.ui.HomeScreenActivity import com.celzero.bravedns.util.Constants.Companion.HTTP_PROXY_PORT import com.celzero.bravedns.util.Constants.Companion.SOCKS_DEFAULT_PORT -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_VPN import com.celzero.bravedns.util.Utilities.getActivityPendingIntent import com.celzero.bravedns.util.Utilities.getBroadcastPendingIntent import com.celzero.bravedns.util.Utilities.isAtleastO @@ -50,13 +48,13 @@ import com.celzero.bravedns.util.Utilities.isAtleastT import com.celzero.bravedns.util.Utilities.isFdroidFlavour import com.celzero.bravedns.util.Utilities.isPlayStoreFlavour import com.celzero.bravedns.util.Utilities.isValidPort +import java.net.URI +import java.util.concurrent.TimeUnit import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -import java.net.URI -import java.util.concurrent.TimeUnit /** * One-click Orbot setup. @@ -198,7 +196,7 @@ class OrbotHelper( ) context.sendBroadcast(intent) waitForOrbot() - if (DEBUG) Log.d(LOG_TAG_VPN, "request orbot start by broadcast") + Logger.d(LOG_TAG_VPN, "request orbot start by broadcast") } /** @@ -209,36 +207,35 @@ class OrbotHelper( private val orbotStatusReceiver: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { - Log.i(LOG_TAG_VPN, "received status from orbot, action: ${intent.action}") + Logger.i(LOG_TAG_VPN, "received status from orbot, action: ${intent.action}") if (ACTION_STATUS != intent.action) { return } val status = intent.getStringExtra(EXTRA_STATUS) - if (DEBUG) - Log.d( - LOG_TAG_VPN, - "received status from orbot, action: ${intent.action}, status: $status" - ) + Logger.d( + LOG_TAG_VPN, + "received status from orbot, action: ${intent.action}, status: $status" + ) when (status) { STATUS_ON -> { - Log.i(LOG_TAG_VPN, "Orbot is ON, update the proxy data") + Logger.i(LOG_TAG_VPN, "Orbot is ON, update the proxy data") isResponseReceivedFromOrbot = true updateOrbotProxyData(intent) setOrbotMode() } STATUS_OFF -> { - Log.i(LOG_TAG_VPN, "Orbot is OFF, retry or stop the Orbot") + Logger.i(LOG_TAG_VPN, "Orbot is OFF, retry or stop the Orbot") io { waitForOrbot() } unregisterReceiver() } STATUS_STARTING -> { - Log.i(LOG_TAG_VPN, "Orbot is STARTING, update the proxy data") + Logger.i(LOG_TAG_VPN, "Orbot is STARTING, update the proxy data") updateOrbotProxyData(intent) } STATUS_STOPPING -> { - Log.i(LOG_TAG_VPN, "Orbot is STOPPING, stop the Proxy") + Logger.i(LOG_TAG_VPN, "Orbot is STOPPING, stop the Proxy") updateOrbotProxyData(intent) stopOrbot(isInteractive = false) } @@ -264,7 +261,7 @@ class OrbotHelper( appConfig.removeAllProxies() persistentState.orbotConnectionStatus.postValue(false) context.sendBroadcast(getOrbotStopIntent()) - Log.i(LOG_TAG_VPN, "stop orbot, remove from proxy") + Logger.i(LOG_TAG_VPN, "stop orbot, remove from proxy") } /** @@ -337,7 +334,7 @@ class OrbotHelper( private fun setOrbotMode() { io { - Log.i(LOG_TAG_VPN, "Initiate orbot start with type: $selectedProxyType") + Logger.i(LOG_TAG_VPN, "Initiate orbot start with type: $selectedProxyType") if (isTypeSocks5() && handleOrbotSocks5Update()) { appConfig.addProxy(AppConfig.ProxyType.SOCKS5, AppConfig.ProxyProvider.ORBOT) @@ -372,7 +369,7 @@ class OrbotHelper( appConfig.updateOrbotProxy(proxyEndpoint) true } else { - Log.w(LOG_TAG_VPN, "Error inserting value in proxy database") + Logger.w(LOG_TAG_VPN, "Error inserting value in proxy database") false } } @@ -387,7 +384,7 @@ class OrbotHelper( appConfig.updateOrbotHttpProxy(proxyEndpoint) true } else { - Log.w(LOG_TAG_VPN, "could not setup Orbot http proxy with ${httpsIp}:${httpsPort}") + Logger.w(LOG_TAG_VPN, "could not setup Orbot http proxy with ${httpsIp}:${httpsPort}") false } } @@ -409,7 +406,7 @@ class OrbotHelper( port: Int? ): ProxyEndpoint? { if (ip.isNullOrEmpty() || port == null || !isValidPort(port)) { - Log.w(LOG_TAG_VPN, "cannot construct proxy with values ip: $ip, port: $port") + Logger.w(LOG_TAG_VPN, "cannot construct proxy with values ip: $ip, port: $port") return null } @@ -439,11 +436,10 @@ class OrbotHelper( httpsIp = data?.getStringExtra(EXTRA_HTTP_PROXY_HOST) dnsPort = data?.getIntExtra(EXTRA_DNS_PORT, 0) - if (DEBUG) - Log.d( - LOG_TAG_VPN, - "OrbotHelper: new val socks5:$socks5Ip($socks5Port), http: $httpsIp($httpsPort), dns: $dnsPort" - ) + Logger.d( + LOG_TAG_VPN, + "OrbotHelper: new val socks5:$socks5Ip($socks5Port), http: $httpsIp($httpsPort), dns: $dnsPort" + ) } /** @@ -453,7 +449,7 @@ class OrbotHelper( private suspend fun waitForOrbot() { io { delay(TimeUnit.SECONDS.toMillis(15L)) - Log.i(LOG_TAG_VPN, "after timeout, isOrbotUp? $isResponseReceivedFromOrbot") + Logger.i(LOG_TAG_VPN, "after timeout, isOrbotUp? $isResponseReceivedFromOrbot") // Execute a task in the background thread after 15 sec. // If there is no response for the broadcast from the Orbot, @@ -467,7 +463,7 @@ class OrbotHelper( retryCount-- if (retryCount > 0) { - Log.i(LOG_TAG_VPN, "retrying orbot start") + Logger.i(LOG_TAG_VPN, "retrying orbot start") startOrbot(selectedProxyType) } else { uiCtx { @@ -482,7 +478,7 @@ class OrbotHelper( try { context.unregisterReceiver(orbotStatusReceiver) } catch (e: IllegalArgumentException) { - Log.w(LOG_TAG_VPN, "orbot unregister not needed: ${e.message}") + Logger.w(LOG_TAG_VPN, "orbot unregister not needed: ${e.message}") } } @@ -497,7 +493,7 @@ class OrbotHelper( openOrbotAppInfo() } } catch (e: ActivityNotFoundException) { - Log.w(LOG_TAG_VPN, "Failure calling app info: ${e.message}", e) + Logger.w(LOG_TAG_VPN, "Failure calling app info: ${e.message}", e) } } @@ -514,7 +510,7 @@ class OrbotHelper( intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(intent) } catch (e: ActivityNotFoundException) { - Log.w(LOG_TAG_VPN, "Failure calling app info: ${e.message}", e) + Logger.w(LOG_TAG_VPN, "Failure calling app info: ${e.message}", e) } } diff --git a/app/src/main/java/com/celzero/bravedns/util/Utilities.kt b/app/src/main/java/com/celzero/bravedns/util/Utilities.kt index cdebf3dae..5b94e8aa8 100644 --- a/app/src/main/java/com/celzero/bravedns/util/Utilities.kt +++ b/app/src/main/java/com/celzero/bravedns/util/Utilities.kt @@ -15,6 +15,10 @@ */ package com.celzero.bravedns.util +import Logger.LOG_TAG_APP_DB +import Logger.LOG_TAG_DOWNLOAD +import Logger.LOG_TAG_FIREWALL +import Logger.LOG_TAG_VPN import android.accessibilityservice.AccessibilityService import android.accessibilityservice.AccessibilityServiceInfo import android.app.PendingIntent @@ -33,7 +37,6 @@ import android.os.Build import android.provider.Settings import android.text.TextUtils import android.text.TextUtils.SimpleStringSplitter -import android.util.Log import android.view.accessibility.AccessibilityManager import android.widget.Toast import androidx.appcompat.content.res.AppCompatResources @@ -41,7 +44,6 @@ import androidx.core.content.getSystemService import androidx.lifecycle.LifecycleCoroutineScope import com.celzero.bravedns.BuildConfig import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.database.AppInfoRepository.Companion.NO_PACKAGE import com.celzero.bravedns.net.doh.CountryMap import com.celzero.bravedns.service.BraveVPNService @@ -56,11 +58,6 @@ import com.celzero.bravedns.util.Constants.Companion.MISSING_UID import com.celzero.bravedns.util.Constants.Companion.REMOTE_BLOCKLIST_DOWNLOAD_FOLDER_NAME import com.celzero.bravedns.util.Constants.Companion.UNSPECIFIED_IP_IPV4 import com.celzero.bravedns.util.Constants.Companion.UNSPECIFIED_IP_IPV6 -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_APP_DB -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_DNS -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_DOWNLOAD -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_FIREWALL -import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_VPN import com.google.common.base.CharMatcher import com.google.common.net.InternetDomainName import com.google.gson.JsonParser @@ -125,7 +122,7 @@ object Utilities { am.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK) for (enabledService in enabledServices) { val enabledServiceInfo: ServiceInfo = enabledService.resolveInfo.serviceInfo - Log.i(LOG_TAG_VPN, "Accessibility enabled check for: ${enabledServiceInfo.packageName}") + Logger.i(LOG_TAG_VPN, "Accessibility enabled check for: ${enabledServiceInfo.packageName}") if ( enabledServiceInfo.packageName == context.packageName && enabledServiceInfo.name == service.name @@ -133,7 +130,7 @@ object Utilities { return true } } - Log.e( + Logger.e( LOG_TAG_VPN, "Accessibility failure, ${context.packageName}, ${service.name}, return size: ${enabledServices.count()}" ) @@ -157,8 +154,7 @@ object Utilities { val componentNameString = colonSplitter.next() val enabledService = ComponentName.unflattenFromString(componentNameString) if (expectedComponentName == enabledService) { - if (DEBUG) - Log.i( + Logger.i( LOG_TAG_VPN, "SettingsSecure accessibility enabled for: ${expectedComponentName.packageName}" ) @@ -166,13 +162,13 @@ object Utilities { } } } catch (e: Settings.SettingNotFoundException) { - Log.e( + Logger.e( LOG_TAG_VPN, "isAccessibilityServiceEnabled Exception on isAccessibilityServiceEnabledViaSettingsSecure() ${e.message}", e ) } - Log.w(LOG_TAG_VPN, "Accessibility service not enabled via Settings Secure") + Logger.w(LOG_TAG_VPN, "Accessibility service not enabled via Settings Secure") return isAccessibilityServiceEnabled(context, accessibilityService) } @@ -196,7 +192,7 @@ object Utilities { try { countryMap = CountryMap(context.assets) } catch (e: IOException) { - Log.e(LOG_TAG_VPN, "Failure fetching country map ${e.message}", e) + Logger.e(LOG_TAG_VPN, "Failure fetching country map ${e.message}", e) } } @@ -290,13 +286,13 @@ object Utilities { try { Toast.makeText(context, message, toastLength).show() } catch (e: IllegalStateException) { - Log.w(LOG_TAG_VPN, "toast err: ${e.message}") + Logger.w(LOG_TAG_VPN, "toast err: ${e.message}") } catch (e: IllegalAccessException) { - Log.w(LOG_TAG_VPN, "toast err: ${e.message}") + Logger.w(LOG_TAG_VPN, "toast err: ${e.message}") } catch (e: IOException) { - Log.w(LOG_TAG_VPN, "toast err: ${e.message}") + Logger.w(LOG_TAG_VPN, "toast err: ${e.message}") } catch (e: Exception) { - Log.w(LOG_TAG_VPN, "toast err: ${e.message}") + Logger.w(LOG_TAG_VPN, "toast err: ${e.message}") } } @@ -313,7 +309,7 @@ object Utilities { pm.getPackageInfo(pi, PackageManager.GET_META_DATA) } } catch (e: PackageManager.NameNotFoundException) { - Log.w(LOG_TAG_APP_DB, "Application not available $pi" + e.message, e) + Logger.w(LOG_TAG_APP_DB, "Application not available $pi" + e.message, e) } return metadata } @@ -336,7 +332,7 @@ object Utilities { // assign value as true as the package name not found, should not be the // case but some devices seems to return package not found immediately // after install - Log.w(LOG_TAG_APP_DB, "app not found ${ctx.packageName}" + e.message, e) + Logger.w(LOG_TAG_APP_DB, "app not found ${ctx.packageName}" + e.message, e) return true } } @@ -350,7 +346,7 @@ object Utilities { src.copyTo(dest, true) } catch (e: Exception) { // Throws NoSuchFileException, IOException - Log.e(LOG_TAG_DOWNLOAD, "Error copying file ${e.message}", e) + Logger.e(LOG_TAG_DOWNLOAD, "Error copying file ${e.message}", e) return false } @@ -372,7 +368,7 @@ object Utilities { writeStream.close() true } catch (e: Exception) { - Log.w(LOG_TAG_DOWNLOAD, "Issue while copying files using streams: ${e.message}, $e") + Logger.w(LOG_TAG_DOWNLOAD, "Issue while copying files using streams: ${e.message}, $e") false } } @@ -401,7 +397,7 @@ object Utilities { val alwaysOn = Settings.Secure.getString(context.contentResolver, "always_on_vpn_app") !TextUtils.isEmpty(alwaysOn) && context.packageName != alwaysOn } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "Failure while retrieving Settings.Secure value ${e.message}", e) + Logger.e(LOG_TAG_VPN, "Failure while retrieving Settings.Secure value ${e.message}", e) false } } @@ -415,7 +411,7 @@ object Utilities { ctx.packageManager.getApplicationIcon(packageName) } catch (e: PackageManager.NameNotFoundException) { // Not adding exception details in logs. - Log.e( + Logger.e( LOG_TAG_FIREWALL, "Application Icon not available for package: $packageName" + e.message ) @@ -437,7 +433,7 @@ object Utilities { try { updateUi() } catch (e: Exception) { - Log.e(LOG_TAG_VPN, "Failure in delay function ${e.message}", e) + Logger.e(LOG_TAG_VPN, "Failure in delay function ${e.message}", e) } } } @@ -446,9 +442,9 @@ object Utilities { try { return ctx.packageManager.getPackagesForUid(uid) } catch (e: PackageManager.NameNotFoundException) { - Log.w(Logger.LOG_TAG_FIREWALL_LOG, "Package Not Found: " + e.message) + Logger.w(LOG_TAG_FIREWALL, "Package Not Found: " + e.message) } catch (e: SecurityException) { - Log.w(Logger.LOG_TAG_FIREWALL_LOG, "Package Not Found: " + e.message) + Logger.w(LOG_TAG_FIREWALL, "Package Not Found: " + e.message) } return null } @@ -508,7 +504,7 @@ object Utilities { ctx.packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA) } } catch (e: PackageManager.NameNotFoundException) { - Log.w(LOG_TAG_FIREWALL, "no app info for package name: $packageName") + Logger.w(LOG_TAG_FIREWALL, "no app info for package name: $packageName") null } } @@ -537,13 +533,12 @@ object Utilities { } else { fileOrDirectory.delete() } - if (DEBUG) - Log.d( + Logger.d( LOG_TAG_DOWNLOAD, "deleteRecursive File : ${fileOrDirectory.path}, $isDeleted" ) } catch (e: Exception) { - Log.w(LOG_TAG_DOWNLOAD, "File delete exception: ${e.message}", e) + Logger.w(LOG_TAG_DOWNLOAD, "File delete exception: ${e.message}", e) } } @@ -584,7 +579,7 @@ object Utilities { return File(localBlocklist) } catch (e: IOException) { - Log.e(LOG_TAG_VPN, "Could not fetch local blocklist: " + e.message, e) + Logger.e(LOG_TAG_VPN, "Could not fetch local blocklist: " + e.message, e) null } } @@ -607,7 +602,7 @@ object Utilities { return try { File(blocklistDownloadBasePath(ctx, which, timestamp)) } catch (e: IOException) { - Log.e(LOG_TAG_VPN, "Could not fetch remote blocklist: " + e.message, e) + Logger.e(LOG_TAG_VPN, "Could not fetch remote blocklist: " + e.message, e) null } } @@ -616,7 +611,7 @@ object Utilities { return try { return File(dirPath + fileName) } catch (e: IOException) { - Log.e(LOG_TAG_VPN, "Could not fetch remote blocklist: " + e.message, e) + Logger.e(LOG_TAG_VPN, "Could not fetch remote blocklist: " + e.message, e) null } } @@ -674,7 +669,7 @@ object Utilities { // earlier check of : will not work as now remote stamp can contain sec/rec return path.trimStart { it == '/' }.trimEnd { it == '/' } } catch (e: Exception) { - Log.w(LOG_TAG_DNS, "failure fetching stamp from Go ${e.message}", e) + Logger.w(Logger.LOG_TAG_DNS, "failure fetching stamp from Go ${e.message}", e) "" } } @@ -742,7 +737,7 @@ object Utilities { val pre = ("KMGTPE")[exp - 1] + if (si) "" else "i" return String.format("%.1f %sB", bytes / Math.pow(unit.toDouble(), exp.toDouble()), pre) } catch (e: NumberFormatException) { - Log.e(LOG_TAG_DOWNLOAD, "Number format exception: ${e.message}", e) + Logger.e(LOG_TAG_DOWNLOAD, "Number format exception: ${e.message}", e) } return "" } @@ -770,12 +765,12 @@ object Utilities { // Extract the specific tag value if (jsonObject.has(tag)) { tagValue = jsonObject.get(tag).asString - Log.i(LOG_TAG_DOWNLOAD, "get tag value: $tagValue, for tag: $tag") + Logger.i(LOG_TAG_DOWNLOAD, "get tag value: $tagValue, for tag: $tag") } else { - Log.i(LOG_TAG_DOWNLOAD, "tag not found: $tag") + Logger.i(LOG_TAG_DOWNLOAD, "tag not found: $tag") } } catch (e: Exception) { - Log.e(LOG_TAG_DOWNLOAD, "err parsing the json file: ${e.message}", e) + Logger.e(LOG_TAG_DOWNLOAD, "err parsing the json file: ${e.message}", e) } return tagValue } From 0e243729b0873506b4a2dbaecc8e5eb3980e1ff2 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Sat, 20 Apr 2024 19:59:47 +0530 Subject: [PATCH 26/48] ktfmt code --- .../bravedns/adapter/AppWiseDomainsAdapter.kt | 1 + .../bravedns/adapter/AppWiseIpsAdapter.kt | 1 + .../adapter/ConnectionTrackerAdapter.kt | 3 +- .../bravedns/adapter/CustomDomainAdapter.kt | 1 + .../bravedns/adapter/CustomIpAdapter.kt | 1 + .../adapter/DnsCryptEndpointAdapter.kt | 3 +- .../bravedns/adapter/DnsQueryAdapter.kt | 1 + .../bravedns/adapter/DoTEndpointAdapter.kt | 1 + .../bravedns/adapter/DohEndpointAdapter.kt | 1 + .../adapter/DomainRulesBtmSheetAdapter.kt | 6 ++-- .../bravedns/adapter/ODoHEndpointAdapter.kt | 1 + .../adapter/RethinkEndpointAdapter.kt | 1 + .../bravedns/adapter/RethinkLogAdapter.kt | 1 + .../adapter/SummaryStatisticsAdapter.kt | 1 + .../bravedns/adapter/WgConfigAdapter.kt | 2 +- .../bravedns/adapter/WgIncludeAppsAdapter.kt | 16 ++++++--- .../LocalBlocklistCoordinator.kt | 29 +++++++++------ .../customdownloader/RetrofitManager.kt | 5 +-- .../bravedns/download/AppDownloadManager.kt | 1 + .../download/BlocklistDownloadHelper.kt | 3 +- .../bravedns/download/DownloadWatcher.kt | 10 +++--- .../bravedns/download/FileHandleWorker.kt | 3 +- .../receiver/BraveAutoStartReceiver.kt | 6 +++- .../receiver/NotificationActionReceiver.kt | 7 +++- .../scheduler/BlocklistUpdateCheckJob.kt | 1 + .../bravedns/scheduler/BugReportCollector.kt | 1 + .../bravedns/scheduler/BugReportZipper.kt | 1 + .../bravedns/scheduler/PaymentWorker.kt | 3 +- .../bravedns/scheduler/PurgeConnectionLogs.kt | 1 + .../bravedns/scheduler/WorkScheduler.kt | 1 + .../celzero/bravedns/service/ProxyManager.kt | 14 ++++---- .../bravedns/service/TcpProxyHelper.kt | 12 ++++--- .../bravedns/service/WireguardManager.kt | 13 +++---- .../celzero/bravedns/ui/HomeScreenActivity.kt | 10 +++--- .../bravedns/ui/NotificationHandlerDialog.kt | 1 + .../bravedns/ui/activity/CheckoutActivity.kt | 1 + .../ui/activity/MiscSettingsActivity.kt | 1 + .../ui/activity/ProxySettingsActivity.kt | 5 ++- .../ui/activity/TcpProxyMainActivity.kt | 1 + .../UniversalFirewallSettingsActivity.kt | 1 + .../ui/activity/WgConfigDetailActivity.kt | 1 + .../ui/activity/WgConfigEditorActivity.kt | 12 ++++--- .../bravedns/ui/activity/WgMainActivity.kt | 1 + .../bottomsheet/AppDomainRulesBottomSheet.kt | 1 + .../ui/bottomsheet/AppIpRulesBottomSheet.kt | 1 + .../bottomsheet/BackupRestoreBottomSheet.kt | 1 + .../ui/bottomsheet/ConnTrackerBottomSheet.kt | 3 +- .../ui/bottomsheet/DnsBlocklistBottomSheet.kt | 15 ++++---- .../HomeScreenSettingBottomSheet.kt | 1 + .../bottomsheet/LocalBlocklistsBottomSheet.kt | 1 + .../ui/bottomsheet/RethinkLogBottomSheet.kt | 1 + .../bravedns/ui/dialog/WgAddPeerDialog.kt | 1 + .../bravedns/ui/dialog/WgIncludeAppsDialog.kt | 1 + .../bravedns/ui/fragment/AboutFragment.kt | 11 +++--- .../ui/fragment/DnsCryptListFragment.kt | 4 +-- .../ui/fragment/DnsProxyListFragment.kt | 1 + .../ui/fragment/DnsSettingsFragment.kt | 1 + .../bravedns/ui/fragment/DoTListFragment.kt | 3 +- .../bravedns/ui/fragment/DohListFragment.kt | 8 ++--- .../ui/fragment/HomeScreenFragment.kt | 23 +++++++----- .../bravedns/ui/fragment/ODoHListFragment.kt | 4 +-- .../ui/fragment/RethinkBlocklistFragment.kt | 6 +++- .../ui/fragment/RethinkListFragment.kt | 1 + .../util/BackgroundAccessibilityService.kt | 1 + .../bravedns/util/QrCodeFromFileScanner.kt | 1 + .../bravedns/util/RemoteFileTagUtil.kt | 3 +- .../celzero/bravedns/util/TunnelImporter.kt | 1 + .../java/com/celzero/bravedns/util/UIUtils.kt | 1 + .../celzero/bravedns/backup/BackupAgent.kt | 1 + .../celzero/bravedns/backup/BackupHelper.kt | 2 +- .../celzero/bravedns/backup/RestoreAgent.kt | 21 ++++++----- .../com/celzero/bravedns/data/AppConfig.kt | 2 +- .../celzero/bravedns/database/LogDatabase.kt | 2 +- .../bravedns/database/RefreshDatabase.kt | 1 + .../bravedns/glide/FavIconDownloader.kt | 1 + .../celzero/bravedns/net/go/GoVpnAdapter.kt | 7 ++-- .../bravedns/net/manager/ConnectionTracer.kt | 1 + .../bravedns/scheduler/DataUsageUpdater.kt | 1 + .../bravedns/scheduler/RefreshAppsJob.kt | 1 + .../bravedns/scheduler/ScheduleManager.kt | 1 + .../bravedns/service/BraveVPNService.kt | 36 +++++++++++-------- .../bravedns/service/ConnectionMonitor.kt | 7 ++-- .../bravedns/service/DomainRulesManager.kt | 1 + .../bravedns/service/EncryptedFileManager.kt | 1 + .../bravedns/service/FirewallManager.kt | 1 + .../com/celzero/bravedns/service/IPTracker.kt | 1 + .../bravedns/service/IpRulesManager.kt | 2 +- .../celzero/bravedns/service/NetLogTracker.kt | 3 +- .../celzero/bravedns/service/PauseTimer.kt | 2 +- .../bravedns/service/PersistentState.kt | 5 +-- .../service/RethinkBlocklistManager.kt | 13 ++++--- .../celzero/bravedns/service/VpnController.kt | 1 + .../java/com/celzero/bravedns/util/IPUtil.kt | 1 + .../celzero/bravedns/util/NetLogBatcher.kt | 1 + .../com/celzero/bravedns/util/OrbotHelper.kt | 5 +-- .../com/celzero/bravedns/util/Utilities.kt | 17 ++++----- 96 files changed, 263 insertions(+), 156 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/adapter/AppWiseDomainsAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/AppWiseDomainsAdapter.kt index 8d9e9ca83..e590b05b7 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/AppWiseDomainsAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/AppWiseDomainsAdapter.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.adapter +import Logger import Logger.LOG_TAG_UI import android.content.Context import android.content.res.ColorStateList diff --git a/app/src/full/java/com/celzero/bravedns/adapter/AppWiseIpsAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/AppWiseIpsAdapter.kt index c8003b61c..d65e83faf 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/AppWiseIpsAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/AppWiseIpsAdapter.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.adapter +import Logger import Logger.LOG_TAG_UI import android.content.Context import android.content.res.ColorStateList diff --git a/app/src/full/java/com/celzero/bravedns/adapter/ConnectionTrackerAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/ConnectionTrackerAdapter.kt index 748f02ffa..35eba7419 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/ConnectionTrackerAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/ConnectionTrackerAdapter.kt @@ -16,6 +16,7 @@ limitations under the License. package com.celzero.bravedns.adapter +import Logger import Logger.LOG_TAG_UI import android.content.Context import android.graphics.drawable.Drawable @@ -46,10 +47,10 @@ import com.celzero.bravedns.util.UIUtils.getDurationInHumanReadableFormat import com.celzero.bravedns.util.Utilities import com.celzero.bravedns.util.Utilities.getIcon import com.google.gson.Gson -import java.util.Locale import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import java.util.Locale class ConnectionTrackerAdapter(private val context: Context) : PagingDataAdapter( diff --git a/app/src/full/java/com/celzero/bravedns/adapter/CustomDomainAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/CustomDomainAdapter.kt index ac4caa77f..a8deb8cde 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/CustomDomainAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/CustomDomainAdapter.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.adapter +import Logger import Logger.LOG_TAG_UI import android.content.Context import android.content.res.ColorStateList diff --git a/app/src/full/java/com/celzero/bravedns/adapter/CustomIpAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/CustomIpAdapter.kt index 86672f2b9..8e748bd97 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/CustomIpAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/CustomIpAdapter.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.adapter +import Logger import Logger.LOG_TAG_UI import android.content.Context import android.content.res.ColorStateList diff --git a/app/src/full/java/com/celzero/bravedns/adapter/DnsCryptEndpointAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/DnsCryptEndpointAdapter.kt index 13d4ed6d6..3246ec86e 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/DnsCryptEndpointAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/DnsCryptEndpointAdapter.kt @@ -120,7 +120,8 @@ class DnsCryptEndpointAdapter(private val context: Context, private val appConfi if (endpoint.isSelected && VpnController.hasTunnel()) { keepSelectedStatusUpdated() } else if (endpoint.isSelected) { - b.dnsCryptEndpointListUrlExplanation.text = context.getString(R.string.rt_filter_parent_selected) + b.dnsCryptEndpointListUrlExplanation.text = + context.getString(R.string.rt_filter_parent_selected) } else { b.dnsCryptEndpointListUrlExplanation.text = "" } diff --git a/app/src/full/java/com/celzero/bravedns/adapter/DnsQueryAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/DnsQueryAdapter.kt index 7cce4aa8c..3fc929764 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/DnsQueryAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/DnsQueryAdapter.kt @@ -16,6 +16,7 @@ limitations under the License. package com.celzero.bravedns.adapter +import Logger import Logger.LOG_TAG_DNS import Logger.LOG_TAG_UI import android.content.Context diff --git a/app/src/full/java/com/celzero/bravedns/adapter/DoTEndpointAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/DoTEndpointAdapter.kt index 31f98d33e..c01a83fdc 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/DoTEndpointAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/DoTEndpointAdapter.kt @@ -16,6 +16,7 @@ limitations under the License. package com.celzero.bravedns.adapter +import Logger import Logger.LOG_TAG_DNS import android.content.Context import android.content.DialogInterface diff --git a/app/src/full/java/com/celzero/bravedns/adapter/DohEndpointAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/DohEndpointAdapter.kt index 72aca4ada..4624c9ada 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/DohEndpointAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/DohEndpointAdapter.kt @@ -16,6 +16,7 @@ limitations under the License. package com.celzero.bravedns.adapter +import Logger import Logger.LOG_TAG_DNS import android.content.Context import android.content.DialogInterface diff --git a/app/src/full/java/com/celzero/bravedns/adapter/DomainRulesBtmSheetAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/DomainRulesBtmSheetAdapter.kt index d60c16358..9627c5f0b 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/DomainRulesBtmSheetAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/DomainRulesBtmSheetAdapter.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.adapter +import Logger import Logger.LOG_TAG_FIREWALL import android.content.Context import android.view.LayoutInflater @@ -94,10 +95,7 @@ class DomainRulesBtmSheetAdapter( } private fun applyDomainRule(domain: String, domainRuleStatus: DomainRulesManager.Status) { - Logger.i( - LOG_TAG_FIREWALL, - "Apply domain rule for $domain, ${domainRuleStatus.name}" - ) + Logger.i(LOG_TAG_FIREWALL, "Apply domain rule for $domain, ${domainRuleStatus.name}") io { DomainRulesManager.addDomainRule( domain.trim(), diff --git a/app/src/full/java/com/celzero/bravedns/adapter/ODoHEndpointAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/ODoHEndpointAdapter.kt index 6f566a1a5..a8c8b81aa 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/ODoHEndpointAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/ODoHEndpointAdapter.kt @@ -16,6 +16,7 @@ limitations under the License. package com.celzero.bravedns.adapter +import Logger import Logger.LOG_TAG_DNS import android.content.Context import android.content.DialogInterface diff --git a/app/src/full/java/com/celzero/bravedns/adapter/RethinkEndpointAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/RethinkEndpointAdapter.kt index b950ab289..3fd7c9246 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/RethinkEndpointAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/RethinkEndpointAdapter.kt @@ -16,6 +16,7 @@ package com.celzero.bravedns.adapter +import Logger import Logger.LOG_TAG_DNS import android.content.Context import android.content.DialogInterface diff --git a/app/src/full/java/com/celzero/bravedns/adapter/RethinkLogAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/RethinkLogAdapter.kt index e71761bce..60d6f449e 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/RethinkLogAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/RethinkLogAdapter.kt @@ -16,6 +16,7 @@ limitations under the License. package com.celzero.bravedns.adapter +import Logger import Logger.LOG_TAG_UI import android.content.Context import android.graphics.drawable.Drawable diff --git a/app/src/full/java/com/celzero/bravedns/adapter/SummaryStatisticsAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/SummaryStatisticsAdapter.kt index 8c3e98b87..ae4e85994 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/SummaryStatisticsAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/SummaryStatisticsAdapter.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.adapter +import Logger import Logger.LOG_TAG_DNS import android.content.Context import android.content.Intent diff --git a/app/src/full/java/com/celzero/bravedns/adapter/WgConfigAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/WgConfigAdapter.kt index 3a4c38866..e99cc667b 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/WgConfigAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/WgConfigAdapter.kt @@ -40,11 +40,11 @@ import com.celzero.bravedns.ui.activity.WgConfigDetailActivity import com.celzero.bravedns.ui.activity.WgConfigEditorActivity.Companion.INTENT_EXTRA_WG_ID import com.celzero.bravedns.util.UIUtils import com.celzero.bravedns.util.Utilities -import java.util.concurrent.ConcurrentHashMap import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch +import java.util.concurrent.ConcurrentHashMap class WgConfigAdapter(private val context: Context) : PagingDataAdapter(DIFF_CALLBACK) { diff --git a/app/src/full/java/com/celzero/bravedns/adapter/WgIncludeAppsAdapter.kt b/app/src/full/java/com/celzero/bravedns/adapter/WgIncludeAppsAdapter.kt index c04982a1e..23162f56f 100644 --- a/app/src/full/java/com/celzero/bravedns/adapter/WgIncludeAppsAdapter.kt +++ b/app/src/full/java/com/celzero/bravedns/adapter/WgIncludeAppsAdapter.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.adapter +import Logger import Logger.LOG_TAG_PROXY import android.content.Context import android.content.DialogInterface @@ -120,7 +121,10 @@ class WgIncludeAppsAdapter( private fun setupClickListeners(mapping: ProxyApplicationMapping, isIncluded: Boolean) { b.wgIncludeCard.setOnClickListener { - Logger.i(LOG_TAG_PROXY, "wgIncludeAppListContainer- ${mapping.appName}, $isIncluded") + Logger.i( + LOG_TAG_PROXY, + "wgIncludeAppListContainer- ${mapping.appName}, $isIncluded" + ) updateInterfaceDetails(mapping, !isIncluded) } @@ -139,16 +143,18 @@ class WgIncludeAppsAdapter( .into(b.wgIncludeAppListApkIconIv) } - private fun setCardBackground(isSelected: Boolean) { if (isSelected) { - b.wgIncludeCard.setCardBackgroundColor(UIUtils.fetchColor(context, R.attr.selectedCardBg)) + b.wgIncludeCard.setCardBackgroundColor( + UIUtils.fetchColor(context, R.attr.selectedCardBg) + ) } else { - b.wgIncludeCard.setCardBackgroundColor(UIUtils.fetchColor(context, R.attr.background)) + b.wgIncludeCard.setCardBackgroundColor( + UIUtils.fetchColor(context, R.attr.background) + ) } } - private fun updateInterfaceDetails(mapping: ProxyApplicationMapping, include: Boolean) { io { val appUidList = FirewallManager.getAppNamesByUid(mapping.uid) diff --git a/app/src/full/java/com/celzero/bravedns/customdownloader/LocalBlocklistCoordinator.kt b/app/src/full/java/com/celzero/bravedns/customdownloader/LocalBlocklistCoordinator.kt index e190c5766..6d34dca41 100644 --- a/app/src/full/java/com/celzero/bravedns/customdownloader/LocalBlocklistCoordinator.kt +++ b/app/src/full/java/com/celzero/bravedns/customdownloader/LocalBlocklistCoordinator.kt @@ -44,9 +44,6 @@ import com.celzero.bravedns.util.Utilities.blocklistDownloadBasePath import com.celzero.bravedns.util.Utilities.calculateMd5 import com.celzero.bravedns.util.Utilities.getTagValueFromJson import com.celzero.bravedns.util.Utilities.tempDownloadBasePath -import okhttp3.ResponseBody -import org.koin.core.component.KoinComponent -import org.koin.core.component.inject import java.io.BufferedInputStream import java.io.File import java.io.FileOutputStream @@ -56,6 +53,9 @@ import java.io.OutputStream import java.util.concurrent.CancellationException import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit +import okhttp3.ResponseBody +import org.koin.core.component.KoinComponent +import org.koin.core.component.inject class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParameters) : CoroutineWorker(context, workerParams), KoinComponent { @@ -153,7 +153,10 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame // check if all the files are downloaded, as of now the check if for only number of files // downloaded. TODO: Later add checksum matching as well if (!isDownloadComplete(file)) { - Logger.e(LOG_TAG_DOWNLOAD, "Local blocklist validation failed for timestamp: $timestamp") + Logger.e( + LOG_TAG_DOWNLOAD, + "Local blocklist validation failed for timestamp: $timestamp" + ) notifyDownloadFailure(context) return false } @@ -318,9 +321,9 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame } Logger.d( - LOG_TAG_DOWNLOAD, - "Valid on-device blocklist in folder (${dir.name}) download? $result, files: $total, dir? ${dir.isDirectory}" - ) + LOG_TAG_DOWNLOAD, + "Valid on-device blocklist in folder (${dir.name}) download? $result, files: $total, dir? ${dir.isDirectory}" + ) return result } @@ -375,14 +378,18 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame val remoteRdmd5 = getTagValueFromJson(path + Constants.ONDEVICE_BLOCKLIST_FILE_BASIC_CONFIG, "rdmd5") Logger.d( - LOG_TAG_DOWNLOAD, - "tdmd5: $tdmd5, rdmd5: $rdmd5, remotetd: $remoteTdmd5, remoterd: $remoteRdmd5" - ) + LOG_TAG_DOWNLOAD, + "tdmd5: $tdmd5, rdmd5: $rdmd5, remotetd: $remoteTdmd5, remoterd: $remoteRdmd5" + ) val isDownloadValid = tdmd5 == remoteTdmd5 && rdmd5 == remoteRdmd5 Logger.i(LOG_TAG_DOWNLOAD, "AppDownloadManager isDownloadValid? $isDownloadValid") return isDownloadValid } catch (e: Exception) { - Logger.e(LOG_TAG_DOWNLOAD, "AppDownloadManager isDownloadValid exception: ${e.message}", e) + Logger.e( + LOG_TAG_DOWNLOAD, + "AppDownloadManager isDownloadValid exception: ${e.message}", + e + ) } return false } diff --git a/app/src/full/java/com/celzero/bravedns/customdownloader/RetrofitManager.kt b/app/src/full/java/com/celzero/bravedns/customdownloader/RetrofitManager.kt index 69aab6bd1..63031fb74 100644 --- a/app/src/full/java/com/celzero/bravedns/customdownloader/RetrofitManager.kt +++ b/app/src/full/java/com/celzero/bravedns/customdownloader/RetrofitManager.kt @@ -15,14 +15,15 @@ */ package com.celzero.bravedns.customdownloader +import Logger import com.celzero.bravedns.util.Constants -import java.net.InetAddress -import java.util.concurrent.TimeUnit import okhttp3.Dns import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.OkHttpClient import okhttp3.dnsoverhttps.DnsOverHttps import retrofit2.Retrofit +import java.net.InetAddress +import java.util.concurrent.TimeUnit class RetrofitManager { diff --git a/app/src/full/java/com/celzero/bravedns/download/AppDownloadManager.kt b/app/src/full/java/com/celzero/bravedns/download/AppDownloadManager.kt index 508752655..8c6a7183c 100644 --- a/app/src/full/java/com/celzero/bravedns/download/AppDownloadManager.kt +++ b/app/src/full/java/com/celzero/bravedns/download/AppDownloadManager.kt @@ -16,6 +16,7 @@ package com.celzero.bravedns.download +import Logger import Logger.LOG_TAG_DNS import Logger.LOG_TAG_DOWNLOAD import android.app.DownloadManager diff --git a/app/src/full/java/com/celzero/bravedns/download/BlocklistDownloadHelper.kt b/app/src/full/java/com/celzero/bravedns/download/BlocklistDownloadHelper.kt index 94155d780..bbf1ef752 100644 --- a/app/src/full/java/com/celzero/bravedns/download/BlocklistDownloadHelper.kt +++ b/app/src/full/java/com/celzero/bravedns/download/BlocklistDownloadHelper.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.download +import Logger import Logger.LOG_TAG_DOWNLOAD import android.content.Context import com.celzero.bravedns.customdownloader.IBlocklistDownload @@ -24,10 +25,10 @@ import com.celzero.bravedns.util.Constants import com.celzero.bravedns.util.Constants.Companion.INIT_TIME_MS import com.celzero.bravedns.util.Utilities.blocklistCanonicalPath import com.celzero.bravedns.util.Utilities.deleteRecursive -import java.io.File import org.json.JSONException import org.json.JSONObject import retrofit2.converter.gson.GsonConverterFactory +import java.io.File class BlocklistDownloadHelper { diff --git a/app/src/full/java/com/celzero/bravedns/download/DownloadWatcher.kt b/app/src/full/java/com/celzero/bravedns/download/DownloadWatcher.kt index 3cb189dd5..d17da7499 100644 --- a/app/src/full/java/com/celzero/bravedns/download/DownloadWatcher.kt +++ b/app/src/full/java/com/celzero/bravedns/download/DownloadWatcher.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.download +import Logger import Logger.LOG_TAG_DOWNLOAD import android.app.DownloadManager import android.content.Context @@ -104,12 +105,11 @@ class DownloadWatcher(val context: Context, workerParameters: WorkerParameters) if (status == DownloadManager.STATUS_SUCCESSFUL) { downloadIdsIterator.remove() } else if (status == DownloadManager.STATUS_FAILED) { - val reason = - cursor.getInt(columnIndex) + val reason = cursor.getInt(columnIndex) Logger.d( - LOG_TAG_DOWNLOAD, - "download status failure for $downloadID, $reason" - ) + LOG_TAG_DOWNLOAD, + "download status failure for $downloadID, $reason" + ) return DOWNLOAD_FAILURE } } else { diff --git a/app/src/full/java/com/celzero/bravedns/download/FileHandleWorker.kt b/app/src/full/java/com/celzero/bravedns/download/FileHandleWorker.kt index b318b17fe..60fca49a9 100644 --- a/app/src/full/java/com/celzero/bravedns/download/FileHandleWorker.kt +++ b/app/src/full/java/com/celzero/bravedns/download/FileHandleWorker.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.download +import Logger import Logger.LOG_TAG_DOWNLOAD import android.content.Context import androidx.work.CoroutineWorker @@ -31,12 +32,12 @@ import com.celzero.bravedns.util.Utilities.calculateMd5 import com.celzero.bravedns.util.Utilities.getTagValueFromJson import com.celzero.bravedns.util.Utilities.hasLocalBlocklists import com.celzero.bravedns.util.Utilities.localBlocklistFileDownloadPath -import java.io.File import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.koin.core.component.KoinComponent import org.koin.core.component.inject +import java.io.File /** * Class responsible for copying the files from External path to canonical path. The worker will be diff --git a/app/src/full/java/com/celzero/bravedns/receiver/BraveAutoStartReceiver.kt b/app/src/full/java/com/celzero/bravedns/receiver/BraveAutoStartReceiver.kt index 2da84df69..67579d650 100644 --- a/app/src/full/java/com/celzero/bravedns/receiver/BraveAutoStartReceiver.kt +++ b/app/src/full/java/com/celzero/bravedns/receiver/BraveAutoStartReceiver.kt @@ -16,6 +16,7 @@ package com.celzero.bravedns.receiver +import Logger import Logger.LOG_TAG_VPN import android.content.BroadcastReceiver import android.content.Context @@ -33,7 +34,10 @@ class BraveAutoStartReceiver : BroadcastReceiver(), KoinComponent { override fun onReceive(context: Context, intent: Intent) { if (!persistentState.prefAutoStartBootUp) { - Logger.w(LOG_TAG_VPN, "Auto start is not enabled: ${persistentState.prefAutoStartBootUp}") + Logger.w( + LOG_TAG_VPN, + "Auto start is not enabled: ${persistentState.prefAutoStartBootUp}" + ) return } diff --git a/app/src/full/java/com/celzero/bravedns/receiver/NotificationActionReceiver.kt b/app/src/full/java/com/celzero/bravedns/receiver/NotificationActionReceiver.kt index fdf6d94d2..97b411b04 100644 --- a/app/src/full/java/com/celzero/bravedns/receiver/NotificationActionReceiver.kt +++ b/app/src/full/java/com/celzero/bravedns/receiver/NotificationActionReceiver.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.receiver +import Logger import Logger.LOG_TAG_VPN import android.app.NotificationManager import android.content.BroadcastReceiver @@ -116,7 +117,11 @@ class NotificationActionReceiver : BroadcastReceiver(), KoinComponent { private fun dnsMode(context: Context) { if (appConfig.isProxyEnabled()) { - Utilities.showToastUiCentered(context, context.getString(R.string.settings_lock_down_proxy_desc), Toast.LENGTH_SHORT) + Utilities.showToastUiCentered( + context, + context.getString(R.string.settings_lock_down_proxy_desc), + Toast.LENGTH_SHORT + ) return } io { appConfig.changeBraveMode(AppConfig.BraveMode.DNS.mode) } diff --git a/app/src/full/java/com/celzero/bravedns/scheduler/BlocklistUpdateCheckJob.kt b/app/src/full/java/com/celzero/bravedns/scheduler/BlocklistUpdateCheckJob.kt index 4ae3201df..d2b0c3fa9 100644 --- a/app/src/full/java/com/celzero/bravedns/scheduler/BlocklistUpdateCheckJob.kt +++ b/app/src/full/java/com/celzero/bravedns/scheduler/BlocklistUpdateCheckJob.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.scheduler +import Logger import Logger.LOG_TAG_SCHEDULER import android.content.Context import androidx.work.CoroutineWorker diff --git a/app/src/full/java/com/celzero/bravedns/scheduler/BugReportCollector.kt b/app/src/full/java/com/celzero/bravedns/scheduler/BugReportCollector.kt index ffeac815d..d6a8f2403 100644 --- a/app/src/full/java/com/celzero/bravedns/scheduler/BugReportCollector.kt +++ b/app/src/full/java/com/celzero/bravedns/scheduler/BugReportCollector.kt @@ -16,6 +16,7 @@ package com.celzero.bravedns.scheduler +import Logger import Logger.LOG_TAG_SCHEDULER import android.app.ActivityManager import android.content.Context diff --git a/app/src/full/java/com/celzero/bravedns/scheduler/BugReportZipper.kt b/app/src/full/java/com/celzero/bravedns/scheduler/BugReportZipper.kt index dcab8cd28..96b6cfef9 100644 --- a/app/src/full/java/com/celzero/bravedns/scheduler/BugReportZipper.kt +++ b/app/src/full/java/com/celzero/bravedns/scheduler/BugReportZipper.kt @@ -16,6 +16,7 @@ package com.celzero.bravedns.scheduler +import Logger import Logger.LOG_TAG_SCHEDULER import android.app.ApplicationExitInfo import android.content.SharedPreferences diff --git a/app/src/full/java/com/celzero/bravedns/scheduler/PaymentWorker.kt b/app/src/full/java/com/celzero/bravedns/scheduler/PaymentWorker.kt index 4fe5f32ce..bfcf116b7 100644 --- a/app/src/full/java/com/celzero/bravedns/scheduler/PaymentWorker.kt +++ b/app/src/full/java/com/celzero/bravedns/scheduler/PaymentWorker.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.scheduler +import Logger import Logger.LOG_TAG_DOWNLOAD import android.content.Context import android.os.SystemClock @@ -23,10 +24,10 @@ import androidx.work.WorkerParameters import com.celzero.bravedns.customdownloader.ITcpProxy import com.celzero.bravedns.customdownloader.RetrofitManager import com.celzero.bravedns.service.TcpProxyHelper -import java.util.concurrent.TimeUnit import org.json.JSONObject import org.koin.core.component.KoinComponent import retrofit2.converter.gson.GsonConverterFactory +import java.util.concurrent.TimeUnit class PaymentWorker(val context: Context, workerParameters: WorkerParameters) : CoroutineWorker(context, workerParameters), KoinComponent { diff --git a/app/src/full/java/com/celzero/bravedns/scheduler/PurgeConnectionLogs.kt b/app/src/full/java/com/celzero/bravedns/scheduler/PurgeConnectionLogs.kt index 8d3e9d0f2..3fb566fb5 100644 --- a/app/src/full/java/com/celzero/bravedns/scheduler/PurgeConnectionLogs.kt +++ b/app/src/full/java/com/celzero/bravedns/scheduler/PurgeConnectionLogs.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.scheduler +import Logger import Logger.LOG_TAG_SCHEDULER import android.content.Context import androidx.work.CoroutineWorker diff --git a/app/src/full/java/com/celzero/bravedns/scheduler/WorkScheduler.kt b/app/src/full/java/com/celzero/bravedns/scheduler/WorkScheduler.kt index 7f547440a..624682d3a 100644 --- a/app/src/full/java/com/celzero/bravedns/scheduler/WorkScheduler.kt +++ b/app/src/full/java/com/celzero/bravedns/scheduler/WorkScheduler.kt @@ -16,6 +16,7 @@ package com.celzero.bravedns.scheduler +import Logger import Logger.LOG_TAG_SCHEDULER import android.content.Context import androidx.work.BackoffPolicy diff --git a/app/src/full/java/com/celzero/bravedns/service/ProxyManager.kt b/app/src/full/java/com/celzero/bravedns/service/ProxyManager.kt index b9e186d3f..0130bea0c 100644 --- a/app/src/full/java/com/celzero/bravedns/service/ProxyManager.kt +++ b/app/src/full/java/com/celzero/bravedns/service/ProxyManager.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.service +import Logger import Logger.LOG_TAG_PROXY import backend.Backend import com.celzero.bravedns.database.AppInfo @@ -104,7 +105,7 @@ object ProxyManager : KoinComponent { val m = pamSet.filter { it.uid == uid } // returns a reference to underlying data-class if (m.isNotEmpty()) { - val n = m.map { ProxyAppMapTuple(it.uid, it.packageName, nonEmptyProxyId)} + val n = m.map { ProxyAppMapTuple(it.uid, it.packageName, nonEmptyProxyId) } // in-place updates in Set does not remove dups on conflicts: pl.kotl.in/hEHOgk3V0 // that is, m.forEach { it.proxyName = nonEmptyProxyId } will not de-dup an existing // entry with the same uid+package-name+proxy-id, and instead will retain both entries. @@ -199,9 +200,7 @@ object ProxyManager : KoinComponent { val dups = mutableSetOf() pamSet .map { FirewallManager.AppInfoTuple(it.uid, it.packageName) } - .forEach { - if (visited.contains(it)) dups.add(it) else visited.add(it) - } + .forEach { if (visited.contains(it)) dups.add(it) else visited.add(it) } // duplicates are unexpected; but since refreshDatabase only deals in uid+package-name // and proxy-mapper primary keys on uid+package-name+proxy-id, there have been cases // of duplicate entries in the proxy-mapper. Purge all entries that have same @@ -244,16 +243,15 @@ object ProxyManager : KoinComponent { } suspend fun deleteApp(appInfo: AppInfo) { - return deleteApp(appInfo.uid, appInfo.packageName) - } + return deleteApp(appInfo.uid, appInfo.packageName) + } suspend fun deleteApp(appInfoTuple: FirewallManager.AppInfoTuple) { return deleteApp(appInfoTuple.uid, appInfoTuple.packageName) } suspend fun deleteApp(uid: Int, packageName: String) { - val pam = - ProxyApplicationMapping(uid, packageName, "", "", false, "") + val pam = ProxyApplicationMapping(uid, packageName, "", "", false, "") deleteFromCache(pam) db.deleteApp(pam) Logger.d(LOG_TAG_PROXY, "Deleting app for mapping: ${pam.appName}, ${pam.uid}") diff --git a/app/src/full/java/com/celzero/bravedns/service/TcpProxyHelper.kt b/app/src/full/java/com/celzero/bravedns/service/TcpProxyHelper.kt index 94dac0322..05ff43b8f 100644 --- a/app/src/full/java/com/celzero/bravedns/service/TcpProxyHelper.kt +++ b/app/src/full/java/com/celzero/bravedns/service/TcpProxyHelper.kt @@ -1,5 +1,6 @@ package com.celzero.bravedns.service +import Logger import Logger.LOG_TAG_PROXY import android.content.Context import android.os.SystemClock @@ -136,9 +137,9 @@ object TcpProxyHelper : KoinComponent { val response = retrofitInterface.getPublicKey(persistentState.appVersion.toString()) Logger.d( - LOG_TAG_PROXY, - "new tcp config: ${response?.headers()}, ${response?.message()}, ${response?.raw()?.request?.url}" - ) + LOG_TAG_PROXY, + "new tcp config: ${response?.headers()}, ${response?.message()}, ${response?.raw()?.request?.url}" + ) if (response?.isSuccessful == true) { val jsonObject = JSONObject(response.body().toString()) @@ -151,7 +152,10 @@ object TcpProxyHelper : KoinComponent { ) return works } else { - Logger.w(LOG_TAG_PROXY, "unsuccessful response for ${response?.raw()?.request?.url}") + Logger.w( + LOG_TAG_PROXY, + "unsuccessful response for ${response?.raw()?.request?.url}" + ) } } catch (e: Exception) { Logger.e( diff --git a/app/src/full/java/com/celzero/bravedns/service/WireguardManager.kt b/app/src/full/java/com/celzero/bravedns/service/WireguardManager.kt index 2fa1e6f88..0b5a9b324 100644 --- a/app/src/full/java/com/celzero/bravedns/service/WireguardManager.kt +++ b/app/src/full/java/com/celzero/bravedns/service/WireguardManager.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.service +import Logger import Logger.LOG_TAG_PROXY import android.content.Context import backend.Backend @@ -30,12 +31,6 @@ import com.celzero.bravedns.wireguard.BadConfigException import com.celzero.bravedns.wireguard.Config import com.celzero.bravedns.wireguard.Peer import com.celzero.bravedns.wireguard.WgInterface -import java.io.ByteArrayInputStream -import java.io.File -import java.io.InputStream -import java.nio.charset.StandardCharsets -import java.util.Locale -import java.util.concurrent.CopyOnWriteArraySet import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -43,6 +38,12 @@ import org.json.JSONObject import org.koin.core.component.KoinComponent import org.koin.core.component.inject import retrofit2.converter.gson.GsonConverterFactory +import java.io.ByteArrayInputStream +import java.io.File +import java.io.InputStream +import java.nio.charset.StandardCharsets +import java.util.Locale +import java.util.concurrent.CopyOnWriteArraySet object WireguardManager : KoinComponent { diff --git a/app/src/full/java/com/celzero/bravedns/ui/HomeScreenActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/HomeScreenActivity.kt index fb8f57e57..c2b2ab4eb 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/HomeScreenActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/HomeScreenActivity.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui +import Logger import Logger.LOG_TAG_APP_UPDATE import Logger.LOG_TAG_BACKUP_RESTORE import Logger.LOG_TAG_DOWNLOAD @@ -74,13 +75,13 @@ import com.celzero.bravedns.util.Utilities.showToastUiCentered import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar -import java.util.Calendar -import java.util.concurrent.Executor -import java.util.concurrent.TimeUnit import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.koin.android.ext.android.get import org.koin.android.ext.android.inject +import java.util.Calendar +import java.util.concurrent.Executor +import java.util.concurrent.TimeUnit class HomeScreenActivity : AppCompatActivity(R.layout.activity_home_screen) { private val b by viewBinding(ActivityHomeScreenBinding::bind) @@ -470,7 +471,8 @@ class HomeScreenActivity : AppCompatActivity(R.layout.activity_home_screen) { // Check updates only for play store / website version. Not fDroid. if (!isPlayStoreFlavour() && !isWebsiteFlavour()) { - Logger.d(LOG_TAG_APP_UPDATE, + Logger.d( + LOG_TAG_APP_UPDATE, "Check for update: Not play or website- ${BuildConfig.FLAVOR}" ) return diff --git a/app/src/full/java/com/celzero/bravedns/ui/NotificationHandlerDialog.kt b/app/src/full/java/com/celzero/bravedns/ui/NotificationHandlerDialog.kt index c564c8bc7..5c370981d 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/NotificationHandlerDialog.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/NotificationHandlerDialog.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui +import Logger import Logger.LOG_TAG_VPN import android.content.Context import android.content.Intent diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/CheckoutActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/CheckoutActivity.kt index a0d95e75f..48b1e93fb 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/CheckoutActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/CheckoutActivity.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.activity +import Logger import android.content.Context import android.content.Intent import android.content.res.Configuration diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/MiscSettingsActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/MiscSettingsActivity.kt index 330fbdd67..9c97a7fee 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/MiscSettingsActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/MiscSettingsActivity.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.activity +import Logger import Logger.LOG_TAG_UI import Logger.LOG_TAG_VPN import Logger.updateConfigLevel diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/ProxySettingsActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/ProxySettingsActivity.kt index dc08c21af..87379e527 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/ProxySettingsActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/ProxySettingsActivity.kt @@ -15,9 +15,9 @@ */ package com.celzero.bravedns.ui.activity +import Logger import Logger.LOG_TAG_PROXY import Logger.LOG_TAG_UI -import android.app.Dialog import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent @@ -25,7 +25,6 @@ import android.content.res.Configuration import android.content.res.Configuration.UI_MODE_NIGHT_YES import android.os.Bundle import android.view.View -import android.view.Window import android.view.WindowManager import android.view.animation.Animation import android.view.animation.RotateAnimation @@ -63,11 +62,11 @@ import com.celzero.bravedns.util.Utilities.isAtleastQ import com.celzero.bravedns.util.Utilities.isValidPort import com.celzero.bravedns.util.Utilities.showToastUiCentered import com.google.android.material.dialog.MaterialAlertDialogBuilder -import java.util.concurrent.TimeUnit import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.koin.android.ext.android.inject +import java.util.concurrent.TimeUnit class ProxySettingsActivity : AppCompatActivity(R.layout.fragment_proxy_configure) { private val b by viewBinding(FragmentProxyConfigureBinding::bind) diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/TcpProxyMainActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/TcpProxyMainActivity.kt index 3db8efe66..e3a4a15be 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/TcpProxyMainActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/TcpProxyMainActivity.kt @@ -1,5 +1,6 @@ package com.celzero.bravedns.ui.activity +import Logger import Logger.LOG_TAG_UI import android.content.Context import android.content.Intent diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/UniversalFirewallSettingsActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/UniversalFirewallSettingsActivity.kt index cc5790def..d900ca169 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/UniversalFirewallSettingsActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/UniversalFirewallSettingsActivity.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.activity +import Logger import Logger.LOG_TAG_FIREWALL import android.content.ActivityNotFoundException import android.content.Context diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigDetailActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigDetailActivity.kt index 035363746..6219ba972 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigDetailActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigDetailActivity.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.activity +import Logger import Logger.LOG_TAG_PROXY import android.content.Context import android.content.Intent diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigEditorActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigEditorActivity.kt index 71672d79d..fd6159510 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigEditorActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/WgConfigEditorActivity.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.activity +import Logger import Logger.LOG_TAG_PROXY import Logger.throwableToException import android.content.Context @@ -96,11 +97,12 @@ class WgConfigEditorActivity : AppCompatActivity(R.layout.activity_wg_config_edi b.publicKeyText.setText(wgInterface?.getKeyPair()?.getPublicKey()?.base64()) var dns = wgInterface?.dnsServers?.joinToString { it.hostAddress?.toString() ?: "" } val searchDomains = wgInterface?.dnsSearchDomains?.joinToString { it } - dns = if (!searchDomains.isNullOrEmpty()) { - "$dns,$searchDomains" - } else { - dns - } + dns = + if (!searchDomains.isNullOrEmpty()) { + "$dns,$searchDomains" + } else { + dns + } b.dnsServersText.setText(dns) if (wgInterface?.getAddresses()?.isEmpty() != true) { b.addressesLabelText.setText( diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/WgMainActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/WgMainActivity.kt index 3542e8c66..c642205ca 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/WgMainActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/WgMainActivity.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.activity +import Logger import Logger.LOG_TAG_PROXY import android.content.Context import android.content.Intent diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/AppDomainRulesBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/AppDomainRulesBottomSheet.kt index 6b2c4aa49..a4fddd087 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/AppDomainRulesBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/AppDomainRulesBottomSheet.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.bottomsheet +import Logger import Logger.LOG_TAG_FIREWALL import android.content.DialogInterface import android.content.res.Configuration diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/AppIpRulesBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/AppIpRulesBottomSheet.kt index fb9a8b85d..63a6d9ba2 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/AppIpRulesBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/AppIpRulesBottomSheet.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.bottomsheet +import Logger import Logger.LOG_TAG_FIREWALL import android.content.DialogInterface import android.content.res.Configuration diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/BackupRestoreBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/BackupRestoreBottomSheet.kt index 66a2a0b5d..0837eaf25 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/BackupRestoreBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/BackupRestoreBottomSheet.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.bottomsheet +import Logger import Logger.LOG_TAG_BACKUP_RESTORE import android.app.Activity import android.content.Context diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/ConnTrackerBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/ConnTrackerBottomSheet.kt index 3f32a197a..3deca080b 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/ConnTrackerBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/ConnTrackerBottomSheet.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.bottomsheet +import Logger import Logger.LOG_TAG_FIREWALL import android.content.Intent import android.content.res.ColorStateList @@ -62,12 +63,12 @@ import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.common.collect.HashMultimap import com.google.common.collect.Multimap import com.google.gson.Gson -import java.util.Locale import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.koin.android.ext.android.inject import org.koin.core.component.KoinComponent +import java.util.Locale class ConnTrackerBottomSheet : BottomSheetDialogFragment(), KoinComponent { diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/DnsBlocklistBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/DnsBlocklistBottomSheet.kt index fc2ad5e88..40c12109b 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/DnsBlocklistBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/DnsBlocklistBottomSheet.kt @@ -15,6 +15,7 @@ limitations under the License. */ package com.celzero.bravedns.ui.bottomsheet +import Logger import Logger.LOG_TAG_DNS import android.content.res.ColorStateList import android.content.res.Configuration @@ -59,10 +60,10 @@ import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.common.collect.HashMultimap import com.google.common.collect.Multimap import com.google.gson.Gson -import java.util.Locale import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.koin.android.ext.android.inject +import java.util.Locale class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { private var _binding: BottomSheetDnsLogBinding? = null @@ -553,9 +554,9 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { private fun lookupForImageDuckduckgo(url: String, domainUrl: String) { try { Logger.d( - LOG_TAG_DNS, - "Glide - TransactionViewHolder lookupForImageDuckduckgo: $url, $domainUrl" - ) + LOG_TAG_DNS, + "Glide - TransactionViewHolder lookupForImageDuckduckgo: $url, $domainUrl" + ) val factory = DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(true).build() Glide.with(requireContext().applicationContext) .load(url) @@ -580,9 +581,9 @@ class DnsBlocklistBottomSheet : BottomSheetDialogFragment() { transition: Transition? ) { Logger.d( - LOG_TAG_DNS, - "Glide - CustomViewTarget onResourceReady() -$url" - ) + LOG_TAG_DNS, + "Glide - CustomViewTarget onResourceReady() -$url" + ) if (!isAdded) return b.dnsBlockFavIcon.visibility = View.VISIBLE diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/HomeScreenSettingBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/HomeScreenSettingBottomSheet.kt index e77499e80..0f1002e43 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/HomeScreenSettingBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/HomeScreenSettingBottomSheet.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.bottomsheet +import Logger import Logger.LOG_TAG_VPN import android.content.res.Configuration import android.os.Bundle diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/LocalBlocklistsBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/LocalBlocklistsBottomSheet.kt index 06091fa56..775cc8254 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/LocalBlocklistsBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/LocalBlocklistsBottomSheet.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.bottomsheet +import Logger import Logger.LOG_TAG_DNS import android.content.DialogInterface import android.content.Intent diff --git a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/RethinkLogBottomSheet.kt b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/RethinkLogBottomSheet.kt index 0f01e1a31..4b0a71e8a 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/RethinkLogBottomSheet.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/bottomsheet/RethinkLogBottomSheet.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.bottomsheet +import Logger import Logger.LOG_TAG_FIREWALL import android.content.Intent import android.content.res.ColorStateList diff --git a/app/src/full/java/com/celzero/bravedns/ui/dialog/WgAddPeerDialog.kt b/app/src/full/java/com/celzero/bravedns/ui/dialog/WgAddPeerDialog.kt index 28192acaa..da0785244 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/dialog/WgAddPeerDialog.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/dialog/WgAddPeerDialog.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.dialog +import Logger import android.app.Activity import android.app.Dialog import android.os.Bundle diff --git a/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt b/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt index 93eb883c2..94a8c3cba 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.dialog +import Logger import Logger.LOG_TAG_PROXY import android.app.Activity import android.app.Dialog diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/AboutFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/AboutFragment.kt index 856a2f883..8fa9df176 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/AboutFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/AboutFragment.kt @@ -15,6 +15,7 @@ limitations under the License. */ package com.celzero.bravedns.ui.fragment +import Logger import Logger.LOG_TAG_UI import android.content.ActivityNotFoundException import android.content.DialogInterface @@ -61,17 +62,17 @@ import com.celzero.bravedns.util.Utilities.isFdroidFlavour import com.celzero.bravedns.util.Utilities.isPlayStoreFlavour import com.celzero.bravedns.util.Utilities.showToastUiCentered import com.google.android.material.dialog.MaterialAlertDialogBuilder +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.koin.android.ext.android.inject +import org.koin.core.component.KoinComponent import java.io.File import java.io.FileInputStream import java.util.concurrent.TimeUnit import java.util.zip.ZipEntry import java.util.zip.ZipFile import java.util.zip.ZipInputStream -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -import org.koin.android.ext.android.inject -import org.koin.core.component.KoinComponent class AboutFragment : Fragment(R.layout.fragment_about), View.OnClickListener, KoinComponent { private val b by viewBinding(FragmentAboutBinding::bind) diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsCryptListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsCryptListFragment.kt index 62cffff1b..05f4c1982 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsCryptListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsCryptListFragment.kt @@ -110,9 +110,7 @@ class DnsCryptListFragment : Fragment(R.layout.fragment_dns_crypt_list) { private fun showAddDnsCryptDialog() { val dialogBinding = DialogSetDnsCryptBinding.inflate(layoutInflater) - val builder = - MaterialAlertDialogBuilder(requireContext()) - .setView(dialogBinding.root) + val builder = MaterialAlertDialogBuilder(requireContext()).setView(dialogBinding.root) val lp = WindowManager.LayoutParams() val dialog = builder.create() diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt index c82fc6e71..744c2863f 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsProxyListFragment.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.fragment +import Logger import android.os.Bundle import android.view.View import android.view.WindowManager diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsSettingsFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsSettingsFragment.kt index a6cbc6ca4..14f4c58b6 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsSettingsFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsSettingsFragment.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.fragment +import Logger import android.content.Intent import android.os.Bundle import android.view.View diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/DoTListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/DoTListFragment.kt index 1db15b5fe..b82ac5082 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/DoTListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/DoTListFragment.kt @@ -75,8 +75,7 @@ class DoTListFragment : Fragment(R.layout.fragment_dot_list) { private fun showAddDialog() { val dialogBinding = DialogSetCustomDohBinding.inflate(layoutInflater) - val builder = - MaterialAlertDialogBuilder(requireContext()).setView(dialogBinding.root) + val builder = MaterialAlertDialogBuilder(requireContext()).setView(dialogBinding.root) val lp = WindowManager.LayoutParams() val dialog = builder.create() dialog.show() diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/DohListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/DohListFragment.kt index 0dbe3b958..a22b4be1e 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/DohListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/DohListFragment.kt @@ -15,7 +15,6 @@ */ package com.celzero.bravedns.ui.fragment -import android.app.Dialog import android.os.Bundle import android.view.View import android.view.WindowManager @@ -33,14 +32,14 @@ import com.celzero.bravedns.databinding.DialogSetCustomDohBinding import com.celzero.bravedns.databinding.FragmentDohListBinding import com.celzero.bravedns.viewmodel.DoHEndpointViewModel import com.google.android.material.dialog.MaterialAlertDialogBuilder -import java.net.MalformedURLException -import java.net.URL import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.koin.android.ext.android.get import org.koin.android.ext.android.inject import org.koin.androidx.viewmodel.ext.android.viewModel +import java.net.MalformedURLException +import java.net.URL class DohListFragment : Fragment(R.layout.fragment_doh_list) { private val b by viewBinding(FragmentDohListBinding::bind) @@ -86,8 +85,7 @@ class DohListFragment : Fragment(R.layout.fragment_doh_list) { */ private fun showAddCustomDohDialog() { val dialogBinding = DialogSetCustomDohBinding.inflate(layoutInflater) - val builder = - MaterialAlertDialogBuilder(requireContext()).setView(dialogBinding.root) + val builder = MaterialAlertDialogBuilder(requireContext()).setView(dialogBinding.root) val lp = WindowManager.LayoutParams() val dialog = builder.create() dialog.show() diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt index 1f942e088..99c612b36 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.fragment +import Logger import Logger.LOG_TAG_UI import Logger.LOG_TAG_VPN import android.Manifest @@ -79,14 +80,14 @@ import com.celzero.bravedns.util.Utilities.showToastUiCentered import com.facebook.shimmer.Shimmer import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar -import java.util.* -import java.util.concurrent.TimeUnit import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.koin.android.ext.android.inject +import java.util.* +import java.util.concurrent.TimeUnit class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { private val b by viewBinding(FragmentHomeScreenBinding::bind) @@ -700,7 +701,11 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { b.fhsCardApps.visibility = View.GONE b.fhsCardAllowedApps.isSelected = true } catch (e: Exception) { // NoSuchElementException, ConcurrentModification - Logger.e(LOG_TAG_VPN, "error retrieving value from appInfos observer ${e.message}", e) + Logger.e( + LOG_TAG_VPN, + "error retrieving value from appInfos observer ${e.message}", + e + ) } } } @@ -741,9 +746,9 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { private fun batteryOptimizationActive(context: Context): Boolean { val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager Logger.d( - LOG_TAG_UI, - "ignore battery optimization: ${powerManager.isIgnoringBatteryOptimizations(context.packageName)}" - ) + LOG_TAG_UI, + "ignore battery optimization: ${powerManager.isIgnoringBatteryOptimizations(context.packageName)}" + ) return !powerManager.isIgnoringBatteryOptimizations(context.packageName) } @@ -773,9 +778,9 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager Logger.d( - LOG_TAG_UI, - "restrict background status: ${connectivityManager.restrictBackgroundStatus}" - ) + LOG_TAG_UI, + "restrict background status: ${connectivityManager.restrictBackgroundStatus}" + ) return connectivityManager.restrictBackgroundStatus == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED } diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/ODoHListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/ODoHListFragment.kt index 36ae8b2ed..5fa401377 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/ODoHListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/ODoHListFragment.kt @@ -32,14 +32,14 @@ import com.celzero.bravedns.databinding.DialogSetCustomOdohBinding import com.celzero.bravedns.databinding.FragmentOdohListBinding import com.celzero.bravedns.viewmodel.ODoHEndpointViewModel import com.google.android.material.dialog.MaterialAlertDialogBuilder -import java.net.MalformedURLException -import java.net.URL import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.koin.android.ext.android.get import org.koin.android.ext.android.inject import org.koin.androidx.viewmodel.ext.android.viewModel +import java.net.MalformedURLException +import java.net.URL class ODoHListFragment : Fragment(R.layout.fragment_odoh_list) { private val b by viewBinding(FragmentOdohListBinding::bind) diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkBlocklistFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkBlocklistFragment.kt index 9722d26b2..a10e18253 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkBlocklistFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkBlocklistFragment.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.fragment +import Logger import Logger.LOG_TAG_UI import android.content.res.ColorStateList import android.os.Bundle @@ -823,7 +824,10 @@ class RethinkBlocklistFragment : workManager.getWorkInfosByTagLiveData(DOWNLOAD_TAG).observe(viewLifecycleOwner) { workInfoList -> val workInfo = workInfoList?.getOrNull(0) ?: return@observe - Logger.i(Logger.LOG_TAG_DOWNLOAD, "WorkManager state: ${workInfo.state} for $DOWNLOAD_TAG") + Logger.i( + Logger.LOG_TAG_DOWNLOAD, + "WorkManager state: ${workInfo.state} for $DOWNLOAD_TAG" + ) if ( WorkInfo.State.ENQUEUED == workInfo.state || WorkInfo.State.RUNNING == workInfo.state diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkListFragment.kt index 2da210e1f..2bb61bc19 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkListFragment.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.fragment +import Logger import android.content.Intent import android.os.Bundle import android.view.LayoutInflater diff --git a/app/src/full/java/com/celzero/bravedns/util/BackgroundAccessibilityService.kt b/app/src/full/java/com/celzero/bravedns/util/BackgroundAccessibilityService.kt index dc6ae661f..ca83ac169 100644 --- a/app/src/full/java/com/celzero/bravedns/util/BackgroundAccessibilityService.kt +++ b/app/src/full/java/com/celzero/bravedns/util/BackgroundAccessibilityService.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.util +import Logger import Logger.LOG_TAG_FIREWALL import android.accessibilityservice.AccessibilityService import android.content.Intent diff --git a/app/src/full/java/com/celzero/bravedns/util/QrCodeFromFileScanner.kt b/app/src/full/java/com/celzero/bravedns/util/QrCodeFromFileScanner.kt index edbc19190..72f5d788d 100644 --- a/app/src/full/java/com/celzero/bravedns/util/QrCodeFromFileScanner.kt +++ b/app/src/full/java/com/celzero/bravedns/util/QrCodeFromFileScanner.kt @@ -18,6 +18,7 @@ */ package com.celzero.bravedns.util +import Logger import Logger.LOG_QR_CODE import android.content.ContentResolver import android.graphics.Bitmap diff --git a/app/src/full/java/com/celzero/bravedns/util/RemoteFileTagUtil.kt b/app/src/full/java/com/celzero/bravedns/util/RemoteFileTagUtil.kt index c26c8bbcf..f71de3a40 100644 --- a/app/src/full/java/com/celzero/bravedns/util/RemoteFileTagUtil.kt +++ b/app/src/full/java/com/celzero/bravedns/util/RemoteFileTagUtil.kt @@ -15,14 +15,15 @@ */ package com.celzero.bravedns.util +import Logger import Logger.LOG_TAG_DOWNLOAD import android.content.Context import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.service.RethinkBlocklistManager +import org.koin.core.component.KoinComponent import java.io.File import java.io.IOException import java.io.InputStream -import org.koin.core.component.KoinComponent class RemoteFileTagUtil : KoinComponent { companion object { diff --git a/app/src/full/java/com/celzero/bravedns/util/TunnelImporter.kt b/app/src/full/java/com/celzero/bravedns/util/TunnelImporter.kt index 7cae5bca9..fc1266f04 100644 --- a/app/src/full/java/com/celzero/bravedns/util/TunnelImporter.kt +++ b/app/src/full/java/com/celzero/bravedns/util/TunnelImporter.kt @@ -18,6 +18,7 @@ */ package com.celzero.bravedns.util +import Logger import Logger.LOG_TAG_PROXY import android.content.ContentResolver import android.content.Context diff --git a/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt b/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt index 5e3c0b52e..80691a8d7 100644 --- a/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt +++ b/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.util +import Logger import android.content.ActivityNotFoundException import android.content.ClipData import android.content.ClipboardManager diff --git a/app/src/main/java/com/celzero/bravedns/backup/BackupAgent.kt b/app/src/main/java/com/celzero/bravedns/backup/BackupAgent.kt index fb9779d94..b6ca4c373 100644 --- a/app/src/main/java/com/celzero/bravedns/backup/BackupAgent.kt +++ b/app/src/main/java/com/celzero/bravedns/backup/BackupAgent.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.backup +import Logger import Logger.LOG_TAG_BACKUP_RESTORE import android.content.Context import android.content.SharedPreferences diff --git a/app/src/main/java/com/celzero/bravedns/backup/BackupHelper.kt b/app/src/main/java/com/celzero/bravedns/backup/BackupHelper.kt index 4869113b8..ebf38bf11 100644 --- a/app/src/main/java/com/celzero/bravedns/backup/BackupHelper.kt +++ b/app/src/main/java/com/celzero/bravedns/backup/BackupHelper.kt @@ -15,8 +15,8 @@ */ package com.celzero.bravedns.backup +import Logger import android.content.Context -import android.util.Log import com.celzero.bravedns.R import com.celzero.bravedns.database.AppDatabase import com.celzero.bravedns.service.VpnController diff --git a/app/src/main/java/com/celzero/bravedns/backup/RestoreAgent.kt b/app/src/main/java/com/celzero/bravedns/backup/RestoreAgent.kt index 02a49bba4..6bb8f98bc 100644 --- a/app/src/main/java/com/celzero/bravedns/backup/RestoreAgent.kt +++ b/app/src/main/java/com/celzero/bravedns/backup/RestoreAgent.kt @@ -15,16 +15,15 @@ */ package com.celzero.bravedns.backup +import Logger import Logger.LOG_TAG_BACKUP_RESTORE import android.content.Context import android.content.SharedPreferences import android.content.pm.PackageInfo import android.net.Uri -import android.util.Log import androidx.preference.PreferenceManager import androidx.work.CoroutineWorker import androidx.work.WorkerParameters -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.backup.BackupHelper.Companion.DATA_BUILDER_RESTORE_URI import com.celzero.bravedns.backup.BackupHelper.Companion.METADATA_FILENAME import com.celzero.bravedns.backup.BackupHelper.Companion.SHARED_PREFS_BACKUP_FILE_NAME @@ -182,15 +181,15 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : } Logger.d( - LOG_TAG_BACKUP_RESTORE, - "List of files in backup folder: ${files.size}, path: ${tempDir.path}" - ) + LOG_TAG_BACKUP_RESTORE, + "List of files in backup folder: ${files.size}, path: ${tempDir.path}" + ) for (file in files) { val currentDbFile = File(context.getDatabasePath(file.name).path) Logger.d( - LOG_TAG_BACKUP_RESTORE, - "db file: ${file.name} backed up from ${file.path} to ${currentDbFile.path}" - ) + LOG_TAG_BACKUP_RESTORE, + "db file: ${file.name} backed up from ${file.path} to ${currentDbFile.path}" + ) if ( !file.name.contains(AppDatabase.DATABASE_NAME) && @@ -343,7 +342,11 @@ class RestoreAgent(val context: Context, workerParams: WorkerParameters) : // there is only one database), so do not consider the backups prior to that return version >= minVersionSupported && persistentState.appVersion >= version } catch (e: Exception) { - Logger.e(LOG_TAG_BACKUP_RESTORE, "error while reading metadata, reason? ${e.message}", e) + Logger.e( + LOG_TAG_BACKUP_RESTORE, + "error while reading metadata, reason? ${e.message}", + e + ) return false } } diff --git a/app/src/main/java/com/celzero/bravedns/data/AppConfig.kt b/app/src/main/java/com/celzero/bravedns/data/AppConfig.kt index 9383d957f..d97bf5dee 100644 --- a/app/src/main/java/com/celzero/bravedns/data/AppConfig.kt +++ b/app/src/main/java/com/celzero/bravedns/data/AppConfig.kt @@ -15,13 +15,13 @@ */ package com.celzero.bravedns.data +import Logger import Logger.LOG_TAG_VPN import android.content.Context import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.database.ConnectionTrackerRepository import com.celzero.bravedns.database.DnsCryptEndpoint import com.celzero.bravedns.database.DnsCryptEndpointRepository diff --git a/app/src/main/java/com/celzero/bravedns/database/LogDatabase.kt b/app/src/main/java/com/celzero/bravedns/database/LogDatabase.kt index 9142f178c..e071dbb7f 100644 --- a/app/src/main/java/com/celzero/bravedns/database/LogDatabase.kt +++ b/app/src/main/java/com/celzero/bravedns/database/LogDatabase.kt @@ -15,11 +15,11 @@ */ package com.celzero.bravedns.database +import Logger import android.content.Context import android.content.pm.PackageInfo import android.database.Cursor import android.database.sqlite.SQLiteException -import android.util.Log import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase diff --git a/app/src/main/java/com/celzero/bravedns/database/RefreshDatabase.kt b/app/src/main/java/com/celzero/bravedns/database/RefreshDatabase.kt index ba95478f8..93ee3b846 100644 --- a/app/src/main/java/com/celzero/bravedns/database/RefreshDatabase.kt +++ b/app/src/main/java/com/celzero/bravedns/database/RefreshDatabase.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.database +import Logger import Logger.LOG_TAG_APP_DB import Logger.LOG_TAG_VPN import android.app.NotificationChannel diff --git a/app/src/main/java/com/celzero/bravedns/glide/FavIconDownloader.kt b/app/src/main/java/com/celzero/bravedns/glide/FavIconDownloader.kt index 4d89e39a2..c0d235f4f 100644 --- a/app/src/main/java/com/celzero/bravedns/glide/FavIconDownloader.kt +++ b/app/src/main/java/com/celzero/bravedns/glide/FavIconDownloader.kt @@ -15,6 +15,7 @@ limitations under the License. */ package com.celzero.bravedns.glide +import Logger import Logger.LOG_TAG_DNS import android.content.Context import android.os.Process diff --git a/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt b/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt index de60353c2..aeeb031ac 100644 --- a/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt +++ b/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt @@ -16,6 +16,7 @@ */ package com.celzero.bravedns.net.go +import Logger import Logger.LOG_TAG_VPN import android.content.Context import android.content.res.Resources @@ -847,9 +848,9 @@ class GoVpnAdapter : KoinComponent { val wgUserSpaceString = secWarp.toWgUserspaceString() val ok2 = getProxies()?.addProxy(ID_WG_BASE + secWarp.getId(), wgUserSpaceString) Logger.d( - LOG_TAG_VPN, - "tcp-mode(wg) set(${ID_WG_BASE+ secWarp.getId()}): ${secWarp.getName()}, res: $ok2" - ) + LOG_TAG_VPN, + "tcp-mode(wg) set(${ID_WG_BASE+ secWarp.getId()}): ${secWarp.getName()}, res: $ok2" + ) } fun hasTunnel(): Boolean { diff --git a/app/src/main/java/com/celzero/bravedns/net/manager/ConnectionTracer.kt b/app/src/main/java/com/celzero/bravedns/net/manager/ConnectionTracer.kt index 0559a491b..e88837565 100644 --- a/app/src/main/java/com/celzero/bravedns/net/manager/ConnectionTracer.kt +++ b/app/src/main/java/com/celzero/bravedns/net/manager/ConnectionTracer.kt @@ -1,5 +1,6 @@ package com.celzero.bravedns.net.manager +import Logger import Logger.LOG_TAG_VPN import android.annotation.TargetApi import android.content.Context diff --git a/app/src/main/java/com/celzero/bravedns/scheduler/DataUsageUpdater.kt b/app/src/main/java/com/celzero/bravedns/scheduler/DataUsageUpdater.kt index 33fa81183..be566a5c0 100644 --- a/app/src/main/java/com/celzero/bravedns/scheduler/DataUsageUpdater.kt +++ b/app/src/main/java/com/celzero/bravedns/scheduler/DataUsageUpdater.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.scheduler +import Logger import Logger.LOG_TAG_SCHEDULER import android.content.Context import androidx.work.CoroutineWorker diff --git a/app/src/main/java/com/celzero/bravedns/scheduler/RefreshAppsJob.kt b/app/src/main/java/com/celzero/bravedns/scheduler/RefreshAppsJob.kt index b0cf3e32b..c6662f97d 100644 --- a/app/src/main/java/com/celzero/bravedns/scheduler/RefreshAppsJob.kt +++ b/app/src/main/java/com/celzero/bravedns/scheduler/RefreshAppsJob.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.scheduler +import Logger import Logger.LOG_TAG_SCHEDULER import android.content.Context import androidx.work.CoroutineWorker diff --git a/app/src/main/java/com/celzero/bravedns/scheduler/ScheduleManager.kt b/app/src/main/java/com/celzero/bravedns/scheduler/ScheduleManager.kt index fd5f5d549..170a14074 100644 --- a/app/src/main/java/com/celzero/bravedns/scheduler/ScheduleManager.kt +++ b/app/src/main/java/com/celzero/bravedns/scheduler/ScheduleManager.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.scheduler +import Logger import Logger.LOG_TAG_SCHEDULER import android.content.Context import androidx.work.ExistingPeriodicWorkPolicy diff --git a/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt b/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt index eeb10b22c..2e1b7705f 100644 --- a/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt +++ b/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt @@ -16,6 +16,7 @@ */ package com.celzero.bravedns.service +import Logger import Logger.LOG_TAG_VPN import android.app.ActivityManager import android.app.ForegroundServiceStartNotAllowedException @@ -98,18 +99,6 @@ import inet.ipaddr.HostName import inet.ipaddr.IPAddressString import intra.Bridge import intra.SocketSummary -import java.io.IOException -import java.net.InetAddress -import java.net.SocketException -import java.net.UnknownHostException -import java.util.Collections -import java.util.Locale -import java.util.concurrent.ConcurrentHashMap -import java.util.concurrent.TimeUnit -import java.util.concurrent.atomic.AtomicBoolean -import kotlin.math.abs -import kotlin.math.min -import kotlin.random.Random import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers @@ -122,6 +111,18 @@ import kotlinx.coroutines.withContext import org.koin.android.ext.android.inject import rnet.ServerSummary import rnet.Tab +import java.io.IOException +import java.net.InetAddress +import java.net.SocketException +import java.net.UnknownHostException +import java.util.Collections +import java.util.Locale +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import kotlin.math.abs +import kotlin.math.min +import kotlin.random.Random class BraveVPNService : VpnService(), ConnectionMonitor.NetworkListener, Bridge, OnSharedPreferenceChangeListener { @@ -1122,7 +1123,11 @@ class BraveVPNService : io("excludeApps") { restartVpnWithNewAppConfig(reason = "excludeApps") } } catch (e: Exception) { // NoSuchElementException, ConcurrentModification - Logger.e(LOG_TAG_VPN, "error retrieving value from appInfos observer ${e.message}", e) + Logger.e( + LOG_TAG_VPN, + "error retrieving value from appInfos observer ${e.message}", + e + ) } } } @@ -2416,7 +2421,10 @@ class BraveVPNService : val interestingNet = interestingNetworkChanges(aux = nw) val isRoutesChanged = interestingNet.routesChanged val isMtuChanged = interestingNet.mtuChanged - Logger.i(LOG_TAG_VPN, "overlay: routes changed? $isRoutesChanged, mtu changed? $isMtuChanged") + Logger.i( + LOG_TAG_VPN, + "overlay: routes changed? $isRoutesChanged, mtu changed? $isMtuChanged" + ) overlayNetworks = nw if (isRoutesChanged || isMtuChanged) { Logger.i(LOG_TAG_VPN, "overlay changed $overlayNetworks, restart vpn") diff --git a/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt b/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt index 6b0ca4045..ead935df4 100644 --- a/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt +++ b/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.service +import Logger import Logger.LOG_TAG_CONNECTION import android.content.Context import android.net.ConnectivityManager @@ -35,6 +36,9 @@ import com.celzero.bravedns.util.Utilities.isAtleastQ import com.celzero.bravedns.util.Utilities.isAtleastS import com.celzero.bravedns.util.Utilities.isNetworkSame import com.google.common.collect.Sets +import kotlinx.coroutines.runBlocking +import org.koin.core.component.KoinComponent +import org.koin.core.component.inject import java.io.Closeable import java.io.IOException import java.net.DatagramSocket @@ -48,9 +52,6 @@ import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit import kotlin.math.max import kotlin.math.min -import kotlinx.coroutines.runBlocking -import org.koin.core.component.KoinComponent -import org.koin.core.component.inject class ConnectionMonitor(private val networkListener: NetworkListener) : ConnectivityManager.NetworkCallback(), KoinComponent { diff --git a/app/src/main/java/com/celzero/bravedns/service/DomainRulesManager.kt b/app/src/main/java/com/celzero/bravedns/service/DomainRulesManager.kt index a48c3c9dc..0f785b286 100644 --- a/app/src/main/java/com/celzero/bravedns/service/DomainRulesManager.kt +++ b/app/src/main/java/com/celzero/bravedns/service/DomainRulesManager.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.service +import Logger import Logger.LOG_TAG_DNS import android.content.Context import android.util.Patterns diff --git a/app/src/main/java/com/celzero/bravedns/service/EncryptedFileManager.kt b/app/src/main/java/com/celzero/bravedns/service/EncryptedFileManager.kt index a52d9a9d0..1a7bc184d 100644 --- a/app/src/main/java/com/celzero/bravedns/service/EncryptedFileManager.kt +++ b/app/src/main/java/com/celzero/bravedns/service/EncryptedFileManager.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.service +import Logger import android.content.Context import androidx.security.crypto.EncryptedFile import androidx.security.crypto.MasterKey diff --git a/app/src/main/java/com/celzero/bravedns/service/FirewallManager.kt b/app/src/main/java/com/celzero/bravedns/service/FirewallManager.kt index 14088e0df..030ea7cbb 100644 --- a/app/src/main/java/com/celzero/bravedns/service/FirewallManager.kt +++ b/app/src/main/java/com/celzero/bravedns/service/FirewallManager.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.service +import Logger import Logger.LOG_TAG_FIREWALL import android.app.KeyguardManager import android.content.Context diff --git a/app/src/main/java/com/celzero/bravedns/service/IPTracker.kt b/app/src/main/java/com/celzero/bravedns/service/IPTracker.kt index 40ff8a593..009f7fa03 100644 --- a/app/src/main/java/com/celzero/bravedns/service/IPTracker.kt +++ b/app/src/main/java/com/celzero/bravedns/service/IPTracker.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.service +import Logger import Logger.LOG_TAG_FIREWALL import android.content.Context import com.celzero.bravedns.R diff --git a/app/src/main/java/com/celzero/bravedns/service/IpRulesManager.kt b/app/src/main/java/com/celzero/bravedns/service/IpRulesManager.kt index bf8cae4ad..3866ea0c5 100644 --- a/app/src/main/java/com/celzero/bravedns/service/IpRulesManager.kt +++ b/app/src/main/java/com/celzero/bravedns/service/IpRulesManager.kt @@ -15,12 +15,12 @@ */ package com.celzero.bravedns.service +import Logger import Logger.LOG_TAG_FIREWALL import android.content.Context import androidx.lifecycle.LiveData import backend.Backend import com.celzero.bravedns.R -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.database.CustomIp import com.celzero.bravedns.database.CustomIpRepository import com.celzero.bravedns.util.Constants diff --git a/app/src/main/java/com/celzero/bravedns/service/NetLogTracker.kt b/app/src/main/java/com/celzero/bravedns/service/NetLogTracker.kt index 6aa4ef547..f2ff5c807 100644 --- a/app/src/main/java/com/celzero/bravedns/service/NetLogTracker.kt +++ b/app/src/main/java/com/celzero/bravedns/service/NetLogTracker.kt @@ -49,8 +49,7 @@ internal constructor( private var scope: CoroutineScope? = null - private var dnsdb: DnsLogTracker = - DnsLogTracker(dnsLogRepository, persistentState, context) + private var dnsdb: DnsLogTracker = DnsLogTracker(dnsLogRepository, persistentState, context) private var ipdb: IPTracker = IPTracker(connectionTrackerRepository, rethinkLogRepository, context) diff --git a/app/src/main/java/com/celzero/bravedns/service/PauseTimer.kt b/app/src/main/java/com/celzero/bravedns/service/PauseTimer.kt index 6eac7e594..42a3e7e26 100644 --- a/app/src/main/java/com/celzero/bravedns/service/PauseTimer.kt +++ b/app/src/main/java/com/celzero/bravedns/service/PauseTimer.kt @@ -15,10 +15,10 @@ */ package com.celzero.bravedns.service +import Logger import Logger.LOG_TAG_UI import Logger.LOG_TAG_VPN import androidx.lifecycle.MutableLiveData -import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import com.celzero.bravedns.util.Constants.Companion.INIT_TIME_MS import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers diff --git a/app/src/main/java/com/celzero/bravedns/service/PersistentState.kt b/app/src/main/java/com/celzero/bravedns/service/PersistentState.kt index 5913cb9ea..eba1c2341 100644 --- a/app/src/main/java/com/celzero/bravedns/service/PersistentState.kt +++ b/app/src/main/java/com/celzero/bravedns/service/PersistentState.kt @@ -284,10 +284,7 @@ class PersistentState(context: Context) : SimpleKrate(context), KoinComponent { var proxyStatus: MutableLiveData = MutableLiveData() // data class to store dnscrypt relay details - data class DnsCryptRelayDetails( - val relay: DnsCryptRelayEndpoint, - val added: Boolean - ) + data class DnsCryptRelayDetails(val relay: DnsCryptRelayEndpoint, val added: Boolean) var dnsCryptRelays: MutableLiveData = MutableLiveData() diff --git a/app/src/main/java/com/celzero/bravedns/service/RethinkBlocklistManager.kt b/app/src/main/java/com/celzero/bravedns/service/RethinkBlocklistManager.kt index 3757f3068..a33e48de4 100644 --- a/app/src/main/java/com/celzero/bravedns/service/RethinkBlocklistManager.kt +++ b/app/src/main/java/com/celzero/bravedns/service/RethinkBlocklistManager.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.service +import Logger import Logger.LOG_TAG_DNS import Logger.LOG_TAG_VPN import android.content.Context @@ -188,7 +189,8 @@ object RethinkBlocklistManager : KoinComponent { Logger.i(LOG_TAG_DNS, "New Local blocklist files inserted into database") return true } catch (ioException: IOException) { - Logger.e(LOG_TAG_DNS, + Logger.e( + LOG_TAG_DNS, "Failure reading json file, blocklist type: remote, timestamp: $timestamp", ioException ) @@ -271,7 +273,8 @@ object RethinkBlocklistManager : KoinComponent { Logger.i(LOG_TAG_DNS, "New Remote blocklist files inserted into database") return true } catch (ioException: IOException) { - Logger.e(LOG_TAG_DNS, + Logger.e( + LOG_TAG_DNS, "Failure reading json file, blocklist type: remote, timestamp: $timestamp", ioException ) @@ -371,9 +374,9 @@ object RethinkBlocklistManager : KoinComponent { return try { val flags = convertListToCsv(fileValues) Logger.d( - LOG_TAG_VPN, - "${type.name} flags: $flags, ${getRDNS(type)?.flagsToStamp(flags, Backend.EB32)}" - ) + LOG_TAG_VPN, + "${type.name} flags: $flags, ${getRDNS(type)?.flagsToStamp(flags, Backend.EB32)}" + ) getRDNS(type)?.flagsToStamp(flags, Backend.EB32) ?: "" } catch (e: java.lang.Exception) { Logger.e(LOG_TAG_VPN, "err stamp2tags: ${e.message}, $e") diff --git a/app/src/main/java/com/celzero/bravedns/service/VpnController.kt b/app/src/main/java/com/celzero/bravedns/service/VpnController.kt index 48efb9432..2f5f6025c 100644 --- a/app/src/main/java/com/celzero/bravedns/service/VpnController.kt +++ b/app/src/main/java/com/celzero/bravedns/service/VpnController.kt @@ -16,6 +16,7 @@ */ package com.celzero.bravedns.service +import Logger import Logger.LOG_TAG_VPN import android.content.Context import android.content.Intent diff --git a/app/src/main/java/com/celzero/bravedns/util/IPUtil.kt b/app/src/main/java/com/celzero/bravedns/util/IPUtil.kt index 24624643f..0e25f415e 100644 --- a/app/src/main/java/com/celzero/bravedns/util/IPUtil.kt +++ b/app/src/main/java/com/celzero/bravedns/util/IPUtil.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.util +import Logger import Logger.LOG_TAG_VPN import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG import inet.ipaddr.IPAddress diff --git a/app/src/main/java/com/celzero/bravedns/util/NetLogBatcher.kt b/app/src/main/java/com/celzero/bravedns/util/NetLogBatcher.kt index 729b8a9c9..dfce43df2 100644 --- a/app/src/main/java/com/celzero/bravedns/util/NetLogBatcher.kt +++ b/app/src/main/java/com/celzero/bravedns/util/NetLogBatcher.kt @@ -16,6 +16,7 @@ package com.celzero.bravedns.util +import Logger import Logger.LOG_BATCH_LOGGER import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.CoroutineScope diff --git a/app/src/main/java/com/celzero/bravedns/util/OrbotHelper.kt b/app/src/main/java/com/celzero/bravedns/util/OrbotHelper.kt index 2bf3653b4..46108b73d 100644 --- a/app/src/main/java/com/celzero/bravedns/util/OrbotHelper.kt +++ b/app/src/main/java/com/celzero/bravedns/util/OrbotHelper.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.util +import Logger import Logger.LOG_TAG_VPN import android.app.NotificationChannel import android.app.NotificationManager @@ -48,13 +49,13 @@ import com.celzero.bravedns.util.Utilities.isAtleastT import com.celzero.bravedns.util.Utilities.isFdroidFlavour import com.celzero.bravedns.util.Utilities.isPlayStoreFlavour import com.celzero.bravedns.util.Utilities.isValidPort -import java.net.URI -import java.util.concurrent.TimeUnit import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import java.net.URI +import java.util.concurrent.TimeUnit /** * One-click Orbot setup. diff --git a/app/src/main/java/com/celzero/bravedns/util/Utilities.kt b/app/src/main/java/com/celzero/bravedns/util/Utilities.kt index 5b94e8aa8..98dd85dd4 100644 --- a/app/src/main/java/com/celzero/bravedns/util/Utilities.kt +++ b/app/src/main/java/com/celzero/bravedns/util/Utilities.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.util +import Logger import Logger.LOG_TAG_APP_DB import Logger.LOG_TAG_DOWNLOAD import Logger.LOG_TAG_FIREWALL @@ -122,7 +123,10 @@ object Utilities { am.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK) for (enabledService in enabledServices) { val enabledServiceInfo: ServiceInfo = enabledService.resolveInfo.serviceInfo - Logger.i(LOG_TAG_VPN, "Accessibility enabled check for: ${enabledServiceInfo.packageName}") + Logger.i( + LOG_TAG_VPN, + "Accessibility enabled check for: ${enabledServiceInfo.packageName}" + ) if ( enabledServiceInfo.packageName == context.packageName && enabledServiceInfo.name == service.name @@ -155,9 +159,9 @@ object Utilities { val enabledService = ComponentName.unflattenFromString(componentNameString) if (expectedComponentName == enabledService) { Logger.i( - LOG_TAG_VPN, - "SettingsSecure accessibility enabled for: ${expectedComponentName.packageName}" - ) + LOG_TAG_VPN, + "SettingsSecure accessibility enabled for: ${expectedComponentName.packageName}" + ) return true } } @@ -533,10 +537,7 @@ object Utilities { } else { fileOrDirectory.delete() } - Logger.d( - LOG_TAG_DOWNLOAD, - "deleteRecursive File : ${fileOrDirectory.path}, $isDeleted" - ) + Logger.d(LOG_TAG_DOWNLOAD, "deleteRecursive File : ${fileOrDirectory.path}, $isDeleted") } catch (e: Exception) { Logger.w(LOG_TAG_DOWNLOAD, "File delete exception: ${e.message}", e) } From 04c72763d5a0bcd51b939a1c9675a74b05f21b8a Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Sat, 20 Apr 2024 20:26:12 +0530 Subject: [PATCH 27/48] ktfmt code --- .../full/java/com/celzero/bravedns/NonStoreAppUpdater.kt | 1 + .../java/com/celzero/bravedns/RethinkDnsApplication.kt | 1 + .../bravedns/customdownloader/LocalBlocklistCoordinator.kt | 7 ++++--- .../customdownloader/RemoteBlocklistCoordinator.kt | 7 ++++++- 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/NonStoreAppUpdater.kt b/app/src/full/java/com/celzero/bravedns/NonStoreAppUpdater.kt index 64120c0cc..73d25c063 100644 --- a/app/src/full/java/com/celzero/bravedns/NonStoreAppUpdater.kt +++ b/app/src/full/java/com/celzero/bravedns/NonStoreAppUpdater.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns +import Logger import Logger.LOG_TAG_APP_UPDATE import android.app.Activity import com.celzero.bravedns.customdownloader.RetrofitManager diff --git a/app/src/full/java/com/celzero/bravedns/RethinkDnsApplication.kt b/app/src/full/java/com/celzero/bravedns/RethinkDnsApplication.kt index 4a4ff29ca..41cb7fbb5 100644 --- a/app/src/full/java/com/celzero/bravedns/RethinkDnsApplication.kt +++ b/app/src/full/java/com/celzero/bravedns/RethinkDnsApplication.kt @@ -1,5 +1,6 @@ package com.celzero.bravedns +import Logger import Logger.LOG_TAG_SCHEDULER import android.app.Application import android.content.pm.ApplicationInfo diff --git a/app/src/full/java/com/celzero/bravedns/customdownloader/LocalBlocklistCoordinator.kt b/app/src/full/java/com/celzero/bravedns/customdownloader/LocalBlocklistCoordinator.kt index 6d34dca41..c8a54c7cb 100644 --- a/app/src/full/java/com/celzero/bravedns/customdownloader/LocalBlocklistCoordinator.kt +++ b/app/src/full/java/com/celzero/bravedns/customdownloader/LocalBlocklistCoordinator.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.customdownloader +import Logger import Logger.LOG_TAG_DOWNLOAD import android.app.NotificationChannel import android.app.NotificationManager @@ -44,6 +45,9 @@ import com.celzero.bravedns.util.Utilities.blocklistDownloadBasePath import com.celzero.bravedns.util.Utilities.calculateMd5 import com.celzero.bravedns.util.Utilities.getTagValueFromJson import com.celzero.bravedns.util.Utilities.tempDownloadBasePath +import okhttp3.ResponseBody +import org.koin.core.component.KoinComponent +import org.koin.core.component.inject import java.io.BufferedInputStream import java.io.File import java.io.FileOutputStream @@ -53,9 +57,6 @@ import java.io.OutputStream import java.util.concurrent.CancellationException import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit -import okhttp3.ResponseBody -import org.koin.core.component.KoinComponent -import org.koin.core.component.inject class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParameters) : CoroutineWorker(context, workerParams), KoinComponent { diff --git a/app/src/full/java/com/celzero/bravedns/customdownloader/RemoteBlocklistCoordinator.kt b/app/src/full/java/com/celzero/bravedns/customdownloader/RemoteBlocklistCoordinator.kt index 45ee97f6d..fb819bee4 100644 --- a/app/src/full/java/com/celzero/bravedns/customdownloader/RemoteBlocklistCoordinator.kt +++ b/app/src/full/java/com/celzero/bravedns/customdownloader/RemoteBlocklistCoordinator.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.customdownloader +import Logger import Logger.LOG_TAG_DOWNLOAD import android.content.Context import android.os.SystemClock @@ -164,7 +165,11 @@ class RemoteBlocklistCoordinator(val context: Context, workerParams: WorkerParam } return filePath } catch (e: IOException) { - Logger.e(LOG_TAG_DOWNLOAD, "err creating remote blocklist, ts: $timestamp" + e.message, e) + Logger.e( + LOG_TAG_DOWNLOAD, + "err creating remote blocklist, ts: $timestamp" + e.message, + e + ) } return null } From bffabf63506989aa9f0a79e0c495dcca25e178ed Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Mon, 22 Apr 2024 21:10:26 +0530 Subject: [PATCH 28/48] Fix: #1137, add unselected filter in proxy app screen in wg --- .../bravedns/ui/activity/WgMainActivity.kt | 2 +- .../bravedns/ui/dialog/WgIncludeAppsDialog.kt | 15 ++++++++++++++- .../viewmodel/ProxyAppsMappingViewModel.kt | 11 +++++++---- .../database/ProxyApplicationMappingDAO.kt | 8 ++++++++ .../main/res/layout/wg_apps_include_dialog.xml | 2 +- 5 files changed, 31 insertions(+), 7 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/WgMainActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/WgMainActivity.kt index c642205ca..ff2f72d76 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/WgMainActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/WgMainActivity.kt @@ -281,7 +281,7 @@ class WgMainActivity : val activeConfigs = WireguardManager.getEnabledConfigs() val isAnyConfigActive = activeConfigs.isNotEmpty() if (isAnyConfigActive) { - val dnsName = activeConfigs.first().getName() + val dnsName = activeConfigs.firstOrNull()?.getName() ?: return b.wgWireguardDisclaimer.text = getString(R.string.wireguard_disclaimer, dnsName) } // remove the observer if any config is active diff --git a/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt b/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt index 94a8c3cba..72846e715 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt @@ -75,12 +75,14 @@ class WgIncludeAppsDialog( enum class TopLevelFilter(val id: Int) { ALL_APPS(0), - SELECTED_APPS(1); + SELECTED_APPS(1), + UNSELECTED_APPS(2); fun getLabelId(): Int { return when (this) { ALL_APPS -> R.string.lbl_all SELECTED_APPS -> R.string.rt_filter_parent_selected + UNSELECTED_APPS -> R.string.lbl_unselected } } } @@ -147,8 +149,15 @@ class WgIncludeAppsDialog( false ) + val unselected = makeFirewallChip( + TopLevelFilter.UNSELECTED_APPS.id, + activity.getString(TopLevelFilter.UNSELECTED_APPS.getLabelId()), + false + ) + b.wgIncludeAppDialogChipGroup.addView(all) b.wgIncludeAppDialogChipGroup.addView(selected) + b.wgIncludeAppDialogChipGroup.addView(unselected) } private fun makeFirewallChip(id: Int, label: String, checked: Boolean): Chip { @@ -190,6 +199,10 @@ class WgIncludeAppsDialog( filterType = TopLevelFilter.SELECTED_APPS viewModel.setFilter(searchText, filterType, proxyId) } + TopLevelFilter.UNSELECTED_APPS.id -> { + filterType = TopLevelFilter.UNSELECTED_APPS + viewModel.setFilter(searchText, filterType, proxyId) + } } } diff --git a/app/src/full/java/com/celzero/bravedns/viewmodel/ProxyAppsMappingViewModel.kt b/app/src/full/java/com/celzero/bravedns/viewmodel/ProxyAppsMappingViewModel.kt index 59ea08cb5..064cb3f4c 100644 --- a/app/src/full/java/com/celzero/bravedns/viewmodel/ProxyAppsMappingViewModel.kt +++ b/app/src/full/java/com/celzero/bravedns/viewmodel/ProxyAppsMappingViewModel.kt @@ -44,10 +44,13 @@ class ProxyAppsMappingViewModel(private val mappingDAO: ProxyApplicationMappingD var apps = filteredList.switchMap { searchTxt -> Pager(PagingConfig(LIVEDATA_PAGE_SIZE)) { - if (filterType == WgIncludeAppsDialog.TopLevelFilter.SELECTED_APPS) { - mappingDAO.getSelectedAppsMapping(searchTxt, proxyId) - } else { - mappingDAO.getAllAppsMapping(searchTxt) + when (filterType) { + WgIncludeAppsDialog.TopLevelFilter.ALL_APPS -> + mappingDAO.getAllAppsMapping(searchTxt) + WgIncludeAppsDialog.TopLevelFilter.SELECTED_APPS -> + mappingDAO.getSelectedAppsMapping(searchTxt, proxyId) + WgIncludeAppsDialog.TopLevelFilter.UNSELECTED_APPS -> + mappingDAO.getUnSelectedAppsMapping(searchTxt, proxyId) } } .liveData diff --git a/app/src/main/java/com/celzero/bravedns/database/ProxyApplicationMappingDAO.kt b/app/src/main/java/com/celzero/bravedns/database/ProxyApplicationMappingDAO.kt index 245da1928..c603f9b63 100644 --- a/app/src/main/java/com/celzero/bravedns/database/ProxyApplicationMappingDAO.kt +++ b/app/src/main/java/com/celzero/bravedns/database/ProxyApplicationMappingDAO.kt @@ -59,6 +59,14 @@ interface ProxyApplicationMappingDAO { proxyId: String ): PagingSource + @Query( + "select * from ProxyApplicationMapping where appName like :appName and proxyId != :proxyId order by lower(appName)" + ) + fun getUnSelectedAppsMapping( + appName: String, + proxyId: String + ): PagingSource + @Query("select count(packageName) from ProxyApplicationMapping where proxyId = :id") fun getAppCountById(id: String): Int diff --git a/app/src/main/res/layout/wg_apps_include_dialog.xml b/app/src/main/res/layout/wg_apps_include_dialog.xml index 0621d1837..f810b1529 100644 --- a/app/src/main/res/layout/wg_apps_include_dialog.xml +++ b/app/src/main/res/layout/wg_apps_include_dialog.xml @@ -45,7 +45,7 @@ android:fontFamily="sans-serif" android:isScrollContainer="true" app:iconifiedByDefault="false" - app:queryHint="@string/search_proxy_add_apps"> + app:queryHint="@string/search_proxy_add_apps" /> Date: Mon, 22 Apr 2024 21:13:02 +0530 Subject: [PATCH 29/48] rmv logging of rethink own conns in nw logs --- .../main/java/com/celzero/bravedns/service/BraveVPNService.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt b/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt index 2e1b7705f..532a2efd5 100644 --- a/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt +++ b/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt @@ -3011,7 +3011,7 @@ class BraveVPNService : if (isRethink) { // case when uid is rethink, return Ipn.Base logd( - "flow: Ipn.Exit for rethink, $uid, $packageName, $srcIp, $srcPort, $realDestIp, $dstPort, $possibleDomains" + "flow: Ipn.Exit for rethink, $uid, $dup, $packageName, $srcIp, $srcPort, $realDestIp, $dstPort, $possibleDomains" ) if (cm.query.isNullOrEmpty()) { // possible domains only used for logging purposes, it may be available if @@ -3038,7 +3038,7 @@ class BraveVPNService : trackedCids.add(key) // TODO: set dup as true for now (v055f), need to handle dup properly in future - val duplicate = dup || DEBUG + val duplicate = dup || true // if the connection is Rethink's uid and if the dup is false, then the connections // are rethink's own connections, so add it in network log as well if (!duplicate) { From ed930e61b50aca574ae135da775a3508274efa8c Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Mon, 22 Apr 2024 21:13:13 +0530 Subject: [PATCH 30/48] bump firestack version --- app/build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index d8021f1d2..edb981e6e 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -247,8 +247,8 @@ dependencies { fullImplementation 'com.github.kirich1409:viewbindingpropertydelegate-noreflection:1.5.9' // from: https://jitpack.io/#celzero/firestack - download 'com.github.celzero:firestack:a945ad8429@aar' - implementation 'com.github.celzero:firestack:a945ad8429@aar' + download 'com.github.celzero:firestack:750d62fc48@aar' + implementation 'com.github.celzero:firestack:750d62fc48@aar' // Work manager implementation('androidx.work:work-runtime-ktx:2.9.0') { From f72a8886af5f7fe878ee3aa71890111d4c39a85e Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Tue, 23 Apr 2024 19:12:27 +0530 Subject: [PATCH 31/48] Fix: #1373, use filename as interface name on wg import --- .../java/com/celzero/bravedns/service/WireguardManager.kt | 6 +++--- .../full/java/com/celzero/bravedns/util/TunnelImporter.kt | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/service/WireguardManager.kt b/app/src/full/java/com/celzero/bravedns/service/WireguardManager.kt index 0b5a9b324..a9b2ce044 100644 --- a/app/src/full/java/com/celzero/bravedns/service/WireguardManager.kt +++ b/app/src/full/java/com/celzero/bravedns/service/WireguardManager.kt @@ -461,7 +461,7 @@ object WireguardManager : KoinComponent { return cfg } - suspend fun addConfig(config: Config?): Config? { + suspend fun addConfig(config: Config?, name: String = ""): Config? { if (config == null) { Logger.e(LOG_TAG_PROXY, "error adding config") return null @@ -469,11 +469,11 @@ object WireguardManager : KoinComponent { // increment the id and add the config lastAddedConfigId += 1 val id = lastAddedConfigId - val name = config.getName().ifEmpty { "${Backend.WG}$id" } + val n = name.ifEmpty { "${Backend.WG}$id" } val cfg = Config.Builder() .setId(id) - .setName(name) + .setName(n) .setInterface(config.getInterface()) .addPeers(config.getPeers()) .build() diff --git a/app/src/full/java/com/celzero/bravedns/util/TunnelImporter.kt b/app/src/full/java/com/celzero/bravedns/util/TunnelImporter.kt index fc1266f04..88428e4d5 100644 --- a/app/src/full/java/com/celzero/bravedns/util/TunnelImporter.kt +++ b/app/src/full/java/com/celzero/bravedns/util/TunnelImporter.kt @@ -103,13 +103,13 @@ object TunnelImporter : KoinComponent { } ?.let { config = it - WireguardManager.addConfig(config) + WireguardManager.addConfig(config, name) } } } } else { config = Config.parse(contentResolver.openInputStream(uri)!!) - WireguardManager.addConfig(config) + WireguardManager.addConfig(config, name) } if (config == null) { From 349e45b9b3d9ba500c8d4932fc176c043ec35351 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Tue, 23 Apr 2024 19:13:12 +0530 Subject: [PATCH 32/48] add unselected filter in proxy app screen in wg --- .../celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt b/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt index 72846e715..6f9f6a0d4 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/dialog/WgIncludeAppsDialog.kt @@ -149,11 +149,12 @@ class WgIncludeAppsDialog( false ) - val unselected = makeFirewallChip( - TopLevelFilter.UNSELECTED_APPS.id, - activity.getString(TopLevelFilter.UNSELECTED_APPS.getLabelId()), - false - ) + val unselected = + makeFirewallChip( + TopLevelFilter.UNSELECTED_APPS.id, + activity.getString(TopLevelFilter.UNSELECTED_APPS.getLabelId()), + false + ) b.wgIncludeAppDialogChipGroup.addView(all) b.wgIncludeAppDialogChipGroup.addView(selected) From 150916e14e0746db6ab9e525c4002e330dd3e053 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Tue, 23 Apr 2024 19:13:23 +0530 Subject: [PATCH 33/48] bump firestack version --- app/build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index edb981e6e..1335973d8 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -247,8 +247,8 @@ dependencies { fullImplementation 'com.github.kirich1409:viewbindingpropertydelegate-noreflection:1.5.9' // from: https://jitpack.io/#celzero/firestack - download 'com.github.celzero:firestack:750d62fc48@aar' - implementation 'com.github.celzero:firestack:750d62fc48@aar' + download 'com.github.celzero:firestack:2787c84e53@aar' + implementation 'com.github.celzero:firestack:2787c84e53@aar' // Work manager implementation('androidx.work:work-runtime-ktx:2.9.0') { From 347dd5126b7d4f0375fb59169235c04398b0bfa8 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Tue, 23 Apr 2024 19:13:43 +0530 Subject: [PATCH 34/48] set log level changes in tunnel --- .../java/com/celzero/bravedns/net/go/GoVpnAdapter.kt | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt b/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt index aeeb031ac..686b8027f 100644 --- a/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt +++ b/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt @@ -496,8 +496,8 @@ class GoVpnAdapter : KoinComponent { } try { // no need to remove from appConfig, as it is already removed - getResolver()?.remove(relay.dnsCryptRelayURL) - Logger.i(LOG_TAG_VPN, "remove dnscrypt relay: ${relay.dnsCryptRelayURL}") + val rmv = getResolver()?.remove(relay.dnsCryptRelayURL) + Logger.i(LOG_TAG_VPN, "rmv dnscrypt relay: ${relay.dnsCryptRelayURL}, success? $rmv") } catch (e: Exception) { Logger.e(LOG_TAG_VPN, "connect-tunnel: dnscrypt rmv failure", e) } @@ -1079,8 +1079,11 @@ class GoVpnAdapter : KoinComponent { } fun setLogLevel(level: Long) { - // 0 - verbose, 1 - debug, 2 - info, 3 - warn, 4 - error, 5 - fatal - Intra.logLevel(level) + // increment the level by 1, as the levels start from 1, but the log levels start from 0 + val l = level.inc() + // 0 - very verbose (unimplemented) + // 1 - verbose, 2 - debug, 3 - info, 4 - warn, 5 - error, 6 - fatal + Intra.logLevel(l) } } From 579e54cb40cc398e07488b91798a4b11231267a0 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Tue, 23 Apr 2024 19:14:37 +0530 Subject: [PATCH 35/48] bg optimization: dialog string literal changes --- .../ui/fragment/HomeScreenFragment.kt | 20 ++++++++++++---- app/src/main/res/values/strings.xml | 23 ++++++++++--------- 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt index 99c612b36..8c1610fbd 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt @@ -756,8 +756,18 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { if (!isAtleastN()) return val builder = MaterialAlertDialogBuilder(requireContext()) - builder.setTitle(R.string.battery_optimization_dialog_heading) - builder.setMessage(R.string.battery_optimization_dialog_message) + val title = + getString( + R.string.battery_optimization_dialog_heading, + getString(R.string.lbl_battery_optimization) + ) + val msg = + getString( + R.string.restrict_dialog_message, + getString(R.string.lbl_battery_optimization) + ) + builder.setTitle(title) + builder.setMessage(msg) builder.setCancelable(false) builder.setPositiveButton(R.string.lbl_proceed) { _, _ -> openNetworkSettings( @@ -789,8 +799,10 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { if (!isAtleastN()) return val builder = MaterialAlertDialogBuilder(requireContext()) - builder.setTitle(R.string.restrict_bg_dialog_heading) - builder.setMessage(R.string.restrict_bg_dialog_message) + builder.setTitle(R.string.lbl_background_data) + val msg = + getString(R.string.restrict_dialog_message, getString(R.string.lbl_background_data)) + builder.setMessage(msg) builder.setCancelable(false) builder.setPositiveButton(R.string.lbl_proceed) { _, _ -> openNetworkSettings( diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 1957c3c0f..ba321892a 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -98,6 +98,7 @@ Split on-device IP + Unselected %1$s 🔺 %1$s 🔻 @@ -398,17 +399,12 @@ Choose mode Chirayu Desai 3.0

- 1. New feature: Optionally proxy DNS over WireGuard and SOCKS5 proxies.
- 2. New feature: Optionally enable built-in Android connectivity checks.
- 3. New feature: List domains and websites an app has connected to.
- 4. Improved support for editing IP-based firewall rules.
- 5. Improved WireGuard bandwidth.
- 6. Overhauled WireGuard UX.
- 7. Avoid connection leaks for Simple and Always-on WireGuard modes.
- 8. Fix crash when editing WireGuard configurations.
- 9. Fix minor bugs with RDNS+ and other domain-based firewall rules.
- 10. Bug fix: Support multiple rules for a single Trusted IP.
- 11. Bug fix: Android 14 specific crash.

+ 1. Show upload, download stats for WireGuard.
+ 2. Auto recover dropped WireGuard connections.
+ 3. Implement Android\'s seamless handover on network changes.
+ 4. Support for multiple DNSCrypt relays.
+ 5. Bug fix: Close packet capture file when appropriate.
+ 6. Other bug fixed and improvements.

Help translate this app]]>
@@ -699,6 +695,11 @@ Theme: %1$s Cannot pause: Rethink not active + Restricting Background data + Battery optimization + Disable %1$s + %1$s may result in connectivity loss. Change setting to let Rethink use data and other resources when in background. + rules From 57476a649e68a73d294c0447cd8c347d81f513e1 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Wed, 24 Apr 2024 21:42:56 +0530 Subject: [PATCH 36/48] new log level in go (very verbose) --- .../ui/activity/MiscSettingsActivity.kt | 1 + .../celzero/bravedns/net/go/GoVpnAdapter.kt | 28 +++++++++++++++---- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/ui/activity/MiscSettingsActivity.kt b/app/src/full/java/com/celzero/bravedns/ui/activity/MiscSettingsActivity.kt index 9c97a7fee..76ac4e166 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/activity/MiscSettingsActivity.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/activity/MiscSettingsActivity.kt @@ -435,6 +435,7 @@ class MiscSettingsActivity : AppCompatActivity(R.layout.activity_misc_settings) alertBuilder.setTitle(getString(R.string.settings_go_log_heading)) val items = arrayOf( + getString(R.string.settings_gologger_dialog_option_0), getString(R.string.settings_gologger_dialog_option_1), getString(R.string.settings_gologger_dialog_option_2), getString(R.string.settings_gologger_dialog_option_3), diff --git a/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt b/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt index 686b8027f..719b23944 100644 --- a/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt +++ b/app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt @@ -99,6 +99,7 @@ class GoVpnAdapter : KoinComponent { } suspend fun initResolverProxiesPcap(opts: TunnelOptions) { + Logger.v(LOG_TAG_VPN, "GoVpnAdapter initResolverProxiesPcap") if (!tunnel.isConnected) { Logger.i(LOG_TAG_VPN, "Tunnel NOT connected, skip init resolver proxies") return @@ -117,18 +118,22 @@ class GoVpnAdapter : KoinComponent { setRDNS() addTransport() setDnsAlg() + Logger.v(LOG_TAG_VPN, "GoVpnAdapter initResolverProxiesPcap done") } suspend fun setPcapMode(pcapFilePath: String) { + Logger.v(LOG_TAG_VPN, "GoVpnAdapter setPcapMode") try { Logger.i(LOG_TAG_VPN, "set pcap mode: $pcapFilePath") tunnel.setPcap(pcapFilePath) } catch (e: Exception) { Logger.e(LOG_TAG_VPN, "err setting pcap: ${e.message}", e) } + Logger.v(LOG_TAG_VPN, "GoVpnAdapter setPcapMode done") } private fun setRoute(tunnelOptions: TunnelOptions) { + Logger.v(LOG_TAG_VPN, "GoVpnAdapter setRoute") try { // setRoute can throw exception iff preferredEngine is invalid, which is not possible // Log.d(LOG_TAG_VPN, "set route: ${tunnelOptions.preferredEngine.value()}") @@ -146,9 +151,11 @@ class GoVpnAdapter : KoinComponent { } catch (e: Exception) { Logger.e(LOG_TAG_VPN, "err setting route: ${e.message}", e) } + Logger.v(LOG_TAG_VPN, "GoVpnAdapter setRoute done") } suspend fun addTransport() { + Logger.v(LOG_TAG_VPN, "GoVpnAdapter addTransport") if (!tunnel.isConnected) { Logger.i(LOG_TAG_VPN, "Tunnel NOT connected, skip add transport") return @@ -200,9 +207,11 @@ class GoVpnAdapter : KoinComponent { } } } + Logger.v(LOG_TAG_VPN, "GoVpnAdapter addTransport done") } private suspend fun addDohTransport(id: String) { + Logger.v(LOG_TAG_VPN, "GoVpnAdapter addDohTransport") var url: String? = null try { val doh = appConfig.getDOHDetails() @@ -222,9 +231,11 @@ class GoVpnAdapter : KoinComponent { getResolver()?.remove(id) showDnsFailureToast(url ?: "") } + Logger.v(LOG_TAG_VPN, "GoVpnAdapter addDohTransport done") } private suspend fun addDotTransport(id: String) { + Logger.v(LOG_TAG_VPN, "GoVpnAdapter addDotTransport, id: $id") var url: String? = null try { val dot = appConfig.getDOTDetails() @@ -244,9 +255,11 @@ class GoVpnAdapter : KoinComponent { getResolver()?.remove(id) showDnsFailureToast(url ?: "") } + Logger.v(LOG_TAG_VPN, "GoVpnAdapter addDotTransport done") } private suspend fun addOdohTransport(id: String) { + Logger.v(LOG_TAG_VPN, "GoVpnAdapter addOdohTransport, id: $id") var resolver: String? = null try { val odoh = appConfig.getODoHDetails() @@ -262,9 +275,11 @@ class GoVpnAdapter : KoinComponent { getResolver()?.remove(id) showDnsFailureToast(resolver ?: "") } + Logger.v(LOG_TAG_VPN, "GoVpnAdapter addOdohTransport done") } private suspend fun addDnscryptTransport(id: String) { + Logger.v(LOG_TAG_VPN, "GoVpnAdapter addDnscryptTransport, id: $id") try { val dc = appConfig.getConnectedDnscryptServer() val url = dc.dnsCryptURL @@ -279,9 +294,11 @@ class GoVpnAdapter : KoinComponent { removeDnscryptRelaysIfAny() showDnscryptConnectionFailureToast() } + Logger.v(LOG_TAG_VPN, "GoVpnAdapter addDnscryptTransport done") } private suspend fun addDnsProxyTransport(id: String) { + Logger.v(LOG_TAG_VPN, "GoVpnAdapter addDnsProxyTransport, id: $id") try { val dnsProxy = appConfig.getSelectedDnsProxyDetails() ?: return // add replaces the existing transport with the same id if successful @@ -296,9 +313,11 @@ class GoVpnAdapter : KoinComponent { getResolver()?.remove(id) showDnsProxyConnectionFailureToast() } + Logger.v(LOG_TAG_VPN, "GoVpnAdapter addDnsProxyTransport done") } private suspend fun addRdnsTransport(id: String, url: String) { + Logger.v(LOG_TAG_VPN, "GoVpnAdapter addRdnsTransport, id: $id, url: $url") try { val useDot = false val ips: String = getIpString(context, url) @@ -315,9 +334,11 @@ class GoVpnAdapter : KoinComponent { getResolver()?.remove(id) showDnsFailureToast(url) } + Logger.v(LOG_TAG_VPN, "GoVpnAdapter addRdnsTransport done") } private fun getRdnsUrl(url: String, useDot: Boolean = false): String? { + val tls = "tls://" val default = "dns-query" // do not proceed if rethinkdns.com is not available @@ -1079,11 +1100,8 @@ class GoVpnAdapter : KoinComponent { } fun setLogLevel(level: Long) { - // increment the level by 1, as the levels start from 1, but the log levels start from 0 - val l = level.inc() - // 0 - very verbose (unimplemented) - // 1 - verbose, 2 - debug, 3 - info, 4 - warn, 5 - error, 6 - fatal - Intra.logLevel(l) + // 0 - very verbose, 1 - verbose, 2 - debug, 3 - info, 4 - warn, 5 - error, 6 - fatal + Intra.logLevel(level) } } From 70d9baae2ae108349d6b603380989e97106cff9d Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Wed, 24 Apr 2024 21:44:52 +0530 Subject: [PATCH 37/48] launch other settings page on launch failure --- .../bravedns/ui/fragment/AboutFragment.kt | 20 +------ .../ui/fragment/HomeScreenFragment.kt | 52 ++++++++++++++----- .../java/com/celzero/bravedns/util/UIUtils.kt | 28 ++++++++-- .../com/celzero/bravedns/util/Utilities.kt | 4 ++ 4 files changed, 69 insertions(+), 35 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/AboutFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/AboutFragment.kt index 8fa9df176..9dfa5dc22 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/AboutFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/AboutFragment.kt @@ -53,6 +53,7 @@ import com.celzero.bravedns.service.AppUpdater import com.celzero.bravedns.ui.HomeScreenActivity import com.celzero.bravedns.util.Constants.Companion.INIT_TIME_MS import com.celzero.bravedns.util.Constants.Companion.RETHINKDNS_SPONSOR_LINK +import com.celzero.bravedns.util.UIUtils.openAppInfo import com.celzero.bravedns.util.UIUtils.openVpnProfile import com.celzero.bravedns.util.UIUtils.sendEmailIntent import com.celzero.bravedns.util.UIUtils.updateHtmlEncodedText @@ -195,7 +196,7 @@ class AboutFragment : Fragment(R.layout.fragment_about), View.OnClickListener, K showNewFeaturesDialog() } b.aboutAppInfo -> { - openAppInfo() + openAppInfo(requireContext()) } b.aboutVpnProfile -> { openVpnProfile(requireContext()) @@ -241,23 +242,6 @@ class AboutFragment : Fragment(R.layout.fragment_about), View.OnClickListener, K } } - private fun openAppInfo() { - val packageName = requireContext().packageName - try { - val intent = Intent(ACTION_APPLICATION_DETAILS_SETTINGS) - intent.data = Uri.fromParts("package", packageName, null) - intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK - startActivity(intent) - } catch (e: ActivityNotFoundException) { - showToastUiCentered( - requireContext(), - getString(R.string.app_info_error), - Toast.LENGTH_SHORT - ) - Logger.w(LOG_TAG_UI, "activity not found ${e.message}", e) - } - } - private fun openNotificationSettings() { val packageName = requireContext().packageName try { diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt index 8c1610fbd..e2a9d0b4f 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt @@ -68,26 +68,28 @@ import com.celzero.bravedns.ui.activity.WgMainActivity import com.celzero.bravedns.ui.bottomsheet.HomeScreenSettingBottomSheet import com.celzero.bravedns.util.* import com.celzero.bravedns.util.Constants.Companion.RETHINKDNS_SPONSOR_LINK +import com.celzero.bravedns.util.UIUtils.openAppInfo import com.celzero.bravedns.util.UIUtils.openNetworkSettings import com.celzero.bravedns.util.UIUtils.openVpnProfile import com.celzero.bravedns.util.UIUtils.updateHtmlEncodedText import com.celzero.bravedns.util.Utilities.delay import com.celzero.bravedns.util.Utilities.getPrivateDnsMode import com.celzero.bravedns.util.Utilities.isAtleastN +import com.celzero.bravedns.util.Utilities.isAtleastP import com.celzero.bravedns.util.Utilities.isOtherVpnHasAlwaysOn import com.celzero.bravedns.util.Utilities.isPrivateDnsActive import com.celzero.bravedns.util.Utilities.showToastUiCentered import com.facebook.shimmer.Shimmer import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar +import java.util.* +import java.util.concurrent.TimeUnit import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.koin.android.ext.android.inject -import java.util.* -import java.util.concurrent.TimeUnit class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { private val b by viewBinding(FragmentHomeScreenBinding::bind) @@ -316,7 +318,7 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { private fun enableProxyCardIfNeeded() { if (isVpnActivated && !appConfig.getBraveMode().isDnsMode()) { - if (persistentState.getProxyStatus() != -1) { + if (persistentState.getProxyStatus().value != -1) { observeProxyStates() } else { disableProxyCard() @@ -375,7 +377,7 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { } */ private fun observeProxyStates() { - persistentState.proxyStatus.observe(viewLifecycleOwner) { + persistentState.getProxyStatus().observe(viewLifecycleOwner) { if (it != -1) { updateUiWithProxyStates(it) } else { @@ -441,7 +443,7 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { } private fun unobserveProxyStates() { - persistentState.proxyStatus.removeObservers(viewLifecycleOwner) + persistentState.getProxyStatus().removeObservers(viewLifecycleOwner) } private fun disableLogsCard() { @@ -770,10 +772,18 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { builder.setMessage(msg) builder.setCancelable(false) builder.setPositiveButton(R.string.lbl_proceed) { _, _ -> - openNetworkSettings( - requireContext(), - Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS - ) + Logger.v(LOG_TAG_UI, "launch battery optimization settings") + val ok = + openNetworkSettings( + requireContext(), + Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS + ) + Logger.v(LOG_TAG_UI, "battery optimization settings launched: $ok") + if (!ok) { + // launch app settings if the above settings is not available + Logger.v(LOG_TAG_UI, "launch app info, battery optimization settings not available") + openAppInfo(requireContext()) + } } builder.setNegativeButton(R.string.lbl_dismiss) { _, _ -> @@ -805,10 +815,26 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { builder.setMessage(msg) builder.setCancelable(false) builder.setPositiveButton(R.string.lbl_proceed) { _, _ -> - openNetworkSettings( - requireContext(), - Settings.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS - ) + Logger.v(LOG_TAG_UI, "launch restrict background data settings") + var ok = + openNetworkSettings( + requireContext(), + Settings.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS + ) + Logger.v(LOG_TAG_UI, "restrict background data settings launched: $ok") + if (!ok && isAtleastP()) { + // launch data usage settings if the above settings is not available + Logger.v( + LOG_TAG_UI, + "launch data usage settings, restrict bg data settings not available" + ) + ok = openNetworkSettings(requireContext(), Settings.ACTION_DATA_USAGE_SETTINGS) + } + if (!ok) { + // launch app settings if the above settings is not available + Logger.v(LOG_TAG_UI, "launch app info, restrict bg data settings not available") + openAppInfo(requireContext()) + } } builder.setNegativeButton(R.string.lbl_dismiss) { _, _ -> diff --git a/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt b/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt index 80691a8d7..7d8d5ef44 100644 --- a/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt +++ b/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt @@ -16,6 +16,7 @@ package com.celzero.bravedns.util import Logger +import Logger.LOG_TAG_UI import android.content.ActivityNotFoundException import android.content.ClipData import android.content.ClipboardManager @@ -161,19 +162,38 @@ object UIUtils { context.getString(R.string.intent_launch_error, url), Toast.LENGTH_SHORT ) - Logger.w(Logger.LOG_TAG_UI, "activity not found ${e.message}", e) + Logger.w(LOG_TAG_UI, "activity not found ${e.message}", e) } } - fun openNetworkSettings(context: Context, settings: String) { - try { + fun openNetworkSettings(context: Context, settings: String): Boolean { + return try { val intent = Intent(settings) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK context.startActivity(intent) + true } catch (e: ActivityNotFoundException) { val msg = context.getString(R.string.intent_launch_error, settings) Utilities.showToastUiCentered(context, msg, Toast.LENGTH_SHORT) - Logger.w(Logger.LOG_TAG_VPN, "Failure opening network setting screen: ${e.message}", e) + Logger.w(Logger.LOG_TAG_VPN, "err opening android setting: ${e.message}", e) + false + } + } + + fun openAppInfo(context: Context) { + val packageName =context.packageName + try { + val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) + intent.data = Uri.fromParts("package", packageName, null) + intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK + context.startActivity(intent) + } catch (e: ActivityNotFoundException) { + Utilities.showToastUiCentered( + context, + context.getString(R.string.app_info_error), + Toast.LENGTH_SHORT + ) + Logger.w(LOG_TAG_UI, "activity not found ${e.message}", e) } } diff --git a/app/src/main/java/com/celzero/bravedns/util/Utilities.kt b/app/src/main/java/com/celzero/bravedns/util/Utilities.kt index 98dd85dd4..32d104471 100644 --- a/app/src/main/java/com/celzero/bravedns/util/Utilities.kt +++ b/app/src/main/java/com/celzero/bravedns/util/Utilities.kt @@ -465,6 +465,10 @@ object Utilities { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.R } + fun isAtleastP(): Boolean { + return Build.VERSION.SDK_INT >= Build.VERSION_CODES.P + } + fun isAtleastQ(): Boolean { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q } From 83ca2da15bd9f77aa64728f1f6eef8fd184179fb Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Wed, 24 Apr 2024 21:45:11 +0530 Subject: [PATCH 38/48] new log level in go (very verbose) --- .../java/com/celzero/bravedns/util/Logger.kt | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/com/celzero/bravedns/util/Logger.kt b/app/src/main/java/com/celzero/bravedns/util/Logger.kt index d53a2870f..3fc82aca5 100644 --- a/app/src/main/java/com/celzero/bravedns/util/Logger.kt +++ b/app/src/main/java/com/celzero/bravedns/util/Logger.kt @@ -38,11 +38,16 @@ object Logger : KoinComponent { const val LOG_QR_CODE = "QrCodeFromFileScanner" enum class LoggerType(val id: Int) { - VERBOSE(0), - DEBUG(1), - INFO(2), - WARN(3), - ERROR(4) + VERY_VERBOSE(0), + VERBOSE(1), + DEBUG(2), + INFO(3), + WARN(4), + ERROR(5) + } + + fun vv(tag: String, message: String) { + log(tag, message, LoggerType.VERY_VERBOSE) } fun v(tag: String, message: String) { @@ -77,13 +82,14 @@ object Logger : KoinComponent { } } - private fun log(tag: String, message: String, type: LoggerType, e: Exception? = null) { + private fun log(tag: String, msg: String, type: LoggerType, e: Exception? = null) { when (type) { - LoggerType.VERBOSE -> if (logLevel <= LoggerType.VERBOSE.id) Log.v(tag, message) - LoggerType.DEBUG -> if (logLevel <= LoggerType.DEBUG.id) Log.d(tag, message) - LoggerType.INFO -> if (logLevel <= LoggerType.INFO.id) Log.i(tag, message) - LoggerType.WARN -> if (logLevel <= LoggerType.WARN.id) Log.w(tag, message, e) - LoggerType.ERROR -> if (logLevel <= LoggerType.ERROR.id) Log.e(tag, message, e) + LoggerType.VERY_VERBOSE -> if (logLevel <= LoggerType.VERY_VERBOSE.id) Log.v(tag, msg) + LoggerType.VERBOSE -> if (logLevel <= LoggerType.VERBOSE.id) Log.v(tag, msg) + LoggerType.DEBUG -> if (logLevel <= LoggerType.DEBUG.id) Log.d(tag, msg) + LoggerType.INFO -> if (logLevel <= LoggerType.INFO.id) Log.i(tag, msg) + LoggerType.WARN -> if (logLevel <= LoggerType.WARN.id) Log.w(tag, msg, e) + LoggerType.ERROR -> if (logLevel <= LoggerType.ERROR.id) Log.e(tag, msg, e) } } } From 1cbc2980c3d3c1fe800539fbbdcc4901cc8bc8c1 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Wed, 24 Apr 2024 21:45:46 +0530 Subject: [PATCH 39/48] minor improvement while handling failopen in connection monitor --- .../java/com/celzero/bravedns/service/ConnectionMonitor.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt b/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt index ead935df4..95a9f8117 100644 --- a/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt +++ b/app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt @@ -508,7 +508,8 @@ class ConnectionMonitor(private val networkListener: NetworkListener) : // see #createNetworksSet for why we are using hasInternet // if no network has been validated, then fail open - if (hasInternet(network) == true && (!isAnyNwValidated || isNwValidated(network))) { + val failOpen = !isAnyNwValidated && BraveVPNService.FAIL_OPEN_ON_NO_NETWORK + if (hasInternet(network) == true && (failOpen || isNwValidated(network))) { var hasDefaultRoute4 = false var hasDefaultRoute6 = false lp.routes.forEach rloop@{ From 6e06ce3228275d18e7026c96c79a12c5c5279bba Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Wed, 24 Apr 2024 21:46:22 +0530 Subject: [PATCH 40/48] ui: update toggle btn text on toggle switch --- .../ui/fragment/RethinkBlocklistFragment.kt | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkBlocklistFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkBlocklistFragment.kt index a10e18253..21c5d8bdf 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkBlocklistFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkBlocklistFragment.kt @@ -59,6 +59,7 @@ import com.celzero.bravedns.util.Constants.Companion.DEFAULT_RDNS_REMOTE_DNS_NAM import com.celzero.bravedns.util.Constants.Companion.MAX_ENDPOINT import com.celzero.bravedns.util.Constants.Companion.RETHINK_STAMP_VERSION import com.celzero.bravedns.util.CustomLinearLayoutManager +import com.celzero.bravedns.util.UIUtils import com.celzero.bravedns.util.UIUtils.fetchToggleBtnColors import com.celzero.bravedns.util.UIUtils.updateHtmlEncodedText import com.celzero.bravedns.util.Utilities.getRemoteBlocklistStamp @@ -73,12 +74,12 @@ import com.google.android.material.button.MaterialButton import com.google.android.material.button.MaterialButtonToggleGroup import com.google.android.material.chip.Chip import com.google.android.material.dialog.MaterialAlertDialogBuilder +import java.util.regex.Pattern import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.koin.android.ext.android.inject import org.koin.androidx.viewmodel.ext.android.viewModel -import java.util.regex.Pattern class RethinkBlocklistFragment : Fragment(R.layout.fragment_rethink_blocklist), SearchView.OnQueryTextListener { @@ -495,13 +496,17 @@ class RethinkBlocklistFragment : } } - private fun selectToggleBtnUi(b: MaterialButton) { - b.backgroundTintList = - ColorStateList.valueOf(fetchToggleBtnColors(requireContext(), R.color.accentGood)) + private fun selectToggleBtnUi(mb: MaterialButton) { + mb.backgroundTintList = + ColorStateList.valueOf( + fetchToggleBtnColors(requireContext(), R.color.accentGood) + ) + mb.setTextColor(UIUtils.fetchColor(requireContext(), R.attr.homeScreenHeaderTextColor)) } - private fun unselectToggleBtnUi(b: MaterialButton) { - b.backgroundTintList = + private fun unselectToggleBtnUi(mb: MaterialButton) { + mb.setTextColor(UIUtils.fetchColor(requireContext(), R.attr.primaryTextColor)) + mb.backgroundTintList = ColorStateList.valueOf( fetchToggleBtnColors(requireContext(), R.color.defaultToggleBtnBg) ) From 018d099e1db80fcf54c886c6ccf0e053fcfa4ae6 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Wed, 24 Apr 2024 21:47:16 +0530 Subject: [PATCH 41/48] ui: check if activity is present before launching relays dialog --- .../celzero/bravedns/ui/fragment/DnsCryptListFragment.kt | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsCryptListFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsCryptListFragment.kt index 05f4c1982..8f817d43d 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsCryptListFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/DnsCryptListFragment.kt @@ -15,6 +15,7 @@ */ package com.celzero.bravedns.ui.fragment +import Logger import android.content.res.Configuration import android.os.Bundle import android.view.View @@ -105,6 +106,12 @@ class DnsCryptListFragment : Fragment(R.layout.fragment_dns_crypt_list) { val themeId = Themes.getCurrentTheme(isDarkThemeOn(), persistentState.theme) val customDialog = DnsCryptRelaysDialog(requireActivity(), dnsCryptRelayRecyclerAdapter, themeId) + + if (!isAdded && requireActivity().isFinishing) { + Logger.w(Logger.LOG_TAG_UI, "DnsCrypt relay, Fragment not added to activity") + return + } + customDialog.show() } From 2ec769bec781fe6d3f17ab8cb18c6dcbe0063732 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Wed, 24 Apr 2024 21:47:48 +0530 Subject: [PATCH 42/48] fix: wrong stats for blocked and allowed domains --- .../main/java/com/celzero/bravedns/database/DnsLogDAO.kt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/celzero/bravedns/database/DnsLogDAO.kt b/app/src/main/java/com/celzero/bravedns/database/DnsLogDAO.kt index 9c64f1e15..9eaf001ee 100644 --- a/app/src/main/java/com/celzero/bravedns/database/DnsLogDAO.kt +++ b/app/src/main/java/com/celzero/bravedns/database/DnsLogDAO.kt @@ -88,22 +88,22 @@ interface DnsLogDAO { @Query("delete from DNSLogs where time < :date") fun purgeDnsLogsByDate(date: Long) @Query( - "select 0 as uid, '' as ipAddress, 0 as port, count(id) as count, flag, 0 as blocked, queryStr as appOrDnsName from DNSLogs where isBlocked = 0 and status = 'COMPLETE' and response != 'NXDOMAIN' and queryStr != '' and time < :to group by queryStr order by count desc LIMIT 7" + "select 0 as uid, '' as ipAddress, 0 as port, count(id) as count, flag, 0 as blocked, queryStr as appOrDnsName from DNSLogs where isBlocked = 0 and status = 'COMPLETE' and response != 'NXDOMAIN' and queryStr != '' and time > :to group by queryStr order by count desc LIMIT 7" ) fun getMostContactedDomains(to: Long): PagingSource @Query( - "select 0 as uid, '' as ipAddress, 0 as port, count(id) as count, flag, 0 as blocked, queryStr as appOrDnsName from DNSLogs where isBlocked = 0 and status = 'COMPLETE' and response != 'NXDOMAIN' and queryStr != '' and time < :to group by queryStr order by count desc" + "select 0 as uid, '' as ipAddress, 0 as port, count(id) as count, flag, 0 as blocked, queryStr as appOrDnsName from DNSLogs where isBlocked = 0 and status = 'COMPLETE' and response != 'NXDOMAIN' and queryStr != '' and time > :to group by queryStr order by count desc" ) fun getAllContactedDomains(to: Long): PagingSource @Query( - "select 0 as uid, '' as ipAddress, 0 as port, count(id) as count, flag, 1 as blocked, queryStr as appOrDnsName from DNSLogs where isBlocked = 1 and time < :to and queryStr != '' group by queryStr order by count desc LIMIT 7" + "select 0 as uid, '' as ipAddress, 0 as port, count(id) as count, flag, 1 as blocked, queryStr as appOrDnsName from DNSLogs where isBlocked = 1 and time > :to and queryStr != '' group by queryStr order by count desc LIMIT 7" ) fun getMostBlockedDomains(to: Long): PagingSource @Query( - "select 0 as uid, '' as ipAddress, 0 as port, count(id) as count, flag, 1 as blocked, queryStr as appOrDnsName from DNSLogs where isBlocked = 1 and time < :to and queryStr != '' group by queryStr order by count desc" + "select 0 as uid, '' as ipAddress, 0 as port, count(id) as count, flag, 1 as blocked, queryStr as appOrDnsName from DNSLogs where isBlocked = 1 and time > :to and queryStr != '' group by queryStr order by count desc" ) fun getAllBlockedDomains(to: Long): PagingSource From 7f13f6d26def9a9f83e0684ad2fc35dd88ecfbde Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Wed, 24 Apr 2024 21:48:29 +0530 Subject: [PATCH 43/48] logs on dns added, removed and stopped listener --- .../java/com/celzero/bravedns/service/BraveVPNService.kt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt b/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt index 532a2efd5..7390cf499 100644 --- a/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt +++ b/app/src/main/java/com/celzero/bravedns/service/BraveVPNService.kt @@ -1928,7 +1928,7 @@ class BraveVPNService : networks.ipv4Net.map { it.network } + networks.ipv6Net.map { it.network } setUnderlyingNetworks(allNetworks.toTypedArray()) } - // restart vpn if the routes (+ auto mode) or when mtu changes + // restart vpn if the routes or when mtu changes if (isMtuChanged || isRoutesChanged) { logd( "mtu? $isMtuChanged(o:${curnet?.minMtu}, n:${networks.minMtu}); routes? $isRoutesChanged, restart vpn" @@ -2854,14 +2854,17 @@ class BraveVPNService : override fun onDNSAdded(id: String) { // no-op + Logger.v(LOG_TAG_VPN, "onDNSAdded: $id") } override fun onDNSRemoved(id: String) { // no-op + Logger.v(LOG_TAG_VPN, "onDNSRemoved: $id") } override fun onDNSStopped() { // no-op + Logger.v(LOG_TAG_VPN, "onDNSStopped") } override fun onComplete(p0: ServerSummary) { From 20a08414c3b76342de96d4551d23ee64593e9cce Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Wed, 24 Apr 2024 21:49:56 +0530 Subject: [PATCH 44/48] Fix: #1371, minor improvement while fetching proxy status --- .../java/com/celzero/bravedns/service/PersistentState.kt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/celzero/bravedns/service/PersistentState.kt b/app/src/main/java/com/celzero/bravedns/service/PersistentState.kt index eba1c2341..69cd62b42 100644 --- a/app/src/main/java/com/celzero/bravedns/service/PersistentState.kt +++ b/app/src/main/java/com/celzero/bravedns/service/PersistentState.kt @@ -281,7 +281,7 @@ class PersistentState(context: Context) : SimpleKrate(context), KoinComponent { var median: MutableLiveData = MutableLiveData() var vpnEnabledLiveData: MutableLiveData = MutableLiveData() var universalRulesCount: MutableLiveData = MutableLiveData() - var proxyStatus: MutableLiveData = MutableLiveData() + private var proxyStatus: MutableLiveData = MutableLiveData() // data class to store dnscrypt relay details data class DnsCryptRelayDetails(val relay: DnsCryptRelayEndpoint, val added: Boolean) @@ -414,9 +414,9 @@ class PersistentState(context: Context) : SimpleKrate(context), KoinComponent { return _blockWhenDeviceLocked } - fun getProxyStatus(): Int { + fun getProxyStatus(): MutableLiveData { if (proxyStatus.value == null) updateProxyStatus() - return proxyStatus.value ?: -1 + return proxyStatus } fun updateProxyStatus() { From 4cdf0bdbf01f9c860cf4475e32cea20834a35b1a Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Wed, 24 Apr 2024 22:58:10 +0530 Subject: [PATCH 45/48] ktfmt code, rmv unnecessary settings invoke from home screen --- .../bravedns/ui/fragment/HomeScreenFragment.kt | 16 +++------------- .../ui/fragment/RethinkBlocklistFragment.kt | 6 ++---- .../java/com/celzero/bravedns/util/UIUtils.kt | 2 +- 3 files changed, 6 insertions(+), 18 deletions(-) diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt index e2a9d0b4f..9b468135d 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/HomeScreenFragment.kt @@ -75,21 +75,20 @@ import com.celzero.bravedns.util.UIUtils.updateHtmlEncodedText import com.celzero.bravedns.util.Utilities.delay import com.celzero.bravedns.util.Utilities.getPrivateDnsMode import com.celzero.bravedns.util.Utilities.isAtleastN -import com.celzero.bravedns.util.Utilities.isAtleastP import com.celzero.bravedns.util.Utilities.isOtherVpnHasAlwaysOn import com.celzero.bravedns.util.Utilities.isPrivateDnsActive import com.celzero.bravedns.util.Utilities.showToastUiCentered import com.facebook.shimmer.Shimmer import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar -import java.util.* -import java.util.concurrent.TimeUnit import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.koin.android.ext.android.inject +import java.util.* +import java.util.concurrent.TimeUnit class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { private val b by viewBinding(FragmentHomeScreenBinding::bind) @@ -816,20 +815,11 @@ class HomeScreenFragment : Fragment(R.layout.fragment_home_screen) { builder.setCancelable(false) builder.setPositiveButton(R.string.lbl_proceed) { _, _ -> Logger.v(LOG_TAG_UI, "launch restrict background data settings") - var ok = + val ok = openNetworkSettings( requireContext(), Settings.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS ) - Logger.v(LOG_TAG_UI, "restrict background data settings launched: $ok") - if (!ok && isAtleastP()) { - // launch data usage settings if the above settings is not available - Logger.v( - LOG_TAG_UI, - "launch data usage settings, restrict bg data settings not available" - ) - ok = openNetworkSettings(requireContext(), Settings.ACTION_DATA_USAGE_SETTINGS) - } if (!ok) { // launch app settings if the above settings is not available Logger.v(LOG_TAG_UI, "launch app info, restrict bg data settings not available") diff --git a/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkBlocklistFragment.kt b/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkBlocklistFragment.kt index 21c5d8bdf..ba19e6de9 100644 --- a/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkBlocklistFragment.kt +++ b/app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkBlocklistFragment.kt @@ -74,12 +74,12 @@ import com.google.android.material.button.MaterialButton import com.google.android.material.button.MaterialButtonToggleGroup import com.google.android.material.chip.Chip import com.google.android.material.dialog.MaterialAlertDialogBuilder -import java.util.regex.Pattern import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.koin.android.ext.android.inject import org.koin.androidx.viewmodel.ext.android.viewModel +import java.util.regex.Pattern class RethinkBlocklistFragment : Fragment(R.layout.fragment_rethink_blocklist), SearchView.OnQueryTextListener { @@ -498,9 +498,7 @@ class RethinkBlocklistFragment : private fun selectToggleBtnUi(mb: MaterialButton) { mb.backgroundTintList = - ColorStateList.valueOf( - fetchToggleBtnColors(requireContext(), R.color.accentGood) - ) + ColorStateList.valueOf(fetchToggleBtnColors(requireContext(), R.color.accentGood)) mb.setTextColor(UIUtils.fetchColor(requireContext(), R.attr.homeScreenHeaderTextColor)) } diff --git a/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt b/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt index 7d8d5ef44..8b056b8df 100644 --- a/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt +++ b/app/src/full/java/com/celzero/bravedns/util/UIUtils.kt @@ -181,7 +181,7 @@ object UIUtils { } fun openAppInfo(context: Context) { - val packageName =context.packageName + val packageName = context.packageName try { val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) intent.data = Uri.fromParts("package", packageName, null) From 8d20ccb9fd9c59d471aaca671ccc3c376e64302f Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Wed, 24 Apr 2024 22:58:53 +0530 Subject: [PATCH 46/48] update code and name for version 055f (37) --- app/src/main/AndroidManifest.xml | 4 ++-- app/src/main/res/values/strings.xml | 3 ++- gradle.properties | 4 ++-- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 3e1dc22e5..c2cb846c1 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,8 +2,8 @@ + android:versionCode="37" + android:versionName="v055f"> diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ba321892a..a8d5cc31b 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -398,7 +398,7 @@ Choose mode - Chirayu Desai 3.0

+ JA Donenfeld 2.0

1. Show upload, download stats for WireGuard.
2. Auto recover dropped WireGuard connections.
3. Implement Android\'s seamless handover on network changes.
@@ -534,6 +534,7 @@ Loopback (experimental) Also enables %1$s setting. Do you want to proceed? + Very verbose Verbose Debug Info (default) diff --git a/gradle.properties b/gradle.properties index 0d6fc9c4a..e757654a4 100644 --- a/gradle.properties +++ b/gradle.properties @@ -24,5 +24,5 @@ android.nonTransitiveRClass=true # Enable configuration cache org.gradle.unsafe.configuration-cache=true android.nonFinalResIds=true -# Version code for this module (36 for v055e) -VERSION_CODE=36 +# Version code for this module (37 for v055f) +VERSION_CODE=37 From 8655ee8e48140e24f2ab227a46fceb44ae89caaa Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Wed, 24 Apr 2024 22:59:24 +0530 Subject: [PATCH 47/48] bump firestack version for v055f --- app/build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 1335973d8..7fb2cd972 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -247,8 +247,8 @@ dependencies { fullImplementation 'com.github.kirich1409:viewbindingpropertydelegate-noreflection:1.5.9' // from: https://jitpack.io/#celzero/firestack - download 'com.github.celzero:firestack:2787c84e53@aar' - implementation 'com.github.celzero:firestack:2787c84e53@aar' + download 'com.github.celzero:firestack:734a7518f1@aar' + implementation 'com.github.celzero:firestack:734a7518f1@aar' // Work manager implementation('androidx.work:work-runtime-ktx:2.9.0') { From 6ba5557e27d1bb67ec22cb3298ceb16496a5c5e1 Mon Sep 17 00:00:00 2001 From: hussainmohd-a Date: Wed, 24 Apr 2024 23:35:23 +0530 Subject: [PATCH 48/48] bump firestack version v055f --- app/build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 7fb2cd972..28f80bdc8 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -247,8 +247,8 @@ dependencies { fullImplementation 'com.github.kirich1409:viewbindingpropertydelegate-noreflection:1.5.9' // from: https://jitpack.io/#celzero/firestack - download 'com.github.celzero:firestack:734a7518f1@aar' - implementation 'com.github.celzero:firestack:734a7518f1@aar' + download 'com.github.celzero:firestack:602a1e456d@aar' + implementation 'com.github.celzero:firestack:602a1e456d@aar' // Work manager implementation('androidx.work:work-runtime-ktx:2.9.0') {