package com.example.netshareecohub.routing import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.pm.PackageManager import android.net.TetheringManager import android.os.Build import android.os.Handler import android.os.Looper import android.provider.Settings import android.widget.Toast import com.example.netshareecohub.R import com.example.netshareecohub.data.logging.Logger import kotlinx.coroutines.suspendCancellableCoroutine import java.util.concurrent.atomic.AtomicBoolean import kotlin.coroutines.resume /** * Tethering controller for ordinary app builds. * * Android's tethering service enforces the caller's real permissions. This class deliberately * does not use root commands, hidden-API reflection, or Settings-screen automation. */ class SystemTetheringManager { private val tag = "SystemTetheringManager" private val mainHandler = Handler(Looper.getMainLooper()) private val startInProgress = AtomicBoolean(false) private val startedByThisInstance = AtomicBoolean(false) fun openSystemTetheringSettings(context: Context): Boolean { // Keep all app flows in-app. A normal APK cannot grant itself privileged tethering access. Toast.makeText( context, context.getString(R.string.tethering_settings_not_opened), Toast.LENGTH_LONG ).show() Logger.info(tag, "Settings navigation intentionally disabled; no external screen was opened.") return false } fun isTetheringSupported(context: Context): Boolean { val sdkCanAttempt = Build.VERSION.SDK_INT in Build.VERSION_CODES.R..35 return sdkCanAttempt && hasControlPermission(context) } private fun hasControlPermission(context: Context): Boolean { val privileged = context.checkSelfPermission(PERMISSION_TETHER_PRIVILEGED) == PackageManager.PERMISSION_GRANTED return privileged || Settings.System.canWrite(context) } private fun permissionMessage(context: Context): String = context.getString(R.string.tethering_permission_missing) /** * Attempts the Android tethering request on Android 11–15 where the platform implementation * has this request path. The OS callback, not the button press, determines the result. * Android 16's public SDK only exposes a normal-app request configuration for Wi-Fi, so this * class does not pretend that it can request Ethernet tethering there. */ fun startTethering( context: Context, tetheringType: Int = TETHERING_ETHERNET, onResult: (Boolean, String?) -> Unit ) { if (tetheringType != TETHERING_ETHERNET) { onResult(false, context.getString(R.string.tethering_only_ethernet_supported)) return } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { onResult(false, context.getString(R.string.tethering_api_unavailable)) return } if (Build.VERSION.SDK_INT >= 36) { onResult(false, context.getString(R.string.tethering_android16_limit)) return } if (!hasControlPermission(context)) { onResult(false, permissionMessage(context)) return } if (startedByThisInstance.get()) { onResult(true, context.getString(R.string.tethering_already_started)) return } if (!startInProgress.compareAndSet(false, true)) { onResult(false, context.getString(R.string.tethering_request_in_progress)) return } val manager = context.getSystemService(TetheringManager::class.java) if (manager == null) { startInProgress.set(false) onResult(false, context.getString(R.string.tethering_service_unavailable)) return } val completed = AtomicBoolean(false) val timeout = Runnable { if (completed.compareAndSet(false, true)) { startInProgress.set(false) onResult(false, context.getString(R.string.tethering_start_timeout)) } } mainHandler.postDelayed(timeout, START_TIMEOUT_MS) try { // Ethernet's AOSP tethering type is 5. The OS still enforces access permissions. val request = TetheringManager.TetheringRequest.Builder(TETHERING_ETHERNET).build() manager.startTethering( request, context.mainExecutor, object : TetheringManager.StartTetheringCallback { override fun onTetheringStarted() { if (!completed.compareAndSet(false, true)) return mainHandler.removeCallbacks(timeout) startInProgress.set(false) startedByThisInstance.set(true) val message = context.getString(R.string.tethering_start_confirmed) Logger.info(tag, message) onResult(true, message) } override fun onTetheringFailed(error: Int) { if (!completed.compareAndSet(false, true)) return mainHandler.removeCallbacks(timeout) startInProgress.set(false) val message = context.getString( R.string.tethering_start_failed_code, error, explainTetheringError(error, context) ) Logger.warn(tag, message) onResult(false, message) } } ) } catch (e: SecurityException) { mainHandler.removeCallbacks(timeout) if (completed.compareAndSet(false, true)) { startInProgress.set(false) val message = context.getString(R.string.tethering_permission_denied) Logger.warn(tag, "$message ${e.message.orEmpty()}") onResult(false, message) } } catch (e: IllegalArgumentException) { mainHandler.removeCallbacks(timeout) if (completed.compareAndSet(false, true)) { startInProgress.set(false) val message = context.getString(R.string.tethering_type_not_supported) Logger.warn(tag, "$message ${e.message.orEmpty()}") onResult(false, message) } } catch (e: LinkageError) { mainHandler.removeCallbacks(timeout) if (completed.compareAndSet(false, true)) { startInProgress.set(false) onResult(false, context.getString(R.string.tethering_api_unavailable)) } } catch (e: Exception) { mainHandler.removeCallbacks(timeout) if (completed.compareAndSet(false, true)) { startInProgress.set(false) val message = context.getString( R.string.tethering_start_exception, e.localizedMessage ?: e.javaClass.simpleName ) Logger.error(tag, message, e) onResult(false, message) } } } suspend fun startTetheringAwait( context: Context, tetheringType: Int = TETHERING_ETHERNET ): Pair = suspendCancellableCoroutine { continuation -> startTethering(context, tetheringType) { success, message -> if (continuation.isActive) continuation.resume(success to message) } } /** * Stop only a session this controller successfully started in this process. On Android 11–15 * stopTethering has no completion callback, so we listen for the legacy state-change broadcast * and report failure if Android never confirms that Ethernet is no longer tethered. */ fun stopTethering( context: Context, tetheringType: Int = TETHERING_ETHERNET, onResult: (Boolean, String?) -> Unit ) { if (tetheringType != TETHERING_ETHERNET) { onResult(false, context.getString(R.string.tethering_only_ethernet_supported)) return } if (!startedByThisInstance.get()) { onResult(false, context.getString(R.string.tethering_no_owned_session)) return } if (Build.VERSION.SDK_INT >= 36) { onResult(false, context.getString(R.string.tethering_android16_limit)) return } if (!hasControlPermission(context)) { onResult(false, permissionMessage(context)) return } val manager = context.getSystemService(TetheringManager::class.java) if (manager == null) { onResult(false, context.getString(R.string.tethering_service_unavailable)) return } val appContext = context.applicationContext val finished = AtomicBoolean(false) lateinit var receiver: BroadcastReceiver lateinit var timeout: Runnable fun finish(success: Boolean, message: String) { if (!finished.compareAndSet(false, true)) return mainHandler.removeCallbacks(timeout) try { appContext.unregisterReceiver(receiver) } catch (_: Exception) { // Receiver may already have been removed by the system/lifecycle. } if (success) startedByThisInstance.set(false) Logger.info(tag, message) onResult(success, message) } receiver = object : BroadcastReceiver() { override fun onReceive(receiveContext: Context?, intent: Intent?) { if (intent?.action != TetheringManager.ACTION_TETHER_STATE_CHANGED) return if (!intent.hasExtra(TetheringManager.EXTRA_ACTIVE_TETHER)) return val active = intent.getStringArrayListExtra(TetheringManager.EXTRA_ACTIVE_TETHER) ?.toList() ?: intent.getStringArrayExtra(TetheringManager.EXTRA_ACTIVE_TETHER)?.toList() ?: return val ethernetStillActive = active.any(::looksLikeEthernetInterface) if (!ethernetStillActive) { finish(true, appContext.getString(R.string.tethering_stop_confirmed)) } } } timeout = Runnable { finish(false, appContext.getString(R.string.tethering_stop_unverified)) } try { val filter = IntentFilter(TetheringManager.ACTION_TETHER_STATE_CHANGED) if (Build.VERSION.SDK_INT >= 33) { appContext.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED) } else { @Suppress("DEPRECATION") appContext.registerReceiver(receiver, filter) } manager.stopTethering(tetheringType) mainHandler.postDelayed(timeout, STOP_TIMEOUT_MS) } catch (e: SecurityException) { finish(false, appContext.getString(R.string.tethering_permission_denied)) } catch (e: LinkageError) { finish(false, appContext.getString(R.string.tethering_api_unavailable)) } catch (e: Exception) { finish( false, appContext.getString( R.string.tethering_stop_exception, e.localizedMessage ?: e.javaClass.simpleName ) ) } } suspend fun stopTetheringAwait( context: Context, tetheringType: Int = TETHERING_ETHERNET ): Pair = suspendCancellableCoroutine { continuation -> stopTethering(context, tetheringType) { success, message -> if (continuation.isActive) continuation.resume(success to message) } } private fun looksLikeEthernetInterface(name: String): Boolean { val value = name.lowercase() return value.startsWith("eth") || value.startsWith("enx") || value.startsWith("enp") || value.startsWith("usb") || value.startsWith("rndis") || value.startsWith("ncm") || value.startsWith("lan") } private fun explainTetheringError(code: Int, context: Context): String = when (code) { 1 -> context.getString(R.string.tethering_error_unknown_interface) 2 -> context.getString(R.string.tethering_error_service_unavailable) 3 -> context.getString(R.string.tethering_error_unsupported) 4 -> context.getString(R.string.tethering_error_interface_unavailable) 11 -> context.getString(R.string.tethering_error_provisioning) 12 -> context.getString(R.string.tethering_error_dhcp) 13 -> context.getString(R.string.tethering_error_entitlement) 14, 15 -> context.getString(R.string.tethering_error_permission) else -> context.getString(R.string.tethering_error_generic) } companion object { const val TETHERING_WIFI = 0 const val TETHERING_USB = 1 const val TETHERING_BLUETOOTH = 2 const val TETHERING_ETHERNET = 5 private const val PERMISSION_TETHER_PRIVILEGED = "android.permission.TETHER_PRIVILEGED" private const val START_TIMEOUT_MS = 30_000L private const val STOP_TIMEOUT_MS = 5_000L } }