Skip to content

Commit

Permalink
improvements in rdns remote and local
Browse files Browse the repository at this point in the history
  • Loading branch information
hussainmohd-a committed Sep 19, 2023
1 parent e0fef21 commit e705e01
Show file tree
Hide file tree
Showing 12 changed files with 241 additions and 296 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,17 @@ import com.celzero.bravedns.data.AppConfig
import com.celzero.bravedns.download.BlocklistDownloadHelper
import com.celzero.bravedns.service.PersistentState
import com.celzero.bravedns.service.RethinkBlocklistManager
import com.celzero.bravedns.ui.activity.HomeScreenActivity
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.LoggerConstants.Companion.LOG_TAG_DOWNLOAD
import com.celzero.bravedns.util.UIUtils
import com.celzero.bravedns.util.Utilities
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 dnsx.Dnsx
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
Expand All @@ -55,6 +53,9 @@ import java.io.InputStream
import java.io.OutputStream
import java.util.concurrent.CancellationException
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 {
Expand Down Expand Up @@ -223,7 +224,7 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame

// create okhttp client with base url
val retrofit =
getBlocklistBaseBuilder(RetrofitManager.Companion.OkHttpDnsType.DEFAULT)
getBlocklistBaseBuilder(RetrofitManager.Companion.OkHttpDnsType.FALLBACK_DNS)
.build()
.create(IBlocklistDownload::class.java)
val response = retrofit.downloadLocalBlocklistFile(url, persistentState.appVersion, "")
Expand Down Expand Up @@ -356,16 +357,20 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame
try {
val path: String =
blocklistDownloadBasePath(context, LOCAL_BLOCKLIST_DOWNLOAD_FOLDER_NAME, timestamp)
val braveDNS =
Dnsx.newBraveDNSLocal(
path + Constants.ONDEVICE_BLOCKLIST_FILE_TD,
path + Constants.ONDEVICE_BLOCKLIST_FILE_RD,
path + Constants.ONDEVICE_BLOCKLIST_FILE_BASIC_CONFIG,
path + Constants.ONDEVICE_BLOCKLIST_FILE_TAG
)
val tdmd5 = calculateMd5(path + Constants.ONDEVICE_BLOCKLIST_FILE_TD)
val rdmd5 = calculateMd5(path + Constants.ONDEVICE_BLOCKLIST_FILE_RD)
val remoteTdmd5 =
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, "AppDownloadManager isDownloadValid? ${braveDNS != null}")
return braveDNS != null
Log.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")
return isDownloadValid
} catch (e: Exception) {
Log.e(LOG_TAG_DOWNLOAD, "AppDownloadManager isDownloadValid exception: ${e.message}", e)
}
Expand Down Expand Up @@ -512,8 +517,6 @@ class LocalBlocklistCoordinator(val context: Context, workerParams: WorkerParame
}

private fun updatePersistenceOnCopySuccess(timestamp: Long) {
// recreate bravedns object ()
appConfig.recreateBraveDnsObj()
persistentState.localBlocklistTimestamp = timestamp
persistentState.blocklistEnabled = true
// reset updatable time stamp
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ class RemoteBlocklistCoordinator(val context: Context, workerParams: WorkerParam
Log.i(LoggerConstants.LOG_TAG_DOWNLOAD, "Download remote blocklist: $timestamp")

val retrofit =
RetrofitManager.getBlocklistBaseBuilder(RetrofitManager.Companion.OkHttpDnsType.DEFAULT)
RetrofitManager.getBlocklistBaseBuilder(RetrofitManager.Companion.OkHttpDnsType.FALLBACK_DNS)
.addConverterFactory(GsonConverterFactory.create())
.build()
val retrofitInterface = retrofit.create(IBlocklistDownload::class.java)
Expand Down
33 changes: 17 additions & 16 deletions app/src/full/java/com/celzero/bravedns/download/FileHandleWorker.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,16 @@ 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.LoggerConstants.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 dnsx.Dnsx
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
Expand Down Expand Up @@ -177,26 +178,26 @@ class FileHandleWorker(val context: Context, workerParameters: WorkerParameters)
LOCAL_BLOCKLIST_DOWNLOAD_FOLDER_NAME,
timestamp
)
val braveDNS =
Dnsx.newBraveDNSLocal(
path + Constants.ONDEVICE_BLOCKLIST_FILE_TD,
path + Constants.ONDEVICE_BLOCKLIST_FILE_RD,
path + Constants.ONDEVICE_BLOCKLIST_FILE_BASIC_CONFIG,
path + Constants.ONDEVICE_BLOCKLIST_FILE_TAG
)
val tdmd5 = calculateMd5(path + Constants.ONDEVICE_BLOCKLIST_FILE_TD)
val rdmd5 = calculateMd5(path + Constants.ONDEVICE_BLOCKLIST_FILE_RD)
val remoteTdmd5 =
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, "AppDownloadManager isDownloadValid? ${braveDNS != null}")
return braveDNS != null
Log.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")
return isDownloadValid
} catch (e: Exception) {
Log.e(LOG_TAG_DOWNLOAD, "AppDownloadManager isDownloadValid exception: ${e.message}", e)
Log.e(LOG_TAG_DOWNLOAD, "AppDownloadManager, isDownloadValid err: ${e.message}", e)
}
return false
}

private fun io(f: suspend () -> Unit) {
CoroutineScope(Dispatchers.IO).launch { f() }
}

private fun ui(f: suspend () -> Unit) {
CoroutineScope(Dispatchers.Main).launch { f() }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,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 {
Expand Down Expand Up @@ -179,7 +179,7 @@ class RethinkBlocklistFragment :
selectedFileTags.observe(viewLifecycleOwner) {
if (it == null) return@observe

modifiedStamp = RethinkBlocklistManager.getStamp(requireContext(), it, type)
io { modifiedStamp = RethinkBlocklistManager.getStamp(it, type) }
}

filters.observe(viewLifecycleOwner) {
Expand Down Expand Up @@ -235,11 +235,6 @@ class RethinkBlocklistFragment :
uiCtx {
val blocklistsExist = withContext(Dispatchers.IO) { hasBlocklists() }
if (blocklistsExist) {
RethinkBlocklistManager.createBraveDns(
requireContext(),
currentBlocklistTimeStamp(),
type
)
setListAdapter()
setSimpleAdapter()
showConfigureUi()
Expand Down Expand Up @@ -430,8 +425,7 @@ class RethinkBlocklistFragment :
}

io {
val blocklistCount =
RethinkBlocklistManager.getTagsFromStamp(requireContext(), stamp, type).size
val blocklistCount = RethinkBlocklistManager.getTagsFromStamp(stamp, type).size
if (type.isLocal()) {
persistentState.localBlocklistStamp = stamp
persistentState.numberOfLocalBlocklists = blocklistCount
Expand Down Expand Up @@ -496,14 +490,17 @@ class RethinkBlocklistFragment :
}

private fun setListAdapter() {
processSelectedFileTags(getStamp())

if (type.isLocal()) {
setLocalAdapter()
} else {
setRemoteAdapter()
io {
processSelectedFileTags(getStamp())
uiCtx {
if (type.isLocal()) {
setLocalAdapter()
} else {
setRemoteAdapter()
}
showList(b.lbSimpleToggleBtn.tag.toString())
}
}
showList(b.lbSimpleToggleBtn.tag.toString())
}

private fun setSimpleAdapter() {
Expand All @@ -514,32 +511,30 @@ class RethinkBlocklistFragment :
}
}

private fun processSelectedFileTags(stamp: String) {
val list = RethinkBlocklistManager.getTagsFromStamp(requireContext(), stamp, type)
private suspend fun processSelectedFileTags(stamp: String) {
val list = RethinkBlocklistManager.getTagsFromStamp(stamp, type)
updateSelectedFileTags(list.toMutableSet())
}

private fun updateSelectedFileTags(selectedTags: MutableSet<Int>) {
io {
// clear the residues if the selected tags are empty
if (selectedTags.isEmpty()) {
if (type.isLocal()) {
RethinkBlocklistManager.clearTagsSelectionLocal()
} else {
RethinkBlocklistManager.clearTagsSelectionRemote()
}
return@io
}

private suspend fun updateSelectedFileTags(selectedTags: MutableSet<Int>) {
// clear the residues if the selected tags are empty
if (selectedTags.isEmpty()) {
if (type.isLocal()) {
RethinkBlocklistManager.updateFiletagsLocal(selectedTags, 1 /* isSelected: true */)
val list = RethinkBlocklistManager.getSelectedFileTagsLocal().toSet()
updateFileTagList(list)
RethinkBlocklistManager.clearTagsSelectionLocal()
} else {
RethinkBlocklistManager.updateFiletagsRemote(selectedTags, 1 /* isSelected: true */)
val list = RethinkBlocklistManager.getSelectedFileTagsRemote().toSet()
updateFileTagList(list)
RethinkBlocklistManager.clearTagsSelectionRemote()
}
return
}

if (type.isLocal()) {
RethinkBlocklistManager.updateFiletagsLocal(selectedTags, 1 /* isSelected: true */)
val list = RethinkBlocklistManager.getSelectedFileTagsLocal().toSet()
updateFileTagList(list)
} else {
RethinkBlocklistManager.updateFiletagsRemote(selectedTags, 1 /* isSelected: true */)
val list = RethinkBlocklistManager.getSelectedFileTagsRemote().toSet()
updateFileTagList(list)
}
}

Expand Down Expand Up @@ -576,7 +571,7 @@ class RethinkBlocklistFragment :
// split: https://max.rethinkdns.com/1:IAAgAA== [https:, , max.rethinkdns.com, 1:IAAgAA==]
split.forEach {
if (it.contains("$RETHINK_STAMP_VERSION:") && isBase64(it)) {
selectTagsForStamp(it)
io { processSelectedFileTags(it) }
showToastUiCentered(requireContext(), "Blocklists restored", Toast.LENGTH_SHORT)
return true
}
Expand All @@ -601,10 +596,6 @@ class RethinkBlocklistFragment :
return pattern.matcher(result).matches()
}

private fun selectTagsForStamp(stamp: String) {
processSelectedFileTags(stamp)
}

fun filterObserver(): MutableLiveData<Filters> {
return filters
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ class BlocklistProvider : ContentProvider() {

val context = context ?: return 0
val localFileTags = RethinkLocalFileTag(values)
val count = RethinkBlocklistManager.cpSelectFileTag(context, localFileTags)
val count = RethinkBlocklistManager.cpSelectFileTag(localFileTags)
context.contentResolver?.notifyChange(uri, null)
return count
}
Expand Down
51 changes: 0 additions & 51 deletions app/src/main/java/com/celzero/bravedns/data/AppConfig.kt
Original file line number Diff line number Diff line change
Expand Up @@ -42,24 +42,15 @@ import com.celzero.bravedns.database.RethinkDnsEndpointRepository
import com.celzero.bravedns.service.PersistentState
import com.celzero.bravedns.service.TcpProxyHelper
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.Constants.Companion.MAX_ENDPOINT
import com.celzero.bravedns.util.Constants.Companion.ONDEVICE_BLOCKLIST_FILE_BASIC_CONFIG
import com.celzero.bravedns.util.Constants.Companion.ONDEVICE_BLOCKLIST_FILE_RD
import com.celzero.bravedns.util.Constants.Companion.ONDEVICE_BLOCKLIST_FILE_TAG
import com.celzero.bravedns.util.Constants.Companion.ONDEVICE_BLOCKLIST_FILE_TD
import com.celzero.bravedns.util.InternetProtocol
import com.celzero.bravedns.util.InternetProtocol.Companion.getInternetProtocol
import com.celzero.bravedns.util.KnownPorts.Companion.DNS_PORT
import com.celzero.bravedns.util.LoggerConstants.Companion.LOG_TAG_VPN
import com.celzero.bravedns.util.OrbotHelper
import com.celzero.bravedns.util.PcapMode
import com.celzero.bravedns.util.Utilities
import com.celzero.bravedns.util.Utilities.getDnsPort
import com.celzero.bravedns.util.Utilities.isAtleastQ
import dnsx.BraveDNS
import dnsx.Dnsx
import inet.ipaddr.IPAddressString
import intra.Bridge
import java.net.InetAddress
Expand All @@ -83,7 +74,6 @@ internal constructor(
private var appTunDnsMode: TunDnsMode = TunDnsMode.NONE
private var systemDns: SystemDns = SystemDns("", DNS_PORT)
private var braveModeObserver: MutableLiveData<Int> = MutableLiveData()
private var braveDns: BraveDNS? = null
private var pcapFilePath: String = ""

companion object {
Expand All @@ -95,47 +85,6 @@ internal constructor(
init {
connectedDns.postValue(persistentState.connectedDnsName)
setDnsMode()
createBraveDnsObjectIfNeeded()
}

private fun createBraveDnsObjectIfNeeded() {
if (!persistentState.blocklistEnabled) return

try {
val path: String =
Utilities.blocklistDownloadBasePath(
context,
LOCAL_BLOCKLIST_DOWNLOAD_FOLDER_NAME,
persistentState.localBlocklistTimestamp
)
braveDns =
Dnsx.newBraveDNSLocal(
path + ONDEVICE_BLOCKLIST_FILE_TD,
path + ONDEVICE_BLOCKLIST_FILE_RD,
path + ONDEVICE_BLOCKLIST_FILE_BASIC_CONFIG,
path + ONDEVICE_BLOCKLIST_FILE_TAG
)
} catch (e: Exception) {
// Set local blocklist enabled to false and reset the timestamp
// if there is a failure creating bravedns
persistentState.blocklistEnabled = false
Log.e(LOG_TAG_VPN, "Local brave dns set exception :${e.message}", e)
// 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 = INIT_TIME_MS
}
}

fun getBraveDnsObj(): BraveDNS? {
if (braveDns == null) {
createBraveDnsObjectIfNeeded()
}

return braveDns
}

fun recreateBraveDnsObj() {
createBraveDnsObjectIfNeeded()
}

data class TunnelOptions(
Expand Down
Loading

0 comments on commit e705e01

Please sign in to comment.