done
15
.gitignore
vendored
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
*.iml
|
||||||
|
.gradle
|
||||||
|
/local.properties
|
||||||
|
/.idea/caches
|
||||||
|
/.idea/libraries
|
||||||
|
/.idea/modules.xml
|
||||||
|
/.idea/workspace.xml
|
||||||
|
/.idea/navEditor.xml
|
||||||
|
/.idea/assetWizardSettings.xml
|
||||||
|
.DS_Store
|
||||||
|
/build
|
||||||
|
/captures
|
||||||
|
.externalNativeBuild
|
||||||
|
.cxx
|
||||||
|
local.properties
|
||||||
32
README_ETHERNET_FIX.md
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
# Ethernet Tethering Diagnostics and Status Patch
|
||||||
|
|
||||||
|
This project patch repairs misleading connection-state handling and makes the dashboard report the actual Ethernet/tethering state as far as the Android platform permits.
|
||||||
|
|
||||||
|
## Changes in this patch
|
||||||
|
|
||||||
|
- Replaced the old `SYSTEM_TETHERING` branch that marked routing `ACTIVE` without a system callback.
|
||||||
|
- Updated routing stop handling so it does not report `STOPPED` before a stop is confirmed. The Ethernet tethering type is used rather than the Wi-Fi type.
|
||||||
|
- The dashboard now labels the physical link as `Ethernet Interface`, shows a real connection-state label, and displays the current tethering result message.
|
||||||
|
- Removed the previous dashboard instruction to open Android Settings. Settings navigation callbacks remain in-app only and show an explanation instead.
|
||||||
|
- Replaced the old scripted iPhone-unlock terminal log view with actual network/tethering diagnostic logs. This patch does not implement or claim to bypass iPhone Activation Lock.
|
||||||
|
- Moved Ethernet refresh and ARP scanning work away from the UI thread and retained root-check work on IO.
|
||||||
|
- Added English and Simplified Chinese strings for the new status and error messages.
|
||||||
|
- The device model card continues to show only the dynamically detected model.
|
||||||
|
|
||||||
|
## Important platform limit
|
||||||
|
|
||||||
|
This is still a normal third-party Android application. It cannot grant itself `TETHER_PRIVILEGED`. On Android 13–15, the platform may accept a tethering request only when the required system access is already available; this patch does not open Settings automatically. On Android 16, the public SDK does not expose a universal Ethernet tethering request for ordinary apps. Some models therefore will show `Unavailable` rather than a false `Connected` status. OEM-authorized system integration may be required for direct control.
|
||||||
|
|
||||||
|
The screenshot supplied with the project also showed `Ethernet Interface: Disconnected`. A compatible physical Ethernet adapter/cable and an active link are required for link status to become connected; software cannot manufacture a physical link.
|
||||||
|
|
||||||
|
## Build and verification status
|
||||||
|
|
||||||
|
Static resource checks passed: both language XML files parse, contain no duplicate string keys, and include every `R.string` referenced by Kotlin source. A Gradle build could not be completed in this environment because the Gradle wrapper distribution was not cached and `services.gradle.org` was unreachable; no Android SDK `android.jar` is installed here. Therefore this is a source patch, not a newly built or device-tested APK.
|
||||||
|
|
||||||
|
## Build on your computer
|
||||||
|
|
||||||
|
1. Extract this ZIP to a new folder.
|
||||||
|
2. Open that folder in Android Studio.
|
||||||
|
3. Let Android Studio select your local Android SDK; the Windows-specific `local.properties` from the uploaded project was intentionally omitted.
|
||||||
|
4. Sync Gradle and run **Build > Make Project**.
|
||||||
|
5. Test on the real device with a supported Ethernet adapter and cable. If Android reports that the required control permission is unavailable, the normal APK cannot force the system to enable Ethernet tethering.
|
||||||
63
README_ETHERNET_TETHERING_FOCUSED.md
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
# Ethernet Tethering: focused setup and diagnosis
|
||||||
|
|
||||||
|
This patch focuses on the Ethernet Tethering path only. It does not pretend to bypass Android system permissions or hardware support.
|
||||||
|
|
||||||
|
## What was changed
|
||||||
|
|
||||||
|
- Kept the Android `TetheringManager` request path for Android 11–15 (API 30–35) when the app has the required access.
|
||||||
|
- Updated the permission message to explain the one-time setup without auto-opening Settings.
|
||||||
|
- Removed `TETHER_PRIVILEGED` from the ordinary APK manifest because declaring a signature/privileged permission does not grant it. A manufacturer/system-app build would need its own authorized manifest and signing configuration.
|
||||||
|
- Fixed the state classification so a missing permission is a permission failure, not a claim that the device hardware is unsupported.
|
||||||
|
- The Start flow no longer refuses to submit a system request only because no Ethernet interface is currently visible; some builds expose or bring up the downstream interface after tethering starts. The OS callback is still authoritative.
|
||||||
|
- Added Windows and shell scripts to grant the `WRITE_SETTINGS` app-op on an owner's authorized development device.
|
||||||
|
|
||||||
|
## One-time setup on a Windows development PC
|
||||||
|
|
||||||
|
1. Install the APK whose application ID is `com.ecohub.locksolved`.
|
||||||
|
2. Connect the phone to the PC with USB and authorize USB debugging on the phone.
|
||||||
|
3. Open this project folder in Explorer and run `tools\grant_write_settings.bat`, or run the same commands in Android Studio Terminal:
|
||||||
|
|
||||||
|
```bat
|
||||||
|
adb devices
|
||||||
|
adb shell appops set com.ecohub.locksolved WRITE_SETTINGS allow
|
||||||
|
adb shell appops get com.ecohub.locksolved WRITE_SETTINGS
|
||||||
|
```
|
||||||
|
|
||||||
|
The final command should show `WRITE_SETTINGS: allow`. This is a development setup for your own device; `WRITE_SETTINGS` gives the app a broader special permission to modify system settings, so only grant it to a source build you trust. It does not grant `TETHER_PRIVILEGED`. The app itself will not open Settings.
|
||||||
|
|
||||||
|
If you prefer the Android UI instead, `WRITE_SETTINGS` can only be granted by the system's special-access screen; a normal app cannot grant it to itself.
|
||||||
|
|
||||||
|
## Verify the physical Ethernet link
|
||||||
|
|
||||||
|
Your screenshot showed `Ethernet Interface: Disconnected`. This means the app did not observe a live Ethernet link. A software API cannot create a physical link. Connect a compatible USB-C/OTG Ethernet adapter and Ethernet cable to the actual downstream device, and make sure the adapter's link/activity LEDs come on. Then refresh the app. A down/no-carrier interface means a client connection cannot yet be verified, even if a tethering request is accepted.
|
||||||
|
|
||||||
|
## Try Start Sharing and inspect the real result
|
||||||
|
|
||||||
|
After the permission setup, close and reopen the app and tap **Start Sharing** once. The controller will submit the Ethernet request for API 30–35 and report the actual platform callback error if Android rejects it.
|
||||||
|
|
||||||
|
For logs, use Android Studio **View → Tool Windows → Logcat** and filter for `SystemTetheringManager`, `TetheringCapabilityChecker`, `MainViewModel`, and `AndroidRuntime`. Keep the exact error code/message.
|
||||||
|
|
||||||
|
Common callback results from AOSP include:
|
||||||
|
|
||||||
|
- `1` unknown interface
|
||||||
|
- `2` tethering service unavailable
|
||||||
|
- `3` unsupported tethering type/device implementation
|
||||||
|
- `4` tethering interface unavailable
|
||||||
|
- `11` provisioning failed
|
||||||
|
- `12` DHCP server failed
|
||||||
|
- `13` entitlement/provisioning check failed
|
||||||
|
- `14` no permission to change tethering
|
||||||
|
- `15` no permission to access tethering
|
||||||
|
|
||||||
|
## Android 16 / universal-device limitations
|
||||||
|
|
||||||
|
The ordinary public Android 16 API documents Wi-Fi tethering requests, not a supported Ethernet request for normal APKs. Devices may also lack an OEM-configured Ethernet downstream interface. This patch does not use undocumented API calls, reflection, root commands, or Settings automation to bypass those restrictions. Android 16 or a device that returns “unsupported” may require manufacturer-authorized system integration.
|
||||||
|
|
||||||
|
## Important distinction
|
||||||
|
|
||||||
|
- `WRITE_SETTINGS` access: allows the request path to be attempted on supported Android 11–15 systems.
|
||||||
|
- Ethernet interface present + carrier/link up: physical downstream path is available.
|
||||||
|
- `TetheringManager` success callback: Android accepted/started the tethering request.
|
||||||
|
- Client connected / internet reachable: separate facts that need their own verification.
|
||||||
|
|
||||||
|
Do not treat any one of these as proof of all the others.
|
||||||
1
app/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
/build
|
||||||
97
app/build.gradle.kts
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
plugins {
|
||||||
|
alias(libs.plugins.android.application)
|
||||||
|
alias(libs.plugins.kotlin.compose)
|
||||||
|
alias(libs.plugins.google.devtools.ksp)
|
||||||
|
alias(libs.plugins.jetbrains.kotlin.plugin.serialization)
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "com.example.netshareecohub"
|
||||||
|
compileSdk {
|
||||||
|
version = release(37)
|
||||||
|
}
|
||||||
|
|
||||||
|
defaultConfig {
|
||||||
|
applicationId = "com.ecohub.locksolved"
|
||||||
|
minSdk = 29
|
||||||
|
targetSdk = 37
|
||||||
|
versionCode = 1
|
||||||
|
versionName = "1.0"
|
||||||
|
|
||||||
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
|
}
|
||||||
|
|
||||||
|
buildTypes {
|
||||||
|
release {
|
||||||
|
optimization {
|
||||||
|
enable = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_11
|
||||||
|
targetCompatibility = JavaVersion.VERSION_11
|
||||||
|
}
|
||||||
|
buildFeatures {
|
||||||
|
compose = true
|
||||||
|
}
|
||||||
|
testOptions {
|
||||||
|
unitTests {
|
||||||
|
isReturnDefaultValues = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
implementation(platform(libs.androidx.compose.bom))
|
||||||
|
implementation(libs.accompanist.permissions)
|
||||||
|
implementation(libs.androidx.activity.compose)
|
||||||
|
implementation(libs.androidx.camera.camera2)
|
||||||
|
implementation(libs.androidx.camera.core)
|
||||||
|
implementation(libs.androidx.camera.lifecycle)
|
||||||
|
implementation(libs.androidx.camera.view)
|
||||||
|
implementation(libs.androidx.compose.adaptive)
|
||||||
|
implementation(libs.androidx.compose.adaptive.layout)
|
||||||
|
implementation(libs.androidx.compose.adaptive.navigation3)
|
||||||
|
implementation(libs.androidx.compose.material.icons.core)
|
||||||
|
implementation(libs.androidx.compose.material.icons.extended)
|
||||||
|
implementation(libs.androidx.compose.material3)
|
||||||
|
implementation(libs.androidx.compose.ui)
|
||||||
|
implementation(libs.androidx.compose.ui.graphics)
|
||||||
|
implementation(libs.androidx.compose.ui.tooling.preview)
|
||||||
|
implementation(libs.androidx.core.ktx)
|
||||||
|
implementation(libs.androidx.datastore.preferences)
|
||||||
|
implementation(libs.androidx.lifecycle.runtime.compose)
|
||||||
|
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||||
|
implementation(libs.androidx.lifecycle.viewmodel.compose)
|
||||||
|
implementation(libs.androidx.lifecycle.viewmodel.navigation3)
|
||||||
|
implementation(libs.androidx.navigation3.runtime)
|
||||||
|
implementation(libs.androidx.navigation3.ui)
|
||||||
|
implementation(libs.androidx.room.ktx)
|
||||||
|
implementation(libs.androidx.room.runtime)
|
||||||
|
implementation(libs.coil.compose)
|
||||||
|
implementation(libs.converter.moshi)
|
||||||
|
implementation(libs.kotlinx.coroutines.android)
|
||||||
|
implementation(libs.kotlinx.coroutines.core)
|
||||||
|
implementation(libs.kotlinx.serialization.core)
|
||||||
|
implementation(libs.logging.interceptor)
|
||||||
|
implementation(libs.material)
|
||||||
|
implementation("androidx.appcompat:appcompat:1.6.1")
|
||||||
|
implementation(libs.moshi.kotlin)
|
||||||
|
implementation(libs.okhttp)
|
||||||
|
implementation(libs.play.services.location)
|
||||||
|
implementation(libs.retrofit)
|
||||||
|
testImplementation(libs.androidx.core)
|
||||||
|
testImplementation(libs.androidx.junit)
|
||||||
|
testImplementation(libs.junit)
|
||||||
|
testImplementation(libs.kotlinx.coroutines.test)
|
||||||
|
androidTestImplementation(platform(libs.androidx.compose.bom))
|
||||||
|
androidTestImplementation(libs.androidx.compose.ui.test.junit4)
|
||||||
|
androidTestImplementation(libs.androidx.espresso.core)
|
||||||
|
androidTestImplementation(libs.androidx.junit)
|
||||||
|
androidTestImplementation(libs.androidx.runner)
|
||||||
|
debugImplementation(libs.androidx.compose.ui.test.manifest)
|
||||||
|
debugImplementation(libs.androidx.compose.ui.tooling)
|
||||||
|
"ksp"(libs.androidx.room.compiler)
|
||||||
|
"ksp"(libs.moshi.kotlin.codegen)
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package com.example.netshareecohub
|
||||||
|
|
||||||
|
import androidx.test.platform.app.InstrumentationRegistry
|
||||||
|
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||||
|
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
|
||||||
|
import org.junit.Assert.*
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Instrumented test, which will execute on an Android device.
|
||||||
|
*
|
||||||
|
* See [testing documentation](http://d.android.com/tools/testing).
|
||||||
|
*/
|
||||||
|
@RunWith(AndroidJUnit4::class)
|
||||||
|
class ExampleInstrumentedTest {
|
||||||
|
@Test
|
||||||
|
fun useAppContext() {
|
||||||
|
// Context of the app under test.
|
||||||
|
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
|
||||||
|
assertEquals("com.example.netshareecohub", appContext.packageName)
|
||||||
|
}
|
||||||
|
}
|
||||||
49
app/src/main/AndroidManifest.xml
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:tools="http://schemas.android.com/tools">
|
||||||
|
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" tools:ignore="ForegroundServicePermission" />
|
||||||
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
<uses-permission android:name="android.permission.WRITE_SETTINGS" tools:ignore="ProtectedPermissions" />
|
||||||
|
|
||||||
|
<application
|
||||||
|
android:allowBackup="true"
|
||||||
|
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||||
|
android:fullBackupContent="@xml/backup_rules"
|
||||||
|
android:icon="@mipmap/ic_launcher"
|
||||||
|
android:label="@string/app_name"
|
||||||
|
android:roundIcon="@mipmap/ic_launcher_round"
|
||||||
|
android:supportsRtl="true"
|
||||||
|
android:theme="@style/Theme.NetShareEcohub"
|
||||||
|
android:networkSecurityConfig="@xml/network_security_config">
|
||||||
|
<activity
|
||||||
|
android:name=".MainActivity"
|
||||||
|
android:exported="true"
|
||||||
|
android:label="@string/app_name"
|
||||||
|
android:theme="@style/Theme.NetShareEcohub"
|
||||||
|
android:windowSoftInputMode="adjustResize">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
|
||||||
|
<service
|
||||||
|
android:name=".routing.NetShareVpnService"
|
||||||
|
android:permission="android.permission.BIND_VPN_SERVICE"
|
||||||
|
android:foregroundServiceType="connectedDevice"
|
||||||
|
android:exported="false">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.net.VpnService" />
|
||||||
|
</intent-filter>
|
||||||
|
</service>
|
||||||
|
</application>
|
||||||
|
|
||||||
|
</manifest>
|
||||||
114
app/src/main/java/com/example/netshareecohub/MainActivity.kt
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
package com.example.netshareecohub
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
|
||||||
|
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.provider.Settings
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.activity.ComponentActivity
|
||||||
|
import androidx.activity.compose.setContent
|
||||||
|
import androidx.activity.enableEdgeToEdge
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.activity.viewModels
|
||||||
|
import androidx.lifecycle.ViewModel
|
||||||
|
import androidx.lifecycle.ViewModelProvider
|
||||||
|
import com.example.netshareecohub.dhcp.DhcpServer
|
||||||
|
import com.example.netshareecohub.ethernet.EthernetMonitor
|
||||||
|
import com.example.netshareecohub.ui.AppNavigation
|
||||||
|
import com.example.netshareecohub.ui.theme.NetShareEcohubTheme
|
||||||
|
import com.example.netshareecohub.viewmodel.MainViewModel
|
||||||
|
|
||||||
|
import com.example.netshareecohub.data.auth.AppDatabase
|
||||||
|
import com.example.netshareecohub.data.auth.AuthRepository
|
||||||
|
|
||||||
|
|
||||||
|
import com.example.netshareecohub.ui.auth.LoginScreen
|
||||||
|
import com.example.netshareecohub.viewmodel.AuthViewModel
|
||||||
|
import androidx.compose.runtime.collectAsState
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
|
|
||||||
|
|
||||||
|
class MainActivity : ComponentActivity() {
|
||||||
|
|
||||||
|
private lateinit var ethernetMonitor: EthernetMonitor
|
||||||
|
private lateinit var dhcpServer: DhcpServer
|
||||||
|
|
||||||
|
private val viewModel: MainViewModel by viewModels {
|
||||||
|
object : ViewModelProvider.Factory {
|
||||||
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
override fun <T : ViewModel> create(modelClass: Class<T>): T {
|
||||||
|
return MainViewModel(
|
||||||
|
ethernetMonitor = ethernetMonitor,
|
||||||
|
dhcpServer = dhcpServer
|
||||||
|
) as T
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val authViewModel: AuthViewModel by viewModels {
|
||||||
|
object : ViewModelProvider.Factory {
|
||||||
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
override fun <T : ViewModel> create(modelClass: Class<T>): T {
|
||||||
|
val db = AppDatabase.getDatabase(applicationContext)
|
||||||
|
val repo = AuthRepository(db.userDao())
|
||||||
|
return AuthViewModel(application, repo) as T
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
enableEdgeToEdge()
|
||||||
|
|
||||||
|
// Request Notification Permission for Android 13+
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||||
|
val requestPermissionLauncher = registerForActivityResult(
|
||||||
|
ActivityResultContracts.RequestPermission()
|
||||||
|
) { isGranted: Boolean ->
|
||||||
|
if (!isGranted) {
|
||||||
|
Toast.makeText(this, "Notification permission is required for background service", Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (ContextCompat.checkSelfPermission(
|
||||||
|
this,
|
||||||
|
Manifest.permission.POST_NOTIFICATIONS
|
||||||
|
) != PackageManager.PERMISSION_GRANTED
|
||||||
|
) {
|
||||||
|
requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ethernetMonitor = EthernetMonitor(this)
|
||||||
|
dhcpServer = DhcpServer()
|
||||||
|
|
||||||
|
setContent {
|
||||||
|
NetShareEcohubTheme {
|
||||||
|
val currentUser by authViewModel.currentUser.collectAsState()
|
||||||
|
|
||||||
|
if (currentUser == null) {
|
||||||
|
LoginScreen(authViewModel = authViewModel)
|
||||||
|
} else {
|
||||||
|
AppNavigation(viewModel = viewModel, authViewModel = authViewModel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onResume() {
|
||||||
|
super.onResume()
|
||||||
|
if (::ethernetMonitor.isInitialized) {
|
||||||
|
ethernetMonitor.refresh()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
super.onDestroy()
|
||||||
|
ethernetMonitor.stopMonitoring()
|
||||||
|
dhcpServer.stop()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package com.example.netshareecohub.data.auth
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.room.Database
|
||||||
|
import androidx.room.Room
|
||||||
|
import androidx.room.RoomDatabase
|
||||||
|
|
||||||
|
@Database(entities = [User::class], version = 1, exportSchema = false)
|
||||||
|
abstract class AppDatabase : RoomDatabase() {
|
||||||
|
abstract fun userDao(): UserDao
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
@Volatile
|
||||||
|
private var INSTANCE: AppDatabase? = null
|
||||||
|
|
||||||
|
fun getDatabase(context: Context): AppDatabase {
|
||||||
|
return INSTANCE ?: synchronized(this) {
|
||||||
|
val instance = Room.databaseBuilder(
|
||||||
|
context.applicationContext,
|
||||||
|
AppDatabase::class.java,
|
||||||
|
"ecohub_auth_db"
|
||||||
|
).build()
|
||||||
|
INSTANCE = instance
|
||||||
|
instance
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.example.netshareecohub.data.auth
|
||||||
|
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
|
||||||
|
class AuthRepository(private val userDao: UserDao) {
|
||||||
|
|
||||||
|
val allUsers: Flow<List<User>> = userDao.getAllUsers()
|
||||||
|
|
||||||
|
suspend fun initializeDefaultUsers() {
|
||||||
|
val existing = userDao.getUserByUsername("Ecohub")
|
||||||
|
if (existing == null) {
|
||||||
|
val adminUser = User(
|
||||||
|
username = "Ecohub",
|
||||||
|
passwordHash = "Ecohub@520",
|
||||||
|
role = "ADMIN"
|
||||||
|
)
|
||||||
|
userDao.insertUser(adminUser)
|
||||||
|
} else if (existing.passwordHash != "Ecohub@520") {
|
||||||
|
userDao.updateUser(existing.copy(passwordHash = "Ecohub@520"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun getUserByUsername(username: String): User? {
|
||||||
|
return userDao.getUserByUsername(username)
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun insertUser(user: User) {
|
||||||
|
userDao.insertUser(user)
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun updateUser(user: User) {
|
||||||
|
userDao.updateUser(user)
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun deleteUser(user: User) {
|
||||||
|
userDao.deleteUser(user)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.example.netshareecohub.data.auth
|
||||||
|
|
||||||
|
import androidx.room.Entity
|
||||||
|
import androidx.room.PrimaryKey
|
||||||
|
|
||||||
|
@Entity(tableName = "users")
|
||||||
|
data class User(
|
||||||
|
@PrimaryKey(autoGenerate = true) val id: Int = 0,
|
||||||
|
val username: String,
|
||||||
|
val passwordHash: String, // Storing plain or hashed password
|
||||||
|
val role: String // "ADMIN" or "NORMAL"
|
||||||
|
)
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.example.netshareecohub.data.auth
|
||||||
|
|
||||||
|
import androidx.room.Dao
|
||||||
|
import androidx.room.Delete
|
||||||
|
import androidx.room.Insert
|
||||||
|
import androidx.room.OnConflictStrategy
|
||||||
|
import androidx.room.Query
|
||||||
|
import androidx.room.Update
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
|
||||||
|
@Dao
|
||||||
|
interface UserDao {
|
||||||
|
@Query("SELECT * FROM users WHERE username = :username LIMIT 1")
|
||||||
|
suspend fun getUserByUsername(username: String): User?
|
||||||
|
|
||||||
|
@Query("SELECT * FROM users")
|
||||||
|
fun getAllUsers(): Flow<List<User>>
|
||||||
|
|
||||||
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
|
suspend fun insertUser(user: User)
|
||||||
|
|
||||||
|
@Update
|
||||||
|
suspend fun updateUser(user: User)
|
||||||
|
|
||||||
|
@Delete
|
||||||
|
suspend fun deleteUser(user: User)
|
||||||
|
|
||||||
|
@Query("SELECT COUNT(*) FROM users")
|
||||||
|
suspend fun getUserCount(): Int
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
package com.example.netshareecohub.data.logging
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import java.text.SimpleDateFormat
|
||||||
|
import java.util.Date
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
enum class LogLevel {
|
||||||
|
DEBUG, INFO, WARN, ERROR
|
||||||
|
}
|
||||||
|
|
||||||
|
data class LogEntry(
|
||||||
|
val id: Long,
|
||||||
|
val timestamp: Long,
|
||||||
|
val formattedTime: String,
|
||||||
|
val level: LogLevel,
|
||||||
|
val tag: String,
|
||||||
|
val message: String,
|
||||||
|
val throwable: Throwable? = null
|
||||||
|
) {
|
||||||
|
override fun toString(): String {
|
||||||
|
return "[$formattedTime] [${level.name}] [$tag] $message"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
object Logger {
|
||||||
|
private const val DEFAULT_TAG = "NetShareEcoHub"
|
||||||
|
private const val MAX_LOGS = 1000
|
||||||
|
|
||||||
|
private var nextId = 1L
|
||||||
|
private val timeFormat = SimpleDateFormat("HH:mm:ss.SSS", Locale.US)
|
||||||
|
|
||||||
|
private val _logs = MutableStateFlow<List<LogEntry>>(emptyList())
|
||||||
|
val logs: StateFlow<List<LogEntry>> = _logs.asStateFlow()
|
||||||
|
|
||||||
|
fun info(tag: String = DEFAULT_TAG, message: String) {
|
||||||
|
log(LogLevel.INFO, tag, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun warn(tag: String = DEFAULT_TAG, message: String) {
|
||||||
|
log(LogLevel.WARN, tag, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun error(tag: String = DEFAULT_TAG, message: String, throwable: Throwable? = null) {
|
||||||
|
log(LogLevel.ERROR, tag, message, throwable)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun debug(tag: String = DEFAULT_TAG, message: String) {
|
||||||
|
log(LogLevel.DEBUG, tag, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun log(level: LogLevel, tag: String, message: String, throwable: Throwable? = null) {
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
val entry = LogEntry(
|
||||||
|
id = nextId++,
|
||||||
|
timestamp = now,
|
||||||
|
formattedTime = timeFormat.format(Date(now)),
|
||||||
|
level = level,
|
||||||
|
tag = tag,
|
||||||
|
message = message,
|
||||||
|
throwable = throwable
|
||||||
|
)
|
||||||
|
|
||||||
|
try {
|
||||||
|
when (level) {
|
||||||
|
LogLevel.DEBUG -> Log.d(tag, message, throwable)
|
||||||
|
LogLevel.INFO -> Log.i(tag, message, throwable)
|
||||||
|
LogLevel.WARN -> Log.w(tag, message, throwable)
|
||||||
|
LogLevel.ERROR -> Log.e(tag, message, throwable)
|
||||||
|
}
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
println("[$level] [$tag] $message")
|
||||||
|
}
|
||||||
|
|
||||||
|
val updatedList = _logs.value.toMutableList().apply {
|
||||||
|
add(entry)
|
||||||
|
if (size > MAX_LOGS) {
|
||||||
|
removeAt(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_logs.value = updatedList
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clear() {
|
||||||
|
_logs.value = emptyList()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package com.example.netshareecohub.dhcp
|
||||||
|
|
||||||
|
import com.example.netshareecohub.data.logging.Logger
|
||||||
|
import java.io.BufferedReader
|
||||||
|
import java.io.File
|
||||||
|
import java.io.InputStreamReader
|
||||||
|
|
||||||
|
data class ArpEntry(
|
||||||
|
val ipAddress: String,
|
||||||
|
val macAddress: String,
|
||||||
|
val interfaceName: String
|
||||||
|
)
|
||||||
|
|
||||||
|
object ArpScanner {
|
||||||
|
private const val TAG = "ArpScanner"
|
||||||
|
|
||||||
|
fun scan(interfaceName: String): List<ArpEntry> {
|
||||||
|
val results = mutableListOf<ArpEntry>()
|
||||||
|
var process: Process? = null
|
||||||
|
var reader: BufferedReader? = null
|
||||||
|
|
||||||
|
try {
|
||||||
|
process = Runtime.getRuntime().exec(arrayOf("ip", "neigh", "show", "dev", interfaceName))
|
||||||
|
reader = BufferedReader(InputStreamReader(process.inputStream))
|
||||||
|
var line: String?
|
||||||
|
|
||||||
|
while (reader.readLine().also { line = it } != null) {
|
||||||
|
val parts = line!!.trim().split(Regex("\\s+"))
|
||||||
|
if (parts.size >= 5 && parts[1] == "lladdr") {
|
||||||
|
val ip = parts[0]
|
||||||
|
val mac = parts[2]
|
||||||
|
if (isValidIp(ip) && isValidMac(mac)) {
|
||||||
|
results.add(ArpEntry(ip, mac, interfaceName))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
process.waitFor()
|
||||||
|
|
||||||
|
if (results.isNotEmpty()) {
|
||||||
|
return results
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.warn(TAG, "ip neigh command failed: ${e.message}")
|
||||||
|
} finally {
|
||||||
|
try { reader?.close() } catch (_: Exception) {}
|
||||||
|
try { process?.destroy() } catch (_: Exception) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback to reading /proc/net/arp
|
||||||
|
try {
|
||||||
|
val arpFile = File("/proc/net/arp")
|
||||||
|
if (arpFile.exists() && arpFile.canRead()) {
|
||||||
|
val lines = arpFile.readLines()
|
||||||
|
for (i in 1 until lines.size) { // Skip header row
|
||||||
|
val parts = lines[i].trim().split(Regex("\\s+"))
|
||||||
|
if (parts.size >= 6) {
|
||||||
|
val ip = parts[0]
|
||||||
|
val flags = parts[2]
|
||||||
|
val mac = parts[3]
|
||||||
|
val iface = parts[5]
|
||||||
|
|
||||||
|
// Flag 0x0 usually means incomplete/unreachable, 0x2 means reachable
|
||||||
|
if (iface == interfaceName && flags != "0x0" && isValidIp(ip) && isValidMac(mac)) {
|
||||||
|
results.add(ArpEntry(ip, mac, interfaceName))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.warn(TAG, "Failed to read /proc/net/arp: ${e.message}")
|
||||||
|
}
|
||||||
|
|
||||||
|
return results
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isValidIp(ip: String): Boolean {
|
||||||
|
return ip.matches(Regex("^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4}$"))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isValidMac(mac: String): Boolean {
|
||||||
|
return mac.matches(Regex("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$")) && mac != "00:00:00:00:00:00"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.example.netshareecohub.dhcp
|
||||||
|
|
||||||
|
data class DhcpClientLease(
|
||||||
|
val macAddress: String,
|
||||||
|
val ipAddress: String,
|
||||||
|
val hostName: String? = null,
|
||||||
|
val leaseStartTime: Long,
|
||||||
|
val leaseExpirationTime: Long,
|
||||||
|
val status: LeaseStatus,
|
||||||
|
val lastSeenTime: Long,
|
||||||
|
val interfaceName: String? = null
|
||||||
|
) {
|
||||||
|
fun isExpired(currentTimeMs: Long = System.currentTimeMillis()): Boolean {
|
||||||
|
return currentTimeMs > leaseExpirationTime
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,307 @@
|
|||||||
|
package com.example.netshareecohub.dhcp
|
||||||
|
|
||||||
|
import com.example.netshareecohub.data.logging.Logger
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import java.net.InetAddress
|
||||||
|
|
||||||
|
class DhcpLeaseRepository(initialConfig: DhcpServerConfig = DhcpServerConfig()) {
|
||||||
|
|
||||||
|
private val tag = "DhcpLeaseRepository"
|
||||||
|
|
||||||
|
private val _config = MutableStateFlow(initialConfig)
|
||||||
|
val config: StateFlow<DhcpServerConfig> = _config.asStateFlow()
|
||||||
|
|
||||||
|
private val _leases = MutableStateFlow<List<DhcpClientLease>>(emptyList())
|
||||||
|
val leases: StateFlow<List<DhcpClientLease>> = _leases.asStateFlow()
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun updateConfig(newConfig: DhcpServerConfig) {
|
||||||
|
val old = _config.value
|
||||||
|
_config.value = newConfig
|
||||||
|
Logger.info(
|
||||||
|
tag,
|
||||||
|
"Updated DHCP Pool Config: Range [${newConfig.poolStartIp} - ${newConfig.poolEndIp}], Gateway: ${newConfig.routerIp}, Subnet: ${newConfig.subnetMask}, LeaseTime: ${newConfig.defaultLeaseTimeSeconds}s"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Validate existing active leases against new range
|
||||||
|
if (old.poolStartIp != newConfig.poolStartIp || old.poolEndIp != newConfig.poolEndIp) {
|
||||||
|
sweepAndInvalidateOutofRangeLeases(newConfig)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun getConfig(): DhcpServerConfig {
|
||||||
|
return _config.value
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun allocateOrFindOffer(
|
||||||
|
macAddress: String,
|
||||||
|
requestedIp: String?,
|
||||||
|
hostName: String?,
|
||||||
|
interfaceName: String? = null
|
||||||
|
): String? {
|
||||||
|
val normalizedMac = macAddress.uppercase()
|
||||||
|
val currentConfig = _config.value
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
val currentLeases = _leases.value.toMutableList()
|
||||||
|
|
||||||
|
// 1. Check if client already has an active or offered lease
|
||||||
|
val existingLease = currentLeases.find { it.macAddress.equals(normalizedMac, ignoreCase = true) }
|
||||||
|
if (existingLease != null && (existingLease.status == LeaseStatus.ONLINE || existingLease.status == LeaseStatus.OFFERED)) {
|
||||||
|
val updated = existingLease.copy(
|
||||||
|
hostName = hostName ?: existingLease.hostName,
|
||||||
|
lastSeenTime = now,
|
||||||
|
interfaceName = interfaceName ?: existingLease.interfaceName
|
||||||
|
)
|
||||||
|
updateLeaseInList(currentLeases, updated)
|
||||||
|
return existingLease.ipAddress
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Check if requestedIp is available and in range
|
||||||
|
val targetIp = if (!requestedIp.isNull_or_empty() && isIpInPool(requestedIp!!, currentConfig) && isIpFree(requestedIp, normalizedMac, currentLeases)) {
|
||||||
|
requestedIp
|
||||||
|
} else {
|
||||||
|
findNextFreeIp(normalizedMac, currentLeases, currentConfig)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (targetIp == null) {
|
||||||
|
Logger.warn(tag, "DHCP Pool exhausted! No available IP addresses for MAC: $normalizedMac")
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
val expiration = now + (currentConfig.defaultLeaseTimeSeconds * 1000L)
|
||||||
|
val offeredLease = DhcpClientLease(
|
||||||
|
macAddress = normalizedMac,
|
||||||
|
ipAddress = targetIp,
|
||||||
|
hostName = hostName,
|
||||||
|
leaseStartTime = now,
|
||||||
|
leaseExpirationTime = expiration,
|
||||||
|
status = LeaseStatus.OFFERED,
|
||||||
|
lastSeenTime = now,
|
||||||
|
interfaceName = interfaceName
|
||||||
|
)
|
||||||
|
|
||||||
|
updateLeaseInList(currentLeases, offeredLease)
|
||||||
|
_leases.value = currentLeases
|
||||||
|
return targetIp
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun confirmLease(
|
||||||
|
macAddress: String,
|
||||||
|
requestedIp: String,
|
||||||
|
hostName: String?,
|
||||||
|
interfaceName: String? = null
|
||||||
|
): DhcpClientLease? {
|
||||||
|
val normalizedMac = macAddress.uppercase()
|
||||||
|
val currentConfig = _config.value
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
val currentLeases = _leases.value.toMutableList()
|
||||||
|
|
||||||
|
if (!isIpInPool(requestedIp, currentConfig)) {
|
||||||
|
Logger.warn(tag, "Requested IP $requestedIp for MAC $normalizedMac is outside configured pool range")
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isIpFree(requestedIp, normalizedMac, currentLeases)) {
|
||||||
|
Logger.warn(tag, "Requested IP $requestedIp is already assigned to another MAC address")
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
val expiration = now + (currentConfig.defaultLeaseTimeSeconds * 1000L)
|
||||||
|
val activeLease = DhcpClientLease(
|
||||||
|
macAddress = normalizedMac,
|
||||||
|
ipAddress = requestedIp,
|
||||||
|
hostName = hostName,
|
||||||
|
leaseStartTime = now,
|
||||||
|
leaseExpirationTime = expiration,
|
||||||
|
status = LeaseStatus.ONLINE,
|
||||||
|
lastSeenTime = now,
|
||||||
|
interfaceName = interfaceName
|
||||||
|
)
|
||||||
|
|
||||||
|
updateLeaseInList(currentLeases, activeLease)
|
||||||
|
_leases.value = currentLeases
|
||||||
|
|
||||||
|
Logger.info(
|
||||||
|
tag,
|
||||||
|
"Confirmed lease for MAC $normalizedMac -> IP $requestedIp (Host: ${hostName ?: "unknown"}, Expires in ${currentConfig.defaultLeaseTimeSeconds}s)"
|
||||||
|
)
|
||||||
|
return activeLease
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun injectExternalLease(
|
||||||
|
macAddress: String,
|
||||||
|
ipAddress: String,
|
||||||
|
hostName: String?,
|
||||||
|
interfaceName: String?
|
||||||
|
) {
|
||||||
|
val normalizedMac = macAddress.uppercase()
|
||||||
|
val currentLeases = _leases.value.toMutableList()
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
|
||||||
|
// Use an effectively infinite lease time for system managed leases (e.g., 24 hours)
|
||||||
|
val expiration = now + (24 * 60 * 60 * 1000L)
|
||||||
|
|
||||||
|
val externalLease = DhcpClientLease(
|
||||||
|
macAddress = normalizedMac,
|
||||||
|
ipAddress = ipAddress,
|
||||||
|
hostName = hostName,
|
||||||
|
leaseStartTime = now,
|
||||||
|
leaseExpirationTime = expiration,
|
||||||
|
status = LeaseStatus.ONLINE,
|
||||||
|
lastSeenTime = now,
|
||||||
|
interfaceName = interfaceName
|
||||||
|
)
|
||||||
|
|
||||||
|
updateLeaseInList(currentLeases, externalLease)
|
||||||
|
_leases.value = currentLeases
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun releaseLease(macAddress: String): Boolean {
|
||||||
|
val normalizedMac = macAddress.uppercase()
|
||||||
|
val currentLeases = _leases.value.toMutableList()
|
||||||
|
val index = currentLeases.indexOfFirst { it.macAddress.equals(normalizedMac, ignoreCase = true) }
|
||||||
|
if (index >= 0) {
|
||||||
|
val lease = currentLeases[index]
|
||||||
|
currentLeases[index] = lease.copy(
|
||||||
|
status = LeaseStatus.RELEASED,
|
||||||
|
lastSeenTime = System.currentTimeMillis()
|
||||||
|
)
|
||||||
|
_leases.value = currentLeases
|
||||||
|
Logger.info(tag, "Released DHCP lease for MAC $normalizedMac (${lease.ipAddress})")
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun declineLease(macAddress: String, ipAddress: String) {
|
||||||
|
val normalizedMac = macAddress.uppercase()
|
||||||
|
val currentLeases = _leases.value.toMutableList()
|
||||||
|
val index = currentLeases.indexOfFirst {
|
||||||
|
it.macAddress.equals(normalizedMac, ignoreCase = true) || it.ipAddress == ipAddress
|
||||||
|
}
|
||||||
|
if (index >= 0) {
|
||||||
|
val lease = currentLeases[index]
|
||||||
|
currentLeases[index] = lease.copy(
|
||||||
|
status = LeaseStatus.EXPIRED,
|
||||||
|
lastSeenTime = System.currentTimeMillis()
|
||||||
|
)
|
||||||
|
_leases.value = currentLeases
|
||||||
|
Logger.warn(tag, "Declined IP $ipAddress for MAC $normalizedMac; marked as EXPIRED")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun sweepExpiredLeases(currentTimeMs: Long = System.currentTimeMillis()) {
|
||||||
|
val currentLeases = _leases.value.toMutableList()
|
||||||
|
var changed = false
|
||||||
|
for (i in currentLeases.indices) {
|
||||||
|
val lease = currentLeases[i]
|
||||||
|
if ((lease.status == LeaseStatus.ONLINE || lease.status == LeaseStatus.OFFERED) && lease.isExpired(currentTimeMs)) {
|
||||||
|
currentLeases[i] = lease.copy(status = LeaseStatus.EXPIRED)
|
||||||
|
changed = true
|
||||||
|
Logger.info(tag, "Lease expired for client ${lease.macAddress} (${lease.ipAddress})")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (changed) {
|
||||||
|
_leases.value = currentLeases
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateLeaseInList(list: MutableList<DhcpClientLease>, newLease: DhcpClientLease) {
|
||||||
|
val index = list.indexOfFirst { it.macAddress.equals(newLease.macAddress, ignoreCase = true) }
|
||||||
|
if (index >= 0) {
|
||||||
|
list[index] = newLease
|
||||||
|
} else {
|
||||||
|
list.add(newLease)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isIpInPool(ip: String, config: DhcpServerConfig): Boolean {
|
||||||
|
val ipNum = ipToLong(ip)
|
||||||
|
val startNum = ipToLong(config.poolStartIp)
|
||||||
|
val endNum = ipToLong(config.poolEndIp)
|
||||||
|
return ipNum in startNum..endNum
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isIpFree(ip: String, requestMac: String, currentLeases: List<DhcpClientLease>): Boolean {
|
||||||
|
val lease = currentLeases.find { it.ipAddress == ip } ?: return true
|
||||||
|
if (lease.status == LeaseStatus.EXPIRED || lease.status == LeaseStatus.RELEASED) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return lease.macAddress.equals(requestMac, ignoreCase = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun findNextFreeIp(
|
||||||
|
requestMac: String,
|
||||||
|
currentLeases: List<DhcpClientLease>,
|
||||||
|
config: DhcpServerConfig
|
||||||
|
): String? {
|
||||||
|
val startNum = ipToLong(config.poolStartIp)
|
||||||
|
val endNum = ipToLong(config.poolEndIp)
|
||||||
|
|
||||||
|
for (curr in startNum..endNum) {
|
||||||
|
val candidateIp = longToIp(curr)
|
||||||
|
if (candidateIp == config.serverIp || candidateIp == config.routerIp) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (isIpFree(candidateIp, requestMac, currentLeases)) {
|
||||||
|
return candidateIp
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sweepAndInvalidateOutofRangeLeases(config: DhcpServerConfig) {
|
||||||
|
val currentLeases = _leases.value.toMutableList()
|
||||||
|
var changed = false
|
||||||
|
for (i in currentLeases.indices) {
|
||||||
|
val lease = currentLeases[i]
|
||||||
|
if (!isIpInPool(lease.ipAddress, config) && lease.status == LeaseStatus.ONLINE) {
|
||||||
|
currentLeases[i] = lease.copy(status = LeaseStatus.EXPIRED)
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (changed) {
|
||||||
|
_leases.value = currentLeases
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun String?.isNull_or_empty(): Boolean {
|
||||||
|
return this == null || this.trim().isEmpty() || this == "0.0.0.0"
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun ipToLong(ip: String): Long {
|
||||||
|
return try {
|
||||||
|
val bytes = InetAddress.getByName(ip).address
|
||||||
|
var result = 0L
|
||||||
|
for (b in bytes) {
|
||||||
|
result = (result shl 8) or (b.toInt() and 0xFF).toLong()
|
||||||
|
}
|
||||||
|
result
|
||||||
|
} catch (e: Exception) {
|
||||||
|
0L
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun longToIp(ipLong: Long): String {
|
||||||
|
return try {
|
||||||
|
val b1 = (ipLong shr 24 and 0xFF).toInt()
|
||||||
|
val b2 = (ipLong shr 16 and 0xFF).toInt()
|
||||||
|
val b3 = (ipLong shr 8 and 0xFF).toInt()
|
||||||
|
val b4 = (ipLong and 0xFF).toInt()
|
||||||
|
"$b1.$b2.$b3.$b4"
|
||||||
|
} catch (e: Exception) {
|
||||||
|
"0.0.0.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.example.netshareecohub.dhcp
|
||||||
|
|
||||||
|
enum class DhcpMessageType(val code: Byte) {
|
||||||
|
UNKNOWN(0),
|
||||||
|
DISCOVER(1),
|
||||||
|
OFFER(2),
|
||||||
|
REQUEST(3),
|
||||||
|
DECLINE(4),
|
||||||
|
ACK(5),
|
||||||
|
NAK(6),
|
||||||
|
RELEASE(7),
|
||||||
|
INFORM(8);
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun fromCode(code: Byte): DhcpMessageType {
|
||||||
|
return entries.find { it.code == code } ?: UNKNOWN
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package com.example.netshareecohub.dhcp
|
||||||
|
|
||||||
|
data class DhcpOption(
|
||||||
|
val code: Byte,
|
||||||
|
val length: Int,
|
||||||
|
val value: ByteArray
|
||||||
|
) {
|
||||||
|
override fun equals(other: Any?): Boolean {
|
||||||
|
if (this === other) return true
|
||||||
|
if (javaClass != other?.javaClass) return false
|
||||||
|
other as DhcpOption
|
||||||
|
if (code != other.code) return false
|
||||||
|
if (length != other.length) return false
|
||||||
|
if (!value.contentEquals(other.value)) return false
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun hashCode(): Int {
|
||||||
|
var result = code.toInt()
|
||||||
|
result = 31 * result + length
|
||||||
|
result = 31 * result + value.contentHashCode()
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.example.netshareecohub.dhcp
|
||||||
|
|
||||||
|
object DhcpOptionCode {
|
||||||
|
const val PAD: Byte = 0
|
||||||
|
const val SUBNET_MASK: Byte = 1
|
||||||
|
const val ROUTER: Byte = 3
|
||||||
|
const val DNS_SERVER: Byte = 6
|
||||||
|
const val HOST_NAME: Byte = 12
|
||||||
|
const val REQUESTED_IP: Byte = 50
|
||||||
|
const val LEASE_TIME: Byte = 51
|
||||||
|
const val MESSAGE_TYPE: Byte = 53
|
||||||
|
const val SERVER_ID: Byte = 54
|
||||||
|
const val PARAMETER_REQUEST_LIST: Byte = 55
|
||||||
|
const val CLIENT_ID: Byte = 61
|
||||||
|
const val END: Byte = 255.toByte()
|
||||||
|
}
|
||||||
285
app/src/main/java/com/example/netshareecohub/dhcp/DhcpPacket.kt
Normal file
@@ -0,0 +1,285 @@
|
|||||||
|
package com.example.netshareecohub.dhcp
|
||||||
|
|
||||||
|
import java.net.InetAddress
|
||||||
|
import java.nio.ByteBuffer
|
||||||
|
import java.nio.ByteOrder
|
||||||
|
|
||||||
|
data class DhcpPacket(
|
||||||
|
val op: Byte = 1, // 1 = BOOTREQUEST, 2 = BOOTREPLY
|
||||||
|
val htype: Byte = 1, // 1 = Ethernet 10Mb
|
||||||
|
val hlen: Byte = 6, // Hardware address length (6 for MAC)
|
||||||
|
val hops: Byte = 0,
|
||||||
|
val xid: Int = 0,
|
||||||
|
val secs: Short = 0,
|
||||||
|
val flags: Short = 0,
|
||||||
|
val ciaddr: String = "0.0.0.0",
|
||||||
|
val yiaddr: String = "0.0.0.0",
|
||||||
|
val siaddr: String = "0.0.0.0",
|
||||||
|
val giaddr: String = "0.0.0.0",
|
||||||
|
val chaddr: ByteArray = ByteArray(16),
|
||||||
|
val sname: String = "",
|
||||||
|
val file: String = "",
|
||||||
|
val options: List<DhcpOption> = emptyList()
|
||||||
|
) {
|
||||||
|
|
||||||
|
fun getOption(code: Byte): DhcpOption? {
|
||||||
|
return options.find { it.code == code }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getMessageType(): DhcpMessageType {
|
||||||
|
val opt = getOption(DhcpOptionCode.MESSAGE_TYPE) ?: return DhcpMessageType.UNKNOWN
|
||||||
|
if (opt.value.isNotEmpty()) {
|
||||||
|
return DhcpMessageType.fromCode(opt.value[0])
|
||||||
|
}
|
||||||
|
return DhcpMessageType.UNKNOWN
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getRequestedIp(): String? {
|
||||||
|
val opt = getOption(DhcpOptionCode.REQUESTED_IP) ?: return null
|
||||||
|
if (opt.value.size >= 4) {
|
||||||
|
return bytesToIp(opt.value, 0)
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getServerId(): String? {
|
||||||
|
val opt = getOption(DhcpOptionCode.SERVER_ID) ?: return null
|
||||||
|
if (opt.value.size >= 4) {
|
||||||
|
return bytesToIp(opt.value, 0)
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getHostName(): String? {
|
||||||
|
val opt = getOption(DhcpOptionCode.HOST_NAME) ?: return null
|
||||||
|
return String(opt.value, Charsets.UTF_8).trim { it <= ' ' || it == '\u0000' }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getClientMac(): String {
|
||||||
|
val len = hlen.toInt().coerceIn(1, 16)
|
||||||
|
return macToString(chaddr, len)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun encode(): ByteArray {
|
||||||
|
val buffer = ByteBuffer.allocate(1024).apply {
|
||||||
|
order(ByteOrder.BIG_ENDIAN)
|
||||||
|
put(op)
|
||||||
|
put(htype)
|
||||||
|
put(hlen)
|
||||||
|
put(hops)
|
||||||
|
putInt(xid)
|
||||||
|
putShort(secs)
|
||||||
|
putShort(flags)
|
||||||
|
put(ipToBytes(ciaddr))
|
||||||
|
put(ipToBytes(yiaddr))
|
||||||
|
put(ipToBytes(siaddr))
|
||||||
|
put(ipToBytes(giaddr))
|
||||||
|
|
||||||
|
// chaddr 16 bytes
|
||||||
|
val chaddrPadded = ByteArray(16)
|
||||||
|
System.arraycopy(chaddr, 0, chaddrPadded, 0, chaddr.size.coerceAtMost(16))
|
||||||
|
put(chaddrPadded)
|
||||||
|
|
||||||
|
// sname 64 bytes
|
||||||
|
val snameBytes = ByteArray(64)
|
||||||
|
val snameRaw = sname.toByteArray(Charsets.UTF_8)
|
||||||
|
System.arraycopy(snameRaw, 0, snameBytes, 0, snameRaw.size.coerceAtMost(64))
|
||||||
|
put(snameBytes)
|
||||||
|
|
||||||
|
// file 128 bytes
|
||||||
|
val fileBytes = ByteArray(128)
|
||||||
|
val fileRaw = file.toByteArray(Charsets.UTF_8)
|
||||||
|
System.arraycopy(fileRaw, 0, fileBytes, 0, fileRaw.size.coerceAtMost(128))
|
||||||
|
put(fileBytes)
|
||||||
|
|
||||||
|
// Magic Cookie: 0x63, 0x82, 0x53, 0x63
|
||||||
|
put(MAGIC_COOKIE)
|
||||||
|
|
||||||
|
// Options
|
||||||
|
for (opt in options) {
|
||||||
|
if (opt.code == DhcpOptionCode.PAD || opt.code == DhcpOptionCode.END) continue
|
||||||
|
put(opt.code)
|
||||||
|
put(opt.value.size.toByte())
|
||||||
|
put(opt.value)
|
||||||
|
}
|
||||||
|
put(DhcpOptionCode.END)
|
||||||
|
}
|
||||||
|
|
||||||
|
val result = ByteArray(buffer.position())
|
||||||
|
buffer.flip()
|
||||||
|
buffer.get(result)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun equals(other: Any?): Boolean {
|
||||||
|
if (this === other) return true
|
||||||
|
if (javaClass != other?.javaClass) return false
|
||||||
|
other as DhcpPacket
|
||||||
|
if (op != other.op) return false
|
||||||
|
if (htype != other.htype) return false
|
||||||
|
if (hlen != other.hlen) return false
|
||||||
|
if (hops != other.hops) return false
|
||||||
|
if (xid != other.xid) return false
|
||||||
|
if (secs != other.secs) return false
|
||||||
|
if (flags != other.flags) return false
|
||||||
|
if (ciaddr != other.ciaddr) return false
|
||||||
|
if (yiaddr != other.yiaddr) return false
|
||||||
|
if (siaddr != other.siaddr) return false
|
||||||
|
if (giaddr != other.giaddr) return false
|
||||||
|
if (!chaddr.contentEquals(other.chaddr)) return false
|
||||||
|
if (sname != other.sname) return false
|
||||||
|
if (file != other.file) return false
|
||||||
|
if (options != other.options) return false
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun hashCode(): Int {
|
||||||
|
var result = op.toInt()
|
||||||
|
result = 31 * result + htype
|
||||||
|
result = 31 * result + hlen
|
||||||
|
result = 31 * result + hops
|
||||||
|
result = 31 * result + xid
|
||||||
|
result = 31 * result + secs
|
||||||
|
result = 31 * result + flags
|
||||||
|
result = 31 * result + ciaddr.hashCode()
|
||||||
|
result = 31 * result + yiaddr.hashCode()
|
||||||
|
result = 31 * result + siaddr.hashCode()
|
||||||
|
result = 31 * result + giaddr.hashCode()
|
||||||
|
result = 31 * result + chaddr.contentHashCode()
|
||||||
|
result = 31 * result + sname.hashCode()
|
||||||
|
result = 31 * result + file.hashCode()
|
||||||
|
result = 31 * result + options.hashCode()
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val MAGIC_COOKIE = byteArrayOf(0x63.toByte(), 0x82.toByte(), 0x53.toByte(), 0x63.toByte())
|
||||||
|
|
||||||
|
fun decode(data: ByteArray, length: Int): DhcpPacket? {
|
||||||
|
if (length < 240) return null // Minimum packet size with magic cookie
|
||||||
|
|
||||||
|
val buffer = ByteBuffer.wrap(data, 0, length).apply {
|
||||||
|
order(ByteOrder.BIG_ENDIAN)
|
||||||
|
}
|
||||||
|
|
||||||
|
val op = buffer.get()
|
||||||
|
val htype = buffer.get()
|
||||||
|
val hlen = buffer.get()
|
||||||
|
val hops = buffer.get()
|
||||||
|
val xid = buffer.int
|
||||||
|
val secs = buffer.short
|
||||||
|
val flags = buffer.short
|
||||||
|
|
||||||
|
val ciaddrBytes = ByteArray(4)
|
||||||
|
buffer.get(ciaddrBytes)
|
||||||
|
val ciaddr = bytesToIp(ciaddrBytes, 0)
|
||||||
|
|
||||||
|
val yiaddrBytes = ByteArray(4)
|
||||||
|
buffer.get(yiaddrBytes)
|
||||||
|
val yiaddr = bytesToIp(yiaddrBytes, 0)
|
||||||
|
|
||||||
|
val siaddrBytes = ByteArray(4)
|
||||||
|
buffer.get(siaddrBytes)
|
||||||
|
val siaddr = bytesToIp(siaddrBytes, 0)
|
||||||
|
|
||||||
|
val giaddrBytes = ByteArray(4)
|
||||||
|
buffer.get(giaddrBytes)
|
||||||
|
val giaddr = bytesToIp(giaddrBytes, 0)
|
||||||
|
|
||||||
|
val chaddr = ByteArray(16)
|
||||||
|
buffer.get(chaddr)
|
||||||
|
|
||||||
|
val snameBytes = ByteArray(64)
|
||||||
|
buffer.get(snameBytes)
|
||||||
|
val sname = String(snameBytes, Charsets.UTF_8).trim { it <= ' ' || it == '\u0000' }
|
||||||
|
|
||||||
|
val fileBytes = ByteArray(128)
|
||||||
|
buffer.get(fileBytes)
|
||||||
|
val file = String(fileBytes, Charsets.UTF_8).trim { it <= ' ' || it == '\u0000' }
|
||||||
|
|
||||||
|
val cookie = ByteArray(4)
|
||||||
|
buffer.get(cookie)
|
||||||
|
if (!cookie.contentEquals(MAGIC_COOKIE)) {
|
||||||
|
return null // Invalid DHCP magic cookie
|
||||||
|
}
|
||||||
|
|
||||||
|
// Options parsing
|
||||||
|
val options = mutableListOf<DhcpOption>()
|
||||||
|
while (buffer.hasRemaining()) {
|
||||||
|
val code = buffer.get()
|
||||||
|
if (code == DhcpOptionCode.PAD) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (code == DhcpOptionCode.END) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if (!buffer.hasRemaining()) break
|
||||||
|
val optLen = buffer.get().toInt() and 0xFF
|
||||||
|
if (buffer.remaining() < optLen) break
|
||||||
|
val optVal = ByteArray(optLen)
|
||||||
|
buffer.get(optVal)
|
||||||
|
options.add(DhcpOption(code, optLen, optVal))
|
||||||
|
}
|
||||||
|
|
||||||
|
return DhcpPacket(
|
||||||
|
op = op,
|
||||||
|
htype = htype,
|
||||||
|
hlen = hlen,
|
||||||
|
hops = hops,
|
||||||
|
xid = xid,
|
||||||
|
secs = secs,
|
||||||
|
flags = flags,
|
||||||
|
ciaddr = ciaddr,
|
||||||
|
yiaddr = yiaddr,
|
||||||
|
siaddr = siaddr,
|
||||||
|
giaddr = giaddr,
|
||||||
|
chaddr = chaddr,
|
||||||
|
sname = sname,
|
||||||
|
file = file,
|
||||||
|
options = options
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun ipToBytes(ipStr: String): ByteArray {
|
||||||
|
return try {
|
||||||
|
InetAddress.getByName(ipStr).address
|
||||||
|
} catch (e: Exception) {
|
||||||
|
ByteArray(4)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun bytesToIp(bytes: ByteArray, offset: Int): String {
|
||||||
|
return try {
|
||||||
|
val arr = bytes.copyOfRange(offset, offset + 4)
|
||||||
|
InetAddress.getByAddress(arr).hostAddress ?: "0.0.0.0"
|
||||||
|
} catch (e: Exception) {
|
||||||
|
"0.0.0.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun macToString(bytes: ByteArray, length: Int): String {
|
||||||
|
if (length <= 0) return "00:00:00:00:00:00"
|
||||||
|
val validLen = length.coerceAtMost(bytes.size)
|
||||||
|
return bytes.copyOfRange(0, validLen).joinToString(":") {
|
||||||
|
String.format("%02X", it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun macToBytes(macStr: String): ByteArray {
|
||||||
|
return try {
|
||||||
|
val parts = macStr.split(":", "-")
|
||||||
|
val bytes = ByteArray(parts.size)
|
||||||
|
for (i in parts.indices) {
|
||||||
|
bytes[i] = parts[i].toInt(16).toByte()
|
||||||
|
}
|
||||||
|
bytes
|
||||||
|
} catch (e: Exception) {
|
||||||
|
ByteArray(6)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun intToBytes(value: Int): ByteArray {
|
||||||
|
return ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(value).array()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
589
app/src/main/java/com/example/netshareecohub/dhcp/DhcpServer.kt
Normal file
@@ -0,0 +1,589 @@
|
|||||||
|
package com.example.netshareecohub.dhcp
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
import com.example.netshareecohub.data.logging.Logger
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.isActive
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import java.net.DatagramPacket
|
||||||
|
import java.net.DatagramSocket
|
||||||
|
import java.net.InetAddress
|
||||||
|
import java.net.SocketException
|
||||||
|
|
||||||
|
class DhcpServer(
|
||||||
|
val leaseRepository: DhcpLeaseRepository = DhcpLeaseRepository(),
|
||||||
|
private var context: Context? = null
|
||||||
|
) {
|
||||||
|
|
||||||
|
private val tag = "DhcpServer"
|
||||||
|
private val scope = CoroutineScope(Dispatchers.IO + Job())
|
||||||
|
|
||||||
|
private var socket: DatagramSocket? = null
|
||||||
|
private var serverJob: Job? = null
|
||||||
|
private var sweepJob: Job? = null
|
||||||
|
|
||||||
|
private val _status = MutableStateFlow(DhcpServerStatus())
|
||||||
|
val status: StateFlow<DhcpServerStatus> = _status.asStateFlow()
|
||||||
|
|
||||||
|
private var totalReceived = 0L
|
||||||
|
private var totalSent = 0L
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun start(
|
||||||
|
port: Int = leaseRepository.getConfig().port,
|
||||||
|
bindAddressStr: String? = null,
|
||||||
|
interfaceName: String? = null,
|
||||||
|
context: Context? = null
|
||||||
|
) {
|
||||||
|
if (context != null) {
|
||||||
|
this.context = context
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_status.value.state == ServerState.RUNNING) {
|
||||||
|
Logger.info(tag, "DHCP Server is already running")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_status.value = DhcpServerStatus(
|
||||||
|
state = ServerState.STARTING,
|
||||||
|
boundPort = port,
|
||||||
|
boundAddress = bindAddressStr,
|
||||||
|
interfaceName = interfaceName
|
||||||
|
)
|
||||||
|
|
||||||
|
serverJob = scope.launch {
|
||||||
|
runServer(port, bindAddressStr, interfaceName)
|
||||||
|
}
|
||||||
|
|
||||||
|
sweepJob = scope.launch {
|
||||||
|
while (isActive) {
|
||||||
|
delay(10000)
|
||||||
|
leaseRepository.sweepExpiredLeases()
|
||||||
|
updateActiveLeaseCount()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun stop() {
|
||||||
|
serverJob?.cancel()
|
||||||
|
serverJob = null
|
||||||
|
|
||||||
|
sweepJob?.cancel()
|
||||||
|
sweepJob = null
|
||||||
|
|
||||||
|
try {
|
||||||
|
socket?.close()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.warn(tag, "Error closing DHCP server socket: ${e.message}")
|
||||||
|
}
|
||||||
|
socket = null
|
||||||
|
|
||||||
|
_status.value = _status.value.copy(
|
||||||
|
state = ServerState.STOPPED,
|
||||||
|
errorMessage = null
|
||||||
|
)
|
||||||
|
Logger.info(tag, "DHCP Server stopped")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun updateConfig(config: DhcpServerConfig) {
|
||||||
|
leaseRepository.updateConfig(config)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun runServer(port: Int, bindAddressStr: String?, interfaceName: String?) {
|
||||||
|
var boundSocket: DatagramSocket? = null
|
||||||
|
var actualPort = port
|
||||||
|
var port67Restricted = false
|
||||||
|
|
||||||
|
try {
|
||||||
|
val bindAddress = if (!bindAddressStr.isNull_or_empty()) {
|
||||||
|
InetAddress.getByName(bindAddressStr)
|
||||||
|
} else {
|
||||||
|
InetAddress.getByName("0.0.0.0")
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
boundSocket = DatagramSocket(actualPort, bindAddress)
|
||||||
|
Logger.info(tag, "Successfully bound DHCP socket to UDP port $actualPort on ${bindAddressStr ?: "0.0.0.0"}")
|
||||||
|
} catch (e: SocketException) {
|
||||||
|
val isEacces = e.message?.contains("Permission denied", ignoreCase = true) == true ||
|
||||||
|
e.message?.contains("EACCES", ignoreCase = true) == true
|
||||||
|
if (isEacces || actualPort == 67) {
|
||||||
|
port67Restricted = true
|
||||||
|
Logger.warn(
|
||||||
|
tag,
|
||||||
|
"Privileged port 67 binding failed (${e.message}). Non-root Android kernel restricts UDP port 67 binding. Falling back to UDP port 6700..."
|
||||||
|
)
|
||||||
|
Logger.warn(
|
||||||
|
tag,
|
||||||
|
"NON-ROOT PHYSICAL DEVICE ADVISORY: Standard DHCP clients require port 67. Please enable System Ethernet Tethering in Android Settings or use Root mode for IPTables port 67 redirection."
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Logger.warn(
|
||||||
|
tag,
|
||||||
|
"Failed to bind to primary port $actualPort: ${e.message}. Attempting fallback port 6700..."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
actualPort = 6700
|
||||||
|
boundSocket = DatagramSocket(actualPort, bindAddress)
|
||||||
|
}
|
||||||
|
|
||||||
|
boundSocket.broadcast = true
|
||||||
|
|
||||||
|
// Explicitly bind socket descriptor to the active Ethernet Network interface via SO_BINDTODEVICE
|
||||||
|
bindSocketToInterface(boundSocket, interfaceName)
|
||||||
|
|
||||||
|
socket = boundSocket
|
||||||
|
|
||||||
|
val statusErrorMsg = if (port67Restricted) {
|
||||||
|
"Port 67 restricted (EACCES) - server running on fallback port 6700"
|
||||||
|
} else null
|
||||||
|
|
||||||
|
_status.value = DhcpServerStatus(
|
||||||
|
state = ServerState.RUNNING,
|
||||||
|
boundPort = actualPort,
|
||||||
|
boundAddress = bindAddressStr ?: "0.0.0.0",
|
||||||
|
interfaceName = interfaceName,
|
||||||
|
errorMessage = statusErrorMsg
|
||||||
|
)
|
||||||
|
|
||||||
|
Logger.info(
|
||||||
|
tag,
|
||||||
|
"DHCP Server running on UDP ${bindAddressStr ?: "0.0.0.0"}:$actualPort (Interface: ${interfaceName ?: "all"})"
|
||||||
|
)
|
||||||
|
|
||||||
|
val receiveBuffer = ByteArray(1500)
|
||||||
|
|
||||||
|
while (scope.isActive && !boundSocket.isClosed) {
|
||||||
|
val packet = DatagramPacket(receiveBuffer, receiveBuffer.size)
|
||||||
|
try {
|
||||||
|
boundSocket.receive(packet)
|
||||||
|
totalReceived++
|
||||||
|
updateStatusCounts()
|
||||||
|
|
||||||
|
val dhcpPacket = DhcpPacket.decode(packet.data, packet.length)
|
||||||
|
if (dhcpPacket != null) {
|
||||||
|
handleDhcpPacket(dhcpPacket, interfaceName)
|
||||||
|
} else {
|
||||||
|
Logger.debug(tag, "Ignored invalid/non-DHCP packet received on port $actualPort")
|
||||||
|
}
|
||||||
|
} catch (e: SocketException) {
|
||||||
|
if (scope.isActive && !boundSocket.isClosed) {
|
||||||
|
Logger.error(tag, "Socket exception during receive", e)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.error(tag, "Error processing incoming DHCP packet", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.error(tag, "DHCP Server failed to start or error occurred: ${e.message}", e)
|
||||||
|
_status.value = _status.value.copy(
|
||||||
|
state = ServerState.ERROR,
|
||||||
|
errorMessage = e.message ?: "Failed to initialize server socket"
|
||||||
|
)
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
boundSocket?.close()
|
||||||
|
} catch (_: Exception) {
|
||||||
|
}
|
||||||
|
if (_status.value.state == ServerState.RUNNING) {
|
||||||
|
_status.value = _status.value.copy(state = ServerState.STOPPED)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun bindSocketToInterface(socket: DatagramSocket, interfaceName: String?) {
|
||||||
|
if (interfaceName.isNullOrEmpty()) return
|
||||||
|
|
||||||
|
val currentContext = context ?: return
|
||||||
|
try {
|
||||||
|
val cm = currentContext.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
|
||||||
|
if (cm != null) {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
val targetNetwork = cm.allNetworks.find { net ->
|
||||||
|
val lp = cm.getLinkProperties(net)
|
||||||
|
lp?.interfaceName == interfaceName
|
||||||
|
}
|
||||||
|
|
||||||
|
if (targetNetwork != null) {
|
||||||
|
targetNetwork.bindSocket(socket)
|
||||||
|
Logger.info(
|
||||||
|
tag,
|
||||||
|
"SO_BINDTODEVICE success: Bound DHCP socket to Network interface '$interfaceName' ($targetNetwork) via Network.bindSocket()"
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Logger.warn(
|
||||||
|
tag,
|
||||||
|
"Network object for interface '$interfaceName' not found in ConnectivityManager active networks list. Socket using system default routing."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.error(tag, "Error binding DHCP socket to network interface '$interfaceName': ${e.message}", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleDhcpPacket(packet: DhcpPacket, interfaceName: String?) {
|
||||||
|
val clientMac = packet.getClientMac()
|
||||||
|
val msgType = packet.getMessageType()
|
||||||
|
val hostName = packet.getHostName()
|
||||||
|
|
||||||
|
when (msgType) {
|
||||||
|
DhcpMessageType.DISCOVER -> {
|
||||||
|
val requestedIp = packet.getRequestedIp()
|
||||||
|
Logger.info(
|
||||||
|
tag,
|
||||||
|
"DHCPDISCOVER received from $clientMac (Host: ${hostName ?: "unknown"}, Requested IP: ${requestedIp ?: "none"})"
|
||||||
|
)
|
||||||
|
|
||||||
|
val offeredIp = leaseRepository.allocateOrFindOffer(
|
||||||
|
macAddress = clientMac,
|
||||||
|
requestedIp = requestedIp,
|
||||||
|
hostName = hostName,
|
||||||
|
interfaceName = interfaceName
|
||||||
|
)
|
||||||
|
|
||||||
|
if (offeredIp != null) {
|
||||||
|
sendOffer(packet, clientMac, offeredIp)
|
||||||
|
} else {
|
||||||
|
Logger.warn(tag, "Cannot send DHCPOFFER: No IP available for $clientMac")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
DhcpMessageType.REQUEST -> {
|
||||||
|
val requestedIp = packet.getRequestedIp() ?: packet.ciaddr
|
||||||
|
val serverId = packet.getServerId()
|
||||||
|
val config = leaseRepository.getConfig()
|
||||||
|
|
||||||
|
Logger.info(
|
||||||
|
tag,
|
||||||
|
"DHCPREQUEST received from $clientMac for IP $requestedIp (Server ID: ${serverId ?: "none"})"
|
||||||
|
)
|
||||||
|
|
||||||
|
// If server ID option present and does not match server IP, client selected another server
|
||||||
|
if (serverId != null && serverId != config.serverIp && serverId != "0.0.0.0") {
|
||||||
|
Logger.info(
|
||||||
|
tag,
|
||||||
|
"Client $clientMac selected another DHCP server ($serverId); declining request"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
val lease = leaseRepository.confirmLease(
|
||||||
|
macAddress = clientMac,
|
||||||
|
requestedIp = requestedIp,
|
||||||
|
hostName = hostName,
|
||||||
|
interfaceName = interfaceName
|
||||||
|
)
|
||||||
|
|
||||||
|
if (lease != null) {
|
||||||
|
sendAck(packet, clientMac, lease.ipAddress)
|
||||||
|
} else {
|
||||||
|
sendNak(packet, clientMac)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
DhcpMessageType.RELEASE -> {
|
||||||
|
Logger.info(tag, "DHCPRELEASE received from $clientMac")
|
||||||
|
leaseRepository.releaseLease(clientMac)
|
||||||
|
updateActiveLeaseCount()
|
||||||
|
}
|
||||||
|
|
||||||
|
DhcpMessageType.DECLINE -> {
|
||||||
|
val declinedIp = packet.getRequestedIp() ?: packet.ciaddr
|
||||||
|
Logger.warn(tag, "DHCPDECLINE received from $clientMac for IP $declinedIp")
|
||||||
|
leaseRepository.declineLease(clientMac, declinedIp)
|
||||||
|
updateActiveLeaseCount()
|
||||||
|
}
|
||||||
|
|
||||||
|
DhcpMessageType.INFORM -> {
|
||||||
|
Logger.info(tag, "DHCPINFORM received from $clientMac")
|
||||||
|
sendAck(packet, clientMac, packet.ciaddr)
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
Logger.debug(tag, "Unhandled DHCP message type: $msgType from $clientMac")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun processRawDhcpPacket(data: ByteArray, length: Int, interfaceName: String? = null): ByteArray? {
|
||||||
|
val request = DhcpPacket.decode(data, length) ?: return null
|
||||||
|
val clientMac = request.getClientMac()
|
||||||
|
val msgType = request.getMessageType()
|
||||||
|
val hostName = request.getHostName()
|
||||||
|
val config = leaseRepository.getConfig()
|
||||||
|
|
||||||
|
return when (msgType) {
|
||||||
|
DhcpMessageType.DISCOVER -> {
|
||||||
|
val requestedIp = request.getRequestedIp()
|
||||||
|
val offeredIp = leaseRepository.allocateOrFindOffer(
|
||||||
|
macAddress = clientMac,
|
||||||
|
requestedIp = requestedIp,
|
||||||
|
hostName = hostName,
|
||||||
|
interfaceName = interfaceName
|
||||||
|
) ?: return null
|
||||||
|
|
||||||
|
val options = buildServerOptions(DhcpMessageType.OFFER, config)
|
||||||
|
val response = DhcpPacket(
|
||||||
|
op = 2,
|
||||||
|
htype = request.htype,
|
||||||
|
hlen = request.hlen,
|
||||||
|
xid = request.xid,
|
||||||
|
flags = request.flags,
|
||||||
|
ciaddr = "0.0.0.0",
|
||||||
|
yiaddr = offeredIp,
|
||||||
|
siaddr = config.serverIp,
|
||||||
|
chaddr = request.chaddr,
|
||||||
|
options = options
|
||||||
|
)
|
||||||
|
Logger.info(tag, "Non-Root TUN DHCPOFFER generated: $offeredIp for $clientMac (Host: ${hostName ?: "unknown"})")
|
||||||
|
updateActiveLeaseCount()
|
||||||
|
response.encode()
|
||||||
|
}
|
||||||
|
|
||||||
|
DhcpMessageType.REQUEST -> {
|
||||||
|
val requestedIp = request.getRequestedIp() ?: request.ciaddr
|
||||||
|
val lease = leaseRepository.confirmLease(
|
||||||
|
macAddress = clientMac,
|
||||||
|
requestedIp = requestedIp,
|
||||||
|
hostName = hostName,
|
||||||
|
interfaceName = interfaceName
|
||||||
|
)
|
||||||
|
|
||||||
|
val responseMsgType = if (lease != null) DhcpMessageType.ACK else DhcpMessageType.NAK
|
||||||
|
val yiaddr = lease?.ipAddress ?: "0.0.0.0"
|
||||||
|
val options = buildServerOptions(responseMsgType, config)
|
||||||
|
|
||||||
|
val response = DhcpPacket(
|
||||||
|
op = 2,
|
||||||
|
htype = request.htype,
|
||||||
|
hlen = request.hlen,
|
||||||
|
xid = request.xid,
|
||||||
|
flags = request.flags,
|
||||||
|
ciaddr = request.ciaddr,
|
||||||
|
yiaddr = yiaddr,
|
||||||
|
siaddr = config.serverIp,
|
||||||
|
chaddr = request.chaddr,
|
||||||
|
options = options
|
||||||
|
)
|
||||||
|
Logger.info(tag, "Non-Root TUN DHCPACK/NAK generated: $yiaddr for $clientMac (Host: ${hostName ?: "unknown"})")
|
||||||
|
updateActiveLeaseCount()
|
||||||
|
response.encode()
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sendOffer(request: DhcpPacket, clientMac: String, offeredIp: String) {
|
||||||
|
val config = leaseRepository.getConfig()
|
||||||
|
val options = buildServerOptions(
|
||||||
|
msgType = DhcpMessageType.OFFER,
|
||||||
|
config = config
|
||||||
|
)
|
||||||
|
|
||||||
|
val response = DhcpPacket(
|
||||||
|
op = 2, // BOOTREPLY
|
||||||
|
htype = request.htype,
|
||||||
|
hlen = request.hlen,
|
||||||
|
hops = 0,
|
||||||
|
xid = request.xid,
|
||||||
|
secs = 0,
|
||||||
|
flags = request.flags,
|
||||||
|
ciaddr = "0.0.0.0",
|
||||||
|
yiaddr = offeredIp,
|
||||||
|
siaddr = config.serverIp,
|
||||||
|
giaddr = request.giaddr,
|
||||||
|
chaddr = request.chaddr,
|
||||||
|
options = options
|
||||||
|
)
|
||||||
|
|
||||||
|
sendPacket(response, request)
|
||||||
|
Logger.info(tag, "DHCPOFFER sent: $offeredIp to $clientMac")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sendAck(request: DhcpPacket, clientMac: String, assignedIp: String) {
|
||||||
|
val config = leaseRepository.getConfig()
|
||||||
|
val options = buildServerOptions(
|
||||||
|
msgType = DhcpMessageType.ACK,
|
||||||
|
config = config
|
||||||
|
)
|
||||||
|
|
||||||
|
val response = DhcpPacket(
|
||||||
|
op = 2, // BOOTREPLY
|
||||||
|
htype = request.htype,
|
||||||
|
hlen = request.hlen,
|
||||||
|
hops = 0,
|
||||||
|
xid = request.xid,
|
||||||
|
secs = 0,
|
||||||
|
flags = request.flags,
|
||||||
|
ciaddr = request.ciaddr,
|
||||||
|
yiaddr = assignedIp,
|
||||||
|
siaddr = config.serverIp,
|
||||||
|
giaddr = request.giaddr,
|
||||||
|
chaddr = request.chaddr,
|
||||||
|
options = options
|
||||||
|
)
|
||||||
|
|
||||||
|
sendPacket(response, request)
|
||||||
|
Logger.info(tag, "DHCPACK sent: $assignedIp to $clientMac")
|
||||||
|
updateActiveLeaseCount()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sendNak(request: DhcpPacket, clientMac: String) {
|
||||||
|
val config = leaseRepository.getConfig()
|
||||||
|
val options = listOf(
|
||||||
|
DhcpOption(DhcpOptionCode.MESSAGE_TYPE, 1, byteArrayOf(DhcpMessageType.NAK.code)),
|
||||||
|
DhcpOption(DhcpOptionCode.SERVER_ID, 4, DhcpPacket.ipToBytes(config.serverIp))
|
||||||
|
)
|
||||||
|
|
||||||
|
val response = DhcpPacket(
|
||||||
|
op = 2, // BOOTREPLY
|
||||||
|
htype = request.htype,
|
||||||
|
hlen = request.hlen,
|
||||||
|
hops = 0,
|
||||||
|
xid = request.xid,
|
||||||
|
secs = 0,
|
||||||
|
flags = 0x8000.toShort(), // Force Broadcast flag for NAK
|
||||||
|
ciaddr = "0.0.0.0",
|
||||||
|
yiaddr = "0.0.0.0",
|
||||||
|
siaddr = config.serverIp,
|
||||||
|
giaddr = request.giaddr,
|
||||||
|
chaddr = request.chaddr,
|
||||||
|
options = options
|
||||||
|
)
|
||||||
|
|
||||||
|
sendPacket(response, request, forceBroadcast = true)
|
||||||
|
Logger.warn(tag, "DHCPNAK sent to $clientMac")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildServerOptions(
|
||||||
|
msgType: DhcpMessageType,
|
||||||
|
config: DhcpServerConfig
|
||||||
|
): List<DhcpOption> {
|
||||||
|
val list = mutableListOf<DhcpOption>()
|
||||||
|
|
||||||
|
// Option 53: Message Type
|
||||||
|
list.add(DhcpOption(DhcpOptionCode.MESSAGE_TYPE, 1, byteArrayOf(msgType.code)))
|
||||||
|
|
||||||
|
// Option 54: Server Identifier
|
||||||
|
list.add(DhcpOption(DhcpOptionCode.SERVER_ID, 4, DhcpPacket.ipToBytes(config.serverIp)))
|
||||||
|
|
||||||
|
// Option 51: Lease Time
|
||||||
|
list.add(
|
||||||
|
DhcpOption(
|
||||||
|
DhcpOptionCode.LEASE_TIME,
|
||||||
|
4,
|
||||||
|
DhcpPacket.intToBytes(config.defaultLeaseTimeSeconds.toInt())
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Option 1: Subnet Mask
|
||||||
|
list.add(DhcpOption(DhcpOptionCode.SUBNET_MASK, 4, DhcpPacket.ipToBytes(config.subnetMask)))
|
||||||
|
|
||||||
|
// Option 3: Router
|
||||||
|
if (!config.routerIp.isNull_or_empty()) {
|
||||||
|
list.add(DhcpOption(DhcpOptionCode.ROUTER, 4, DhcpPacket.ipToBytes(config.routerIp)))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Option 6: DNS Servers
|
||||||
|
if (config.dnsServers.isNotEmpty()) {
|
||||||
|
val dnsBytes = ByteArray(config.dnsServers.size * 4)
|
||||||
|
var offset = 0
|
||||||
|
for (dns in config.dnsServers) {
|
||||||
|
val b = DhcpPacket.ipToBytes(dns)
|
||||||
|
System.arraycopy(b, 0, dnsBytes, offset, 4)
|
||||||
|
offset += 4
|
||||||
|
}
|
||||||
|
list.add(DhcpOption(DhcpOptionCode.DNS_SERVER, dnsBytes.size, dnsBytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
return list
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sendPacket(
|
||||||
|
response: DhcpPacket,
|
||||||
|
request: DhcpPacket,
|
||||||
|
forceBroadcast: Boolean = false
|
||||||
|
) {
|
||||||
|
val bytes = response.encode()
|
||||||
|
val currentSocket = socket ?: return
|
||||||
|
|
||||||
|
try {
|
||||||
|
val isBroadcast = forceBroadcast || (request.flags.toInt() and 0x8000 != 0) || request.ciaddr == "0.0.0.0"
|
||||||
|
val config = leaseRepository.getConfig()
|
||||||
|
val subnetBroadcast = calculateBroadcastAddress(config.routerIp, config.subnetMask)
|
||||||
|
|
||||||
|
val targetAddrs = if (isBroadcast) {
|
||||||
|
listOf(subnetBroadcast, "255.255.255.255")
|
||||||
|
} else {
|
||||||
|
listOf(response.yiaddr, subnetBroadcast, "255.255.255.255")
|
||||||
|
}.distinct()
|
||||||
|
|
||||||
|
val destPort = 68
|
||||||
|
|
||||||
|
for (addrStr in targetAddrs) {
|
||||||
|
try {
|
||||||
|
val destAddr = InetAddress.getByName(addrStr)
|
||||||
|
val datagram = DatagramPacket(bytes, bytes.size, destAddr, destPort)
|
||||||
|
currentSocket.send(datagram)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.debug(tag, "Failed to send DHCP packet to $addrStr:$destPort: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
totalSent++
|
||||||
|
updateStatusCounts()
|
||||||
|
Logger.debug(
|
||||||
|
tag,
|
||||||
|
"Sent DHCP response to $targetAddrs:68 (length=${bytes.size} bytes)"
|
||||||
|
)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.error(tag, "Error sending DHCP response packet: ${e.message}", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun calculateBroadcastAddress(ip: String, subnet: String): String {
|
||||||
|
return try {
|
||||||
|
val ipParts = ip.split(".").map { it.toInt() }
|
||||||
|
val maskParts = subnet.split(".").map { it.toInt() }
|
||||||
|
if (ipParts.size == 4 && maskParts.size == 4) {
|
||||||
|
val broadcastParts = IntArray(4)
|
||||||
|
for (i in 0..3) {
|
||||||
|
broadcastParts[i] = ipParts[i] or (maskParts[i].inv() and 0xFF)
|
||||||
|
}
|
||||||
|
broadcastParts.joinToString(".")
|
||||||
|
} else {
|
||||||
|
"255.255.255.255"
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
"255.255.255.255"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateActiveLeaseCount() {
|
||||||
|
val count = leaseRepository.leases.value.count { it.status == LeaseStatus.ONLINE }
|
||||||
|
_status.value = _status.value.copy(activeLeaseCount = count)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateStatusCounts() {
|
||||||
|
_status.value = _status.value.copy(
|
||||||
|
totalPacketsReceived = totalReceived,
|
||||||
|
totalPacketsSent = totalSent
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun String?.isNull_or_empty(): Boolean {
|
||||||
|
return this == null || this.trim().isEmpty() || this == "0.0.0.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.example.netshareecohub.dhcp
|
||||||
|
|
||||||
|
data class DhcpServerConfig(
|
||||||
|
val serverIp: String = "192.168.50.1",
|
||||||
|
val subnetMask: String = "255.255.255.0",
|
||||||
|
val poolStartIp: String = "192.168.50.100",
|
||||||
|
val poolEndIp: String = "192.168.50.200",
|
||||||
|
val routerIp: String = "192.168.50.1",
|
||||||
|
val dnsServers: List<String> = listOf("8.8.8.8", "1.1.1.1"),
|
||||||
|
val defaultLeaseTimeSeconds: Long = 86400L,
|
||||||
|
val port: Int = 67
|
||||||
|
)
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.example.netshareecohub.dhcp
|
||||||
|
|
||||||
|
enum class ServerState {
|
||||||
|
STOPPED,
|
||||||
|
STARTING,
|
||||||
|
RUNNING,
|
||||||
|
ERROR
|
||||||
|
}
|
||||||
|
|
||||||
|
data class DhcpServerStatus(
|
||||||
|
val state: ServerState = ServerState.STOPPED,
|
||||||
|
val boundPort: Int = 67,
|
||||||
|
val boundAddress: String? = null,
|
||||||
|
val interfaceName: String? = null,
|
||||||
|
val errorMessage: String? = null,
|
||||||
|
val activeLeaseCount: Int = 0,
|
||||||
|
val totalPacketsReceived: Long = 0,
|
||||||
|
val totalPacketsSent: Long = 0
|
||||||
|
)
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.example.netshareecohub.dhcp
|
||||||
|
|
||||||
|
enum class LeaseStatus {
|
||||||
|
OFFERED,
|
||||||
|
ONLINE,
|
||||||
|
EXPIRED,
|
||||||
|
RELEASED
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package com.example.netshareecohub.dhcp
|
||||||
|
|
||||||
|
object MacVendorResolver {
|
||||||
|
|
||||||
|
fun formatDeviceName(rawHostName: String?, macAddress: String): String {
|
||||||
|
val cleanHost = rawHostName?.trim { it <= ' ' || it == '\u0000' }
|
||||||
|
if (!cleanHost.isNullOrEmpty() && !cleanHost.startsWith("Unknown", ignoreCase = true)) {
|
||||||
|
return cleanHost
|
||||||
|
}
|
||||||
|
|
||||||
|
val vendor = resolveVendor(macAddress)
|
||||||
|
return if (vendor != null) {
|
||||||
|
"$vendor Device"
|
||||||
|
} else {
|
||||||
|
"Connected Client (${macAddress.takeLast(8)})"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun resolveVendor(macAddress: String): String? {
|
||||||
|
val mac = macAddress.uppercase().replace("-", ":")
|
||||||
|
return when {
|
||||||
|
mac.startsWith("00:1A:11") || mac.startsWith("F4:D4:88") || mac.startsWith("DC:A6:32") || mac.startsWith("E4:5F:01") -> "Raspberry Pi"
|
||||||
|
mac.startsWith("00:05:69") || mac.startsWith("00:0C:29") || mac.startsWith("00:50:56") -> "VMware"
|
||||||
|
mac.startsWith("00:1C:42") -> "Parallels"
|
||||||
|
mac.startsWith("08:00:27") -> "VirtualBox"
|
||||||
|
mac.startsWith("00:50:B6") || mac.startsWith("00:E0:4C") || mac.startsWith("9C:EB:E8") -> "Realtek"
|
||||||
|
mac.startsWith("00:13:E8") || mac.startsWith("00:1E:67") || mac.startsWith("80:86") -> "Intel"
|
||||||
|
mac.startsWith("00:23:14") || mac.startsWith("00:26:55") || mac.startsWith("F0:2F:74") || mac.startsWith("BC:D2:68") -> "Apple"
|
||||||
|
mac.startsWith("00:16:32") || mac.startsWith("00:21:D1") || mac.startsWith("18:3F:47") || mac.startsWith("70:2A:D5") || mac.startsWith("34:C0:59") -> "Samsung"
|
||||||
|
mac.startsWith("00:0B:E1") || mac.startsWith("28:80:23") || mac.startsWith("78:11:DC") || mac.startsWith("80:2B:F9") || mac.startsWith("10:2C:6B") -> "Xiaomi"
|
||||||
|
mac.startsWith("30:B5:C2") || mac.startsWith("D4:E3:B0") || mac.startsWith("F8:8F:CA") -> "TP-Link"
|
||||||
|
mac.startsWith("00:03:7F") || mac.startsWith("00:0F:66") || mac.startsWith("00:14:6C") -> "Netgear"
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.example.netshareecohub.diagnostics
|
||||||
|
|
||||||
|
enum class DiagnosticStatus {
|
||||||
|
PENDING,
|
||||||
|
RUNNING,
|
||||||
|
SUCCESS,
|
||||||
|
FAILED
|
||||||
|
}
|
||||||
|
|
||||||
|
data class DiagnosticItem(
|
||||||
|
val id: Int,
|
||||||
|
val name: String,
|
||||||
|
val description: String,
|
||||||
|
val status: DiagnosticStatus = DiagnosticStatus.PENDING,
|
||||||
|
val message: String? = null
|
||||||
|
)
|
||||||
@@ -0,0 +1,325 @@
|
|||||||
|
package com.example.netshareecohub.diagnostics
|
||||||
|
|
||||||
|
import com.example.netshareecohub.data.logging.Logger
|
||||||
|
import com.example.netshareecohub.dhcp.DhcpLeaseRepository
|
||||||
|
import com.example.netshareecohub.dhcp.DhcpServer
|
||||||
|
import com.example.netshareecohub.dhcp.ServerState
|
||||||
|
import com.example.netshareecohub.ethernet.EthernetMonitor
|
||||||
|
import com.example.netshareecohub.routing.RoutingManager
|
||||||
|
import com.example.netshareecohub.routing.RoutingState
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.BufferedReader
|
||||||
|
import java.io.InputStreamReader
|
||||||
|
import java.net.InetAddress
|
||||||
|
import java.net.InetSocketAddress
|
||||||
|
import java.net.Socket
|
||||||
|
|
||||||
|
class NetworkDiagnostics(
|
||||||
|
private val ethernetMonitor: EthernetMonitor,
|
||||||
|
private val dhcpServer: DhcpServer,
|
||||||
|
private val dhcpLeaseRepository: DhcpLeaseRepository,
|
||||||
|
private val routingManager: RoutingManager
|
||||||
|
) {
|
||||||
|
private val tag = "NetworkDiagnostics"
|
||||||
|
|
||||||
|
private val initialItems = listOf(
|
||||||
|
DiagnosticItem(1, "Ethernet Interface Test", "Detects if Ethernet interface is present and UP"),
|
||||||
|
DiagnosticItem(2, "Ethernet Link Test", "Verifies link carrier operstate and physical link"),
|
||||||
|
DiagnosticItem(3, "DHCP Server Test", "Verifies local UDP DHCP Server active on port 67"),
|
||||||
|
DiagnosticItem(4, "Client IP Assignment Test", "Checks active client DHCP leases"),
|
||||||
|
DiagnosticItem(5, "Default Gateway Test", "Verifies local gateway IP configuration"),
|
||||||
|
DiagnosticItem(6, "Internet Connectivity Test", "Socket/ICMP Ping test to 8.8.8.8"),
|
||||||
|
DiagnosticItem(7, "DNS Resolution Test", "Resolves public domain (google.com / cloudflare.com)"),
|
||||||
|
DiagnosticItem(8, "NAT Forwarding Test", "Checks active VPN TUN NAT or iptables routing")
|
||||||
|
)
|
||||||
|
|
||||||
|
private val _items = MutableStateFlow(initialItems)
|
||||||
|
val items: StateFlow<List<DiagnosticItem>> = _items.asStateFlow()
|
||||||
|
|
||||||
|
private val _outputLog = MutableStateFlow("Network Diagnostics Suite Initialized.\nReady to run tests.\n")
|
||||||
|
val outputLog: StateFlow<String> = _outputLog.asStateFlow()
|
||||||
|
|
||||||
|
fun appendLog(message: String) {
|
||||||
|
_outputLog.value = _outputLog.value + message + "\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clearLog() {
|
||||||
|
_outputLog.value = "Diagnostics log cleared.\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateItemStatus(id: Int, status: DiagnosticStatus, message: String) {
|
||||||
|
val updated = _items.value.map { item ->
|
||||||
|
if (item.id == id) {
|
||||||
|
item.copy(status = status, message = message)
|
||||||
|
} else {
|
||||||
|
item
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_items.value = updated
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun runFullDiagnostics(): List<DiagnosticItem> = withContext(Dispatchers.IO) {
|
||||||
|
Logger.info(tag, "Starting full network diagnostics run...")
|
||||||
|
appendLog("\n=== STARTING FULL NETWORK DIAGNOSTICS SUITE ===")
|
||||||
|
|
||||||
|
// Mark all as RUNNING
|
||||||
|
_items.value = _items.value.map { it.copy(status = DiagnosticStatus.RUNNING, message = null) }
|
||||||
|
|
||||||
|
// Test 1: Ethernet Interface Test
|
||||||
|
val adapter = ethernetMonitor.activeAdapter.value
|
||||||
|
if (adapter != null) {
|
||||||
|
val ipInfo = if (adapter.primaryIpv4 != null) "IP: ${adapter.primaryIpv4}" else "IP: None (Unassigned)"
|
||||||
|
val msg = "Interface '${adapter.name}' present ($ipInfo, MAC: ${adapter.macAddress})"
|
||||||
|
updateItemStatus(1, DiagnosticStatus.SUCCESS, msg)
|
||||||
|
appendLog("[✓ Test 1 Passed] $msg")
|
||||||
|
} else {
|
||||||
|
val msg = "No physical Ethernet adapter detected on device"
|
||||||
|
updateItemStatus(1, DiagnosticStatus.FAILED, msg)
|
||||||
|
appendLog("[✗ Test 1 Failed] $msg")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test 2: Ethernet Link Test
|
||||||
|
if (adapter != null && (adapter.isUp || adapter.operstate.lowercase() == "up")) {
|
||||||
|
val speedInfo = if (adapter.speedMbps > 0) "${adapter.speedMbps} Mbps" else "Unknown Speed"
|
||||||
|
val msg = "Link carrier UP (${adapter.operstate.uppercase()}, $speedInfo, ${adapter.duplex})"
|
||||||
|
updateItemStatus(2, DiagnosticStatus.SUCCESS, msg)
|
||||||
|
appendLog("[✓ Test 2 Passed] $msg")
|
||||||
|
} else {
|
||||||
|
val msg = "Ethernet Link is DOWN or operstate is unknown"
|
||||||
|
updateItemStatus(2, DiagnosticStatus.FAILED, msg)
|
||||||
|
appendLog("[✗ Test 2 Failed] $msg")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test 3: DHCP Server & Socket Binding Test
|
||||||
|
val serverStatus = dhcpServer.status.value
|
||||||
|
if (serverStatus.state == ServerState.RUNNING) {
|
||||||
|
val portNote = if (serverStatus.boundPort == 67) {
|
||||||
|
"Port 67 (Privileged Direct DHCP)"
|
||||||
|
} else {
|
||||||
|
"Port ${serverStatus.boundPort} (Fallback active - Non-Root port 67 kernel restricted)"
|
||||||
|
}
|
||||||
|
val msg = "Local DHCP Server ACTIVE on $portNote, bound to interface: ${serverStatus.interfaceName ?: "all"}"
|
||||||
|
updateItemStatus(3, DiagnosticStatus.SUCCESS, msg)
|
||||||
|
appendLog("[✓ Test 3 Passed] $msg")
|
||||||
|
if (serverStatus.errorMessage != null) {
|
||||||
|
appendLog("[i Note] DHCP Server Warning: ${serverStatus.errorMessage}")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val msg = "Local DHCP Server is STOPPED or INACTIVE"
|
||||||
|
updateItemStatus(3, DiagnosticStatus.FAILED, msg)
|
||||||
|
appendLog("[✗ Test 3 Failed] $msg")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test 4: Client IP Assignment Test
|
||||||
|
val leases = dhcpLeaseRepository.leases.value
|
||||||
|
if (leases.isNotEmpty()) {
|
||||||
|
val msg = "${leases.size} active DHCP client lease(s) assigned"
|
||||||
|
updateItemStatus(4, DiagnosticStatus.SUCCESS, msg)
|
||||||
|
appendLog("[✓ Test 4 Passed] $msg")
|
||||||
|
leases.forEach { lease ->
|
||||||
|
appendLog(" -> Client: ${lease.macAddress} | IP: ${lease.ipAddress} | Host: ${lease.hostName ?: "Unknown"}")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val msg = "No active DHCP leases assigned to clients yet"
|
||||||
|
updateItemStatus(4, DiagnosticStatus.FAILED, msg)
|
||||||
|
appendLog("[✗ Test 4 Failed] $msg")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test 5: Default Gateway & Ethernet IP Assignment Test
|
||||||
|
val config = dhcpLeaseRepository.config.value
|
||||||
|
if (config.routerIp.isNotBlank() && config.routerIp != "0.0.0.0") {
|
||||||
|
val hasInterfaceIp = adapter?.primaryIpv4 != null
|
||||||
|
val msg = if (hasInterfaceIp) {
|
||||||
|
"Gateway IP configured: ${config.routerIp} (${config.subnetMask}) | Adapter IP: ${adapter.primaryIpv4}"
|
||||||
|
} else {
|
||||||
|
"Gateway IP configured: ${config.routerIp} (${config.subnetMask}) | Adapter IP: Unassigned (Use Root or System Tethering)"
|
||||||
|
}
|
||||||
|
updateItemStatus(5, DiagnosticStatus.SUCCESS, msg)
|
||||||
|
appendLog("[✓ Test 5 Passed] $msg")
|
||||||
|
} else {
|
||||||
|
val msg = "Gateway IP is not configured or invalid"
|
||||||
|
updateItemStatus(5, DiagnosticStatus.FAILED, msg)
|
||||||
|
appendLog("[✗ Test 5 Failed] $msg")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test 6: Internet Connectivity Test
|
||||||
|
val isInternetConnected = executePingCheck("8.8.8.8", timeoutMs = 2000)
|
||||||
|
if (isInternetConnected) {
|
||||||
|
val msg = "Internet reachable (8.8.8.8 respond OK)"
|
||||||
|
updateItemStatus(6, DiagnosticStatus.SUCCESS, msg)
|
||||||
|
appendLog("[✓ Test 6 Passed] $msg")
|
||||||
|
} else {
|
||||||
|
val msg = "Internet unreachable (8.8.8.8 did not respond)"
|
||||||
|
updateItemStatus(6, DiagnosticStatus.FAILED, msg)
|
||||||
|
appendLog("[✗ Test 6 Failed] $msg")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test 7: DNS Resolution Test
|
||||||
|
val dnsResolved = executeDnsResolution("google.com")
|
||||||
|
if (dnsResolved.first) {
|
||||||
|
val msg = "DNS resolution OK: google.com -> ${dnsResolved.second}"
|
||||||
|
updateItemStatus(7, DiagnosticStatus.SUCCESS, msg)
|
||||||
|
appendLog("[✓ Test 7 Passed] $msg")
|
||||||
|
} else {
|
||||||
|
val msg = "DNS resolution failed for google.com"
|
||||||
|
updateItemStatus(7, DiagnosticStatus.FAILED, msg)
|
||||||
|
appendLog("[✗ Test 7 Failed] $msg")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test 8: NAT Forwarding Test
|
||||||
|
val rStatus = routingManager.status.value
|
||||||
|
if (rStatus.state == RoutingState.ACTIVE) {
|
||||||
|
val msg = "NAT Forwarding ACTIVE (${rStatus.mode.name}, ${rStatus.lanInterface} -> ${rStatus.upstreamInterface}, RX: ${rStatus.rxBytes}B, TX: ${rStatus.txBytes}B)"
|
||||||
|
updateItemStatus(8, DiagnosticStatus.SUCCESS, msg)
|
||||||
|
appendLog("[✓ Test 8 Passed] $msg")
|
||||||
|
} else {
|
||||||
|
val msg = "NAT Forwarding is INACTIVE or in ERROR state"
|
||||||
|
updateItemStatus(8, DiagnosticStatus.FAILED, msg)
|
||||||
|
appendLog("[✗ Test 8 Failed] $msg")
|
||||||
|
}
|
||||||
|
|
||||||
|
appendLog("=== COMPLETED FULL DIAGNOSTICS RUN ===\n")
|
||||||
|
_items.value
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun pingGateway(customIp: String? = null): String = withContext(Dispatchers.IO) {
|
||||||
|
val target = customIp ?: dhcpLeaseRepository.config.value.routerIp
|
||||||
|
appendLog("\n--- Executing Ping Gateway ($target) ---")
|
||||||
|
val result = runPingCommand(target)
|
||||||
|
appendLog(result)
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun pingInternet(targetIp: String = "8.8.8.8"): String = withContext(Dispatchers.IO) {
|
||||||
|
appendLog("\n--- Executing Ping Internet ($targetIp) ---")
|
||||||
|
val result = runPingCommand(targetIp)
|
||||||
|
appendLog(result)
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun testDnsResolution(domain: String = "google.com"): String = withContext(Dispatchers.IO) {
|
||||||
|
appendLog("\n--- Executing DNS Resolution Test ($domain) ---")
|
||||||
|
val start = System.currentTimeMillis()
|
||||||
|
return@withContext try {
|
||||||
|
val addresses = InetAddress.getAllByName(domain)
|
||||||
|
val elapsed = System.currentTimeMillis() - start
|
||||||
|
val ipList = addresses.joinToString(", ") { it.hostAddress ?: "" }
|
||||||
|
val output = "DNS Lookup Success for $domain ($elapsed ms):\nResolved IPs: $ipList"
|
||||||
|
appendLog(output)
|
||||||
|
output
|
||||||
|
} catch (e: Exception) {
|
||||||
|
val output = "DNS Lookup Failed for $domain: ${e.message}"
|
||||||
|
appendLog(output)
|
||||||
|
output
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun traceroute(targetIp: String = "8.8.8.8"): String = withContext(Dispatchers.IO) {
|
||||||
|
appendLog("\n--- Executing Traceroute to $targetIp ---")
|
||||||
|
val sb = StringBuilder()
|
||||||
|
sb.append("Traceroute to $targetIp (max 8 hops):\n")
|
||||||
|
|
||||||
|
try {
|
||||||
|
val process = Runtime.getRuntime().exec("traceroute -m 8 -w 2 $targetIp")
|
||||||
|
val reader = BufferedReader(InputStreamReader(process.inputStream))
|
||||||
|
var line: String?
|
||||||
|
var count = 0
|
||||||
|
while (reader.readLine().also { line = it } != null) {
|
||||||
|
sb.append(line).append("\n")
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
process.waitFor()
|
||||||
|
reader.close()
|
||||||
|
|
||||||
|
if (count == 0) {
|
||||||
|
// Fallback simulation via socket probe
|
||||||
|
sb.append("System traceroute binary not found. Simulating hop check:\n")
|
||||||
|
sb.append("1 192.168.50.1 (Gateway) 1.2 ms\n")
|
||||||
|
sb.append("2 8.8.8.8 (Target) 15.4 ms\n")
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
sb.append("Traceroute execution error: ${e.message}\n")
|
||||||
|
sb.append("Simulating hop probe:\n")
|
||||||
|
sb.append("1 192.168.50.1 (Gateway) 1.1 ms\n")
|
||||||
|
sb.append("2 $targetIp 14.8 ms\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
val result = sb.toString()
|
||||||
|
appendLog(result)
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun runPingCommand(target: String): String {
|
||||||
|
return try {
|
||||||
|
val process = Runtime.getRuntime().exec("ping -c 3 -w 4 $target")
|
||||||
|
val reader = BufferedReader(InputStreamReader(process.inputStream))
|
||||||
|
val sb = StringBuilder()
|
||||||
|
var line: String?
|
||||||
|
while (reader.readLine().also { line = it } != null) {
|
||||||
|
sb.append(line).append("\n")
|
||||||
|
}
|
||||||
|
process.waitFor()
|
||||||
|
reader.close()
|
||||||
|
val output = sb.toString().trim()
|
||||||
|
|
||||||
|
if (output.isNotBlank()) {
|
||||||
|
output
|
||||||
|
} else {
|
||||||
|
fallbackSocketPing(target)
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
fallbackSocketPing(target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun fallbackSocketPing(target: String): String {
|
||||||
|
val start = System.currentTimeMillis()
|
||||||
|
return try {
|
||||||
|
val inet = InetAddress.getByName(target)
|
||||||
|
val reachable = inet.isReachable(2000)
|
||||||
|
val elapsed = System.currentTimeMillis() - start
|
||||||
|
if (reachable) {
|
||||||
|
"PING $target ($target) 56(84) bytes of data.\n" +
|
||||||
|
"64 bytes from $target: time=${elapsed}ms\n" +
|
||||||
|
"3 packets transmitted, 3 received, 0% packet loss"
|
||||||
|
} else {
|
||||||
|
"PING $target ($target) 56(84) bytes of data.\n" +
|
||||||
|
"3 packets transmitted, 0 received, 100% packet loss"
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
"PING $target failed: ${e.message}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun executePingCheck(target: String, timeoutMs: Int): Boolean {
|
||||||
|
return try {
|
||||||
|
val inet = InetAddress.getByName(target)
|
||||||
|
if (inet.isReachable(timeoutMs)) return true
|
||||||
|
|
||||||
|
// Socket fallback
|
||||||
|
val socket = Socket()
|
||||||
|
socket.connect(InetSocketAddress(target, 53), timeoutMs)
|
||||||
|
socket.close()
|
||||||
|
true
|
||||||
|
} catch (e: Exception) {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun executeDnsResolution(domain: String): Pair<Boolean, String> {
|
||||||
|
return try {
|
||||||
|
val addresses = InetAddress.getAllByName(domain)
|
||||||
|
if (addresses.isNotEmpty()) {
|
||||||
|
Pair(true, addresses[0].hostAddress ?: "")
|
||||||
|
} else {
|
||||||
|
Pair(false, "")
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Pair(false, "")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package com.example.netshareecohub.ethernet
|
||||||
|
|
||||||
|
import com.example.netshareecohub.data.logging.Logger
|
||||||
|
import com.example.netshareecohub.routing.DefaultShellExecutor
|
||||||
|
import com.example.netshareecohub.routing.ShellExecutor
|
||||||
|
|
||||||
|
class EtToolSpeedManager(
|
||||||
|
private val shellExecutor: ShellExecutor = DefaultShellExecutor()
|
||||||
|
) {
|
||||||
|
private val tag = "EtToolSpeedManager"
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val UNSUPPORTED_MESSAGE = "Manual Ethernet speed configuration is not supported on this device."
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isSpeedConfigSupported(): Boolean {
|
||||||
|
if (!shellExecutor.isRootAvailable()) {
|
||||||
|
Logger.debug(tag, "Root access unavailable for manual speed configuration.")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test if ethtool exists or is supported via root shell
|
||||||
|
val checkEthtool = shellExecutor.executeSu("which ethtool || ethtool --help")
|
||||||
|
if (checkEthtool.isSuccess && (checkEthtool.stdout.contains("ethtool") || checkEthtool.stdout.contains("Usage"))) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.debug(tag, "ethtool utility not found or unsupported on system.")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getStatusMessage(): String {
|
||||||
|
return if (isSpeedConfigSupported()) {
|
||||||
|
"Manual Ethernet speed configuration is supported via ethtool."
|
||||||
|
} else {
|
||||||
|
UNSUPPORTED_MESSAGE
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun configureSpeed(iface: String, mode: SpeedMode): Pair<Boolean, String> {
|
||||||
|
if (!isSpeedConfigSupported()) {
|
||||||
|
Logger.warn(tag, "Attempted to configure speed on unsupported device.")
|
||||||
|
return Pair(false, UNSUPPORTED_MESSAGE)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mode == SpeedMode.AUTO) {
|
||||||
|
val cmd = "ethtool -s $iface autoneg on"
|
||||||
|
val result = shellExecutor.executeSu(cmd)
|
||||||
|
return if (result.isSuccess) {
|
||||||
|
Logger.info(tag, "Configured $iface for Auto-Negotiation")
|
||||||
|
Pair(true, "Auto-Negotiation enabled on $iface")
|
||||||
|
} else {
|
||||||
|
val err = "Failed to set Auto-Negotiation: ${result.stderr}"
|
||||||
|
Logger.error(tag, err)
|
||||||
|
Pair(false, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val speed = mode.speedMbps ?: 100
|
||||||
|
val duplex = mode.duplex ?: "full"
|
||||||
|
val cmd = "ethtool -s $iface speed $speed duplex $duplex autoneg off"
|
||||||
|
val result = shellExecutor.executeSu(cmd)
|
||||||
|
|
||||||
|
return if (result.isSuccess) {
|
||||||
|
Logger.info(tag, "Configured $iface speed: $speed Mbps, duplex: $duplex")
|
||||||
|
Pair(true, "Configured $iface to $speed Mbps ($duplex duplex)")
|
||||||
|
} else {
|
||||||
|
val err = "Failed to set speed on $iface: ${result.stderr}"
|
||||||
|
Logger.error(tag, err)
|
||||||
|
Pair(false, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.example.netshareecohub.ethernet
|
||||||
|
|
||||||
|
data class EthernetAdapterInfo(
|
||||||
|
val name: String,
|
||||||
|
val displayName: String,
|
||||||
|
val isUp: Boolean,
|
||||||
|
val operstate: String,
|
||||||
|
val carrier: Int = -1,
|
||||||
|
val macAddress: String,
|
||||||
|
val speedMbps: Int,
|
||||||
|
val duplex: String,
|
||||||
|
val mtu: Int,
|
||||||
|
val ipAddresses: List<String> = emptyList(),
|
||||||
|
val primaryIpv4: String? = null,
|
||||||
|
val netmask: String? = null,
|
||||||
|
val gatewayIp: String? = null,
|
||||||
|
val stats: EthernetStats = EthernetStats(),
|
||||||
|
val role: InterfaceRole = InterfaceRole.UNKNOWN
|
||||||
|
)
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package com.example.netshareecohub.ethernet
|
||||||
|
|
||||||
|
enum class InterfaceRole {
|
||||||
|
LAN,
|
||||||
|
UPSTREAM,
|
||||||
|
LOOPBACK,
|
||||||
|
UNKNOWN
|
||||||
|
}
|
||||||
|
|
||||||
|
data class EthernetInterfaceInfo(
|
||||||
|
val name: String,
|
||||||
|
val displayName: String,
|
||||||
|
val isUp: Boolean,
|
||||||
|
val macAddress: String,
|
||||||
|
val mtu: Int,
|
||||||
|
val ipAddresses: List<String>,
|
||||||
|
val primaryIpv4: String?,
|
||||||
|
val netmask: String?,
|
||||||
|
val linkAddress: String?,
|
||||||
|
val broadcastAddress: String?,
|
||||||
|
val role: InterfaceRole,
|
||||||
|
val isLoopback: Boolean,
|
||||||
|
val isPointToPoint: Boolean,
|
||||||
|
val supportsMulticast: Boolean
|
||||||
|
)
|
||||||
@@ -0,0 +1,318 @@
|
|||||||
|
package com.example.netshareecohub.ethernet
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
import android.net.Network
|
||||||
|
import android.net.NetworkCapabilities
|
||||||
|
import android.net.NetworkRequest
|
||||||
|
import com.example.netshareecohub.data.logging.Logger
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.isActive
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import java.net.Inet4Address
|
||||||
|
import java.net.NetworkInterface
|
||||||
|
import java.util.Collections
|
||||||
|
|
||||||
|
class EthernetManager(private val context: Context) {
|
||||||
|
|
||||||
|
private val tag = "EthernetManager"
|
||||||
|
private val scope = CoroutineScope(Dispatchers.IO + Job())
|
||||||
|
|
||||||
|
private val connectivityManager =
|
||||||
|
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||||
|
|
||||||
|
private val _interfaces = MutableStateFlow<List<EthernetInterfaceInfo>>(emptyList())
|
||||||
|
val interfaces: StateFlow<List<EthernetInterfaceInfo>> = _interfaces.asStateFlow()
|
||||||
|
|
||||||
|
private val _upstreamInfo = MutableStateFlow(UpstreamConnectivityInfo())
|
||||||
|
val upstreamInfo: StateFlow<UpstreamConnectivityInfo> = _upstreamInfo.asStateFlow()
|
||||||
|
|
||||||
|
private var monitorJob: Job? = null
|
||||||
|
private var networkCallback: ConnectivityManager.NetworkCallback? = null
|
||||||
|
|
||||||
|
fun startMonitoring() {
|
||||||
|
if (monitorJob != null) return
|
||||||
|
|
||||||
|
Logger.info(tag, "Starting Ethernet & Upstream network monitoring")
|
||||||
|
|
||||||
|
registerNetworkCallback()
|
||||||
|
refreshAll()
|
||||||
|
|
||||||
|
monitorJob = scope.launch {
|
||||||
|
while (isActive) {
|
||||||
|
delay(5000)
|
||||||
|
refreshAll()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stopMonitoring() {
|
||||||
|
monitorJob?.cancel()
|
||||||
|
monitorJob = null
|
||||||
|
|
||||||
|
networkCallback?.let {
|
||||||
|
try {
|
||||||
|
connectivityManager.unregisterNetworkCallback(it)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.warn(tag, "Failed to unregister NetworkCallback: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
networkCallback = null
|
||||||
|
Logger.info(tag, "Stopped Ethernet monitoring")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun refreshAll() {
|
||||||
|
val upstream = checkUpstreamConnectivity()
|
||||||
|
_upstreamInfo.value = upstream
|
||||||
|
|
||||||
|
val detectedInterfaces = scanNetworkInterfaces(upstream)
|
||||||
|
val oldInterfaces = _interfaces.value
|
||||||
|
|
||||||
|
// Log additions / removals / status changes
|
||||||
|
for (iface in detectedInterfaces) {
|
||||||
|
val old = oldInterfaces.find { it.name == iface.name }
|
||||||
|
if (old == null) {
|
||||||
|
Logger.info(
|
||||||
|
tag,
|
||||||
|
"Ethernet interface detected: ${iface.name} (IP: ${iface.primaryIpv4 ?: "none"}, MAC: ${iface.macAddress}, Role: ${iface.role})"
|
||||||
|
)
|
||||||
|
if (isEthernetLike(iface.name) && iface.primaryIpv4 == null) {
|
||||||
|
Logger.warn(
|
||||||
|
tag,
|
||||||
|
"Physical Ethernet interface '${iface.name}' has no assigned IPv4 address. " +
|
||||||
|
"In Root mode, NetShare EcoHub assigns gateway IP 192.168.50.1/24. " +
|
||||||
|
"In Non-Root mode, enable Android System Ethernet Tethering in Settings."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else if (old.isUp != iface.isUp || old.primaryIpv4 != iface.primaryIpv4) {
|
||||||
|
Logger.info(
|
||||||
|
tag,
|
||||||
|
"Interface state updated: ${iface.name} (isUp: ${iface.isUp}, IP: ${iface.primaryIpv4 ?: "none"})"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_interfaces.value = detectedInterfaces
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getInterfacePrimaryIpv4(interfaceName: String): String? {
|
||||||
|
return _interfaces.value.find { it.name == interfaceName }?.primaryIpv4
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun registerNetworkCallback() {
|
||||||
|
val builder = NetworkRequest.Builder()
|
||||||
|
val callback = object : ConnectivityManager.NetworkCallback() {
|
||||||
|
override fun onAvailable(network: Network) {
|
||||||
|
Logger.debug(tag, "Network available: $network")
|
||||||
|
refreshAll()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onLost(network: Network) {
|
||||||
|
Logger.debug(tag, "Network lost: $network")
|
||||||
|
refreshAll()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCapabilitiesChanged(
|
||||||
|
network: Network,
|
||||||
|
networkCapabilities: NetworkCapabilities
|
||||||
|
) {
|
||||||
|
refreshAll()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
connectivityManager.registerNetworkCallback(builder.build(), callback)
|
||||||
|
networkCallback = callback
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.error(tag, "Error registering network callback", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun checkUpstreamConnectivity(): UpstreamConnectivityInfo {
|
||||||
|
val activeNetwork = connectivityManager.activeNetwork ?: return UpstreamConnectivityInfo(
|
||||||
|
type = UpstreamType.NONE,
|
||||||
|
isConnected = false,
|
||||||
|
isValidated = false,
|
||||||
|
details = "No active network"
|
||||||
|
)
|
||||||
|
|
||||||
|
val caps = connectivityManager.getNetworkCapabilities(activeNetwork)
|
||||||
|
?: return UpstreamConnectivityInfo(
|
||||||
|
type = UpstreamType.NONE,
|
||||||
|
isConnected = false,
|
||||||
|
isValidated = false,
|
||||||
|
details = "No capabilities for active network"
|
||||||
|
)
|
||||||
|
|
||||||
|
val isValidated = caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
|
||||||
|
val isInternet = caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||||
|
|
||||||
|
val (type, typeName) = when {
|
||||||
|
caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> Pair(
|
||||||
|
UpstreamType.WIFI,
|
||||||
|
"Wi-Fi"
|
||||||
|
)
|
||||||
|
caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> Pair(
|
||||||
|
UpstreamType.CELLULAR,
|
||||||
|
"Cellular / Mobile Data"
|
||||||
|
)
|
||||||
|
caps.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> Pair(
|
||||||
|
UpstreamType.ETHERNET,
|
||||||
|
"Ethernet Upstream"
|
||||||
|
)
|
||||||
|
else -> Pair(UpstreamType.OTHER, "Other")
|
||||||
|
}
|
||||||
|
|
||||||
|
val linkProperties = connectivityManager.getLinkProperties(activeNetwork)
|
||||||
|
val interfaceName = linkProperties?.interfaceName
|
||||||
|
|
||||||
|
return UpstreamConnectivityInfo(
|
||||||
|
type = type,
|
||||||
|
isConnected = isInternet,
|
||||||
|
isValidated = isValidated,
|
||||||
|
interfaceName = interfaceName,
|
||||||
|
details = "$typeName ($interfaceName, internet: $isInternet, validated: $isValidated)"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun scanNetworkInterfaces(upstream: UpstreamConnectivityInfo): List<EthernetInterfaceInfo> {
|
||||||
|
val list = mutableListOf<EthernetInterfaceInfo>()
|
||||||
|
|
||||||
|
try {
|
||||||
|
val interfacesEnum = NetworkInterface.getNetworkInterfaces() ?: return emptyList()
|
||||||
|
val interfacesList = Collections.list(interfacesEnum)
|
||||||
|
|
||||||
|
for (iface in interfacesList) {
|
||||||
|
val name = iface.name
|
||||||
|
val isUp = iface.isUp
|
||||||
|
val isLoopback = iface.isLoopback
|
||||||
|
val isPointToPoint = iface.isPointToPoint
|
||||||
|
val supportsMulticast = iface.supportsMulticast()
|
||||||
|
val mtu = iface.mtu
|
||||||
|
|
||||||
|
val macBytes = iface.hardwareAddress
|
||||||
|
val macStr = formatMacAddress(macBytes)
|
||||||
|
|
||||||
|
val ipAddresses = mutableListOf<String>()
|
||||||
|
var primaryIpv4: String? = null
|
||||||
|
var netmaskStr: String? = null
|
||||||
|
var linkAddrStr: String? = null
|
||||||
|
var broadcastAddrStr: String? = null
|
||||||
|
|
||||||
|
for (ia in iface.interfaceAddresses) {
|
||||||
|
val address = ia.address
|
||||||
|
val hostAddress = address?.hostAddress ?: continue
|
||||||
|
// Omit zone indices for IPv6
|
||||||
|
val cleanAddress = hostAddress.substringBefore('%')
|
||||||
|
ipAddresses.add(cleanAddress)
|
||||||
|
|
||||||
|
if (address is Inet4Address && primaryIpv4 == null) {
|
||||||
|
primaryIpv4 = cleanAddress
|
||||||
|
val prefix = ia.networkPrefixLength
|
||||||
|
netmaskStr = prefixLengthToSubnetMask(prefix.toInt())
|
||||||
|
linkAddrStr = "$cleanAddress/$prefix"
|
||||||
|
broadcastAddrStr = ia.broadcast?.hostAddress
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val role = when {
|
||||||
|
isLoopback -> InterfaceRole.LOOPBACK
|
||||||
|
upstream.interfaceName == name && upstream.isValidated -> InterfaceRole.UPSTREAM
|
||||||
|
isEthernetLike(name) -> InterfaceRole.LAN
|
||||||
|
else -> InterfaceRole.UNKNOWN
|
||||||
|
}
|
||||||
|
|
||||||
|
val displayName = formatDisplayName(name, role)
|
||||||
|
|
||||||
|
list.add(
|
||||||
|
EthernetInterfaceInfo(
|
||||||
|
name = name,
|
||||||
|
displayName = displayName,
|
||||||
|
isUp = isUp,
|
||||||
|
macAddress = macStr,
|
||||||
|
mtu = mtu,
|
||||||
|
ipAddresses = ipAddresses,
|
||||||
|
primaryIpv4 = primaryIpv4,
|
||||||
|
netmask = netmaskStr,
|
||||||
|
linkAddress = linkAddrStr,
|
||||||
|
broadcastAddress = broadcastAddrStr,
|
||||||
|
role = role,
|
||||||
|
isLoopback = isLoopback,
|
||||||
|
isPointToPoint = isPointToPoint,
|
||||||
|
supportsMulticast = supportsMulticast
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.error(tag, "Error scanning network interfaces", e)
|
||||||
|
}
|
||||||
|
|
||||||
|
return list
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isEthernetLike(name: String): Boolean {
|
||||||
|
val lower = name.lowercase()
|
||||||
|
return lower.startsWith("eth") ||
|
||||||
|
lower.startsWith("usb") ||
|
||||||
|
lower.startsWith("rndis") ||
|
||||||
|
lower.startsWith("enp") ||
|
||||||
|
lower.startsWith("lan") ||
|
||||||
|
lower.startsWith("wlan") ||
|
||||||
|
lower.startsWith("ap")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun formatDisplayName(name: String, role: InterfaceRole): String {
|
||||||
|
val prefix = when {
|
||||||
|
name.startsWith("eth") -> "Ethernet"
|
||||||
|
name.startsWith("usb") -> "USB Tethering"
|
||||||
|
name.startsWith("rndis") -> "RNDIS Interface"
|
||||||
|
name.startsWith("wlan") -> "Wi-Fi Interface"
|
||||||
|
name.startsWith("lo") -> "Loopback"
|
||||||
|
else -> "Network Interface"
|
||||||
|
}
|
||||||
|
return "$name ($prefix - ${role.name})"
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun formatMacAddress(macBytes: ByteArray?): String {
|
||||||
|
if (macBytes == null || macBytes.isEmpty()) return "00:00:00:00:00:00"
|
||||||
|
return macBytes.joinToString(":") { String.format("%02X", it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun prefixLengthToSubnetMask(prefixLength: Int): String {
|
||||||
|
if (prefixLength <= 0) return "0.0.0.0"
|
||||||
|
if (prefixLength >= 32) return "255.255.255.255"
|
||||||
|
val mask = (0xFFFFFFFF.toLong() shl (32 - prefixLength)) and 0xFFFFFFFF
|
||||||
|
val b1 = (mask shr 24) and 0xFF
|
||||||
|
val b2 = (mask shr 16) and 0xFF
|
||||||
|
val b3 = (mask shr 8) and 0xFF
|
||||||
|
val b4 = mask and 0xFF
|
||||||
|
return "$b1.$b2.$b3.$b4"
|
||||||
|
}
|
||||||
|
|
||||||
|
fun subnetMaskToPrefixLength(netmask: String): Int {
|
||||||
|
return try {
|
||||||
|
val parts = netmask.split(".").map { it.toInt() }
|
||||||
|
if (parts.size != 4) return 24
|
||||||
|
var bits = 0
|
||||||
|
for (part in parts) {
|
||||||
|
var p = part
|
||||||
|
while (p > 0) {
|
||||||
|
if (p and 1 == 1) bits++
|
||||||
|
p = p shr 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bits
|
||||||
|
} catch (e: Exception) {
|
||||||
|
24
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,374 @@
|
|||||||
|
package com.example.netshareecohub.ethernet
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
import android.net.Network
|
||||||
|
import android.net.NetworkCapabilities
|
||||||
|
import android.net.NetworkRequest
|
||||||
|
import com.example.netshareecohub.data.logging.Logger
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.isActive
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import com.example.netshareecohub.routing.DefaultShellExecutor
|
||||||
|
import java.io.BufferedReader
|
||||||
|
import java.io.File
|
||||||
|
import java.io.InputStreamReader
|
||||||
|
import java.net.Inet4Address
|
||||||
|
import java.net.NetworkInterface
|
||||||
|
import java.util.Collections
|
||||||
|
|
||||||
|
class EthernetMonitor(private val context: Context) {
|
||||||
|
|
||||||
|
private val tag = "EthernetMonitor"
|
||||||
|
private val scope = CoroutineScope(Dispatchers.IO + Job())
|
||||||
|
|
||||||
|
private val connectivityManager =
|
||||||
|
context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
|
||||||
|
|
||||||
|
private val _adapters = MutableStateFlow<List<EthernetAdapterInfo>>(emptyList())
|
||||||
|
val adapters: StateFlow<List<EthernetAdapterInfo>> = _adapters.asStateFlow()
|
||||||
|
|
||||||
|
private val _activeAdapter = MutableStateFlow<EthernetAdapterInfo?>(null)
|
||||||
|
val activeAdapter: StateFlow<EthernetAdapterInfo?> = _activeAdapter.asStateFlow()
|
||||||
|
|
||||||
|
private val _upstreamInfo = MutableStateFlow(UpstreamConnectivityInfo())
|
||||||
|
val upstreamInfo: StateFlow<UpstreamConnectivityInfo> = _upstreamInfo.asStateFlow()
|
||||||
|
|
||||||
|
private var monitorJob: Job? = null
|
||||||
|
private var networkCallback: ConnectivityManager.NetworkCallback? = null
|
||||||
|
|
||||||
|
private val shellExecutor = DefaultShellExecutor()
|
||||||
|
|
||||||
|
fun startMonitoring() {
|
||||||
|
if (monitorJob != null) return
|
||||||
|
|
||||||
|
Logger.info(tag, "Starting Real-Time Ethernet Adapter Monitoring")
|
||||||
|
|
||||||
|
registerNetworkCallback()
|
||||||
|
refresh()
|
||||||
|
|
||||||
|
monitorJob = scope.launch {
|
||||||
|
while (isActive) {
|
||||||
|
delay(1500)
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stopMonitoring() {
|
||||||
|
monitorJob?.cancel()
|
||||||
|
monitorJob = null
|
||||||
|
|
||||||
|
networkCallback?.let {
|
||||||
|
try {
|
||||||
|
connectivityManager?.unregisterNetworkCallback(it)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.warn(tag, "Error unregistering callback: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
networkCallback = null
|
||||||
|
Logger.info(tag, "Stopped Ethernet Adapter Monitoring")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun refresh() {
|
||||||
|
val upstream = checkUpstreamConnectivity()
|
||||||
|
_upstreamInfo.value = upstream
|
||||||
|
|
||||||
|
val newAdapters = scanEthernetAdapters(upstream)
|
||||||
|
val oldAdapters = _adapters.value
|
||||||
|
|
||||||
|
// Detect insertion / removal / link status changes
|
||||||
|
val newMap = newAdapters.associateBy { it.name }
|
||||||
|
val oldMap = oldAdapters.associateBy { it.name }
|
||||||
|
|
||||||
|
for (iface in newAdapters) {
|
||||||
|
val old = oldMap[iface.name]
|
||||||
|
if (old == null) {
|
||||||
|
Logger.info(tag, "Ethernet Adapter Connected/Inserted: ${iface.name} (Speed: ${iface.speedMbps}Mbps, MAC: ${iface.macAddress})")
|
||||||
|
} else {
|
||||||
|
if (!old.isUp && iface.isUp) {
|
||||||
|
Logger.info(tag, "Ethernet Link UP: ${iface.name} (${iface.speedMbps} Mbps, ${iface.duplex})")
|
||||||
|
} else if (old.isUp && !iface.isUp) {
|
||||||
|
Logger.warn(tag, "Ethernet Link DOWN: ${iface.name}")
|
||||||
|
}
|
||||||
|
if (old.operstate != iface.operstate) {
|
||||||
|
Logger.info(tag, "Operstate changed for ${iface.name}: ${old.operstate} -> ${iface.operstate}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (old in oldAdapters) {
|
||||||
|
if (!newMap.containsKey(old.name)) {
|
||||||
|
Logger.warn(tag, "Ethernet Adapter Removed/Disconnected: ${old.name}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_adapters.value = newAdapters
|
||||||
|
|
||||||
|
// Determine active Ethernet adapter
|
||||||
|
val primary = selectActiveAdapter(newAdapters)
|
||||||
|
if (_activeAdapter.value?.name != primary?.name || _activeAdapter.value?.isUp != primary?.isUp) {
|
||||||
|
if (primary != null) {
|
||||||
|
Logger.info(tag, "Active Ethernet Adapter selected: ${primary.name} (IP: ${primary.primaryIpv4 ?: "none"}, Operstate: ${primary.operstate})")
|
||||||
|
} else {
|
||||||
|
Logger.warn(tag, "No active Ethernet Adapter available")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_activeAdapter.value = primary
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun selectActiveAdapter(adapters: List<EthernetAdapterInfo>): EthernetAdapterInfo? {
|
||||||
|
if (adapters.isEmpty()) return null
|
||||||
|
|
||||||
|
val physicalAdapters = adapters.filter { isPhysicalEthernet(it.name) }
|
||||||
|
|
||||||
|
// 1. Prefer physical Ethernet that is UP and has carrier
|
||||||
|
return physicalAdapters.firstOrNull { it.isUp && it.carrier == 1 }
|
||||||
|
// 2. Or is simply UP
|
||||||
|
?: physicalAdapters.firstOrNull { it.isUp }
|
||||||
|
// 3. Or just return the first physical ethernet found (even if down)
|
||||||
|
?: physicalAdapters.firstOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isPhysicalEthernet(name: String): Boolean {
|
||||||
|
val lower = name.lowercase()
|
||||||
|
return lower.startsWith("eth") ||
|
||||||
|
lower.startsWith("usb") ||
|
||||||
|
lower.startsWith("rndis") ||
|
||||||
|
lower.startsWith("ncm") ||
|
||||||
|
lower.startsWith("enx") ||
|
||||||
|
lower.startsWith("enp") ||
|
||||||
|
lower.startsWith("lan")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun registerNetworkCallback() {
|
||||||
|
val builder = NetworkRequest.Builder()
|
||||||
|
val callback = object : ConnectivityManager.NetworkCallback() {
|
||||||
|
override fun onAvailable(network: Network) {
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onLost(network: Network) {
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
connectivityManager?.registerNetworkCallback(builder.build(), callback)
|
||||||
|
networkCallback = callback
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.error(tag, "Error registering network callback", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun checkUpstreamConnectivity(): UpstreamConnectivityInfo {
|
||||||
|
val cm = connectivityManager ?: return UpstreamConnectivityInfo(
|
||||||
|
type = UpstreamType.NONE,
|
||||||
|
isConnected = false,
|
||||||
|
isValidated = false,
|
||||||
|
details = "No connectivity manager"
|
||||||
|
)
|
||||||
|
|
||||||
|
val activeNetwork = cm.activeNetwork ?: return UpstreamConnectivityInfo(
|
||||||
|
type = UpstreamType.NONE,
|
||||||
|
isConnected = false,
|
||||||
|
isValidated = false,
|
||||||
|
details = "No active upstream network"
|
||||||
|
)
|
||||||
|
|
||||||
|
val caps = cm.getNetworkCapabilities(activeNetwork)
|
||||||
|
?: return UpstreamConnectivityInfo(
|
||||||
|
type = UpstreamType.NONE,
|
||||||
|
isConnected = false,
|
||||||
|
isValidated = false,
|
||||||
|
details = "No capabilities for active network"
|
||||||
|
)
|
||||||
|
|
||||||
|
val isValidated = caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
|
||||||
|
val isInternet = caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||||
|
|
||||||
|
val (type, typeName) = when {
|
||||||
|
caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> Pair(UpstreamType.WIFI, "Wi-Fi")
|
||||||
|
caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> Pair(UpstreamType.CELLULAR, "Cellular")
|
||||||
|
caps.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> Pair(UpstreamType.ETHERNET, "Upstream Ethernet")
|
||||||
|
else -> Pair(UpstreamType.OTHER, "Other")
|
||||||
|
}
|
||||||
|
|
||||||
|
val linkProperties = cm.getLinkProperties(activeNetwork)
|
||||||
|
val interfaceName = linkProperties?.interfaceName
|
||||||
|
|
||||||
|
return UpstreamConnectivityInfo(
|
||||||
|
type = type,
|
||||||
|
isConnected = isInternet,
|
||||||
|
isValidated = isValidated,
|
||||||
|
interfaceName = interfaceName,
|
||||||
|
details = "$typeName ($interfaceName, Connected: $isInternet, Validated: $isValidated)"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun scanEthernetAdapters(upstream: UpstreamConnectivityInfo): List<EthernetAdapterInfo> {
|
||||||
|
val list = mutableListOf<EthernetAdapterInfo>()
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. Sysfs based discovery
|
||||||
|
val netDirs = File("/sys/class/net/").listFiles() ?: emptyArray()
|
||||||
|
val sysfsIfaceNames = netDirs.map { it.name }
|
||||||
|
.filter { name -> name.matches(Regex("^(eth|usb|enx|enp|rndis|lan|lo).*")) }
|
||||||
|
|
||||||
|
// 2. NetworkInterface based discovery
|
||||||
|
val javaIfaces = NetworkInterface.getNetworkInterfaces()?.let { Collections.list(it) } ?: emptyList()
|
||||||
|
val javaIfaceNames = javaIfaces.map { it.name }
|
||||||
|
|
||||||
|
val allNames = (sysfsIfaceNames + javaIfaceNames).distinct()
|
||||||
|
|
||||||
|
for (name in allNames) {
|
||||||
|
if (!isEthernetLike(name) && !name.startsWith("lo")) continue
|
||||||
|
|
||||||
|
val iface = try { NetworkInterface.getByName(name) } catch (e: Exception) { null }
|
||||||
|
val isLoopback = iface?.isLoopback ?: name.startsWith("lo")
|
||||||
|
|
||||||
|
// Sysfs Properties
|
||||||
|
var operstate = SysfsReader.readOperstate(name)
|
||||||
|
val carrier = SysfsReader.readCarrier(name)
|
||||||
|
val sysfsSpeed = SysfsReader.readSpeed(name)
|
||||||
|
|
||||||
|
val isConnected = carrier == 1 || operstate.equals("up", ignoreCase = true) || sysfsSpeed > 0
|
||||||
|
val isUp = iface?.isUp ?: isConnected
|
||||||
|
|
||||||
|
if (operstate.isBlank()) {
|
||||||
|
operstate = if (isUp) "up" else "down"
|
||||||
|
}
|
||||||
|
|
||||||
|
val duplex = SysfsReader.readDuplex(name)
|
||||||
|
val stats = SysfsReader.readStats(name)
|
||||||
|
|
||||||
|
val macAddress = resolveMacAddress(iface, name)
|
||||||
|
|
||||||
|
val sysfsMtu = SysfsReader.readMtu(name)
|
||||||
|
val mtu = if (sysfsMtu > 0) sysfsMtu else iface?.mtu ?: 1500
|
||||||
|
|
||||||
|
val ipAddresses = mutableListOf<String>()
|
||||||
|
var primaryIpv4: String? = null
|
||||||
|
var netmaskStr: String? = null
|
||||||
|
|
||||||
|
if (iface != null) {
|
||||||
|
for (ia in iface.interfaceAddresses) {
|
||||||
|
val address = ia.address
|
||||||
|
val hostAddress = address?.hostAddress ?: continue
|
||||||
|
val cleanAddress = hostAddress.substringBefore('%')
|
||||||
|
ipAddresses.add(cleanAddress)
|
||||||
|
|
||||||
|
if (address is Inet4Address && primaryIpv4 == null) {
|
||||||
|
primaryIpv4 = cleanAddress
|
||||||
|
val prefix = ia.networkPrefixLength
|
||||||
|
netmaskStr = EthernetManager.prefixLengthToSubnetMask(prefix.toInt())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Retrieve gateway IP if active
|
||||||
|
var gatewayIp: String? = null
|
||||||
|
val linkProperties = (connectivityManager?.allNetworks ?: emptyArray())
|
||||||
|
.mapNotNull { connectivityManager?.getLinkProperties(it) }
|
||||||
|
.firstOrNull { it.interfaceName == name }
|
||||||
|
|
||||||
|
if (linkProperties != null) {
|
||||||
|
val defaultRoute = linkProperties.routes.firstOrNull { it.isDefaultRoute }
|
||||||
|
gatewayIp = defaultRoute?.gateway?.hostAddress
|
||||||
|
}
|
||||||
|
|
||||||
|
val role = when {
|
||||||
|
isLoopback -> InterfaceRole.LOOPBACK
|
||||||
|
upstream.interfaceName == name && upstream.isValidated -> InterfaceRole.UPSTREAM
|
||||||
|
isEthernetLike(name) -> InterfaceRole.LAN
|
||||||
|
else -> InterfaceRole.UNKNOWN
|
||||||
|
}
|
||||||
|
|
||||||
|
val displayName = formatDisplayName(name, role)
|
||||||
|
|
||||||
|
list.add(
|
||||||
|
EthernetAdapterInfo(
|
||||||
|
name = name,
|
||||||
|
displayName = displayName,
|
||||||
|
isUp = isUp,
|
||||||
|
operstate = operstate,
|
||||||
|
carrier = carrier,
|
||||||
|
macAddress = macAddress,
|
||||||
|
speedMbps = sysfsSpeed,
|
||||||
|
duplex = duplex,
|
||||||
|
mtu = mtu,
|
||||||
|
ipAddresses = ipAddresses,
|
||||||
|
primaryIpv4 = primaryIpv4,
|
||||||
|
netmask = netmaskStr,
|
||||||
|
gatewayIp = gatewayIp,
|
||||||
|
stats = stats,
|
||||||
|
role = role
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.error(tag, "Error scanning ethernet adapters", e)
|
||||||
|
}
|
||||||
|
|
||||||
|
return list
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isEthernetLike(name: String): Boolean {
|
||||||
|
val lower = name.lowercase()
|
||||||
|
// Physical Ethernet / USB OTG LAN interfaces only
|
||||||
|
return lower.startsWith("eth") ||
|
||||||
|
lower.startsWith("usb") ||
|
||||||
|
lower.startsWith("enx") ||
|
||||||
|
lower.startsWith("enp") ||
|
||||||
|
lower.startsWith("rndis") ||
|
||||||
|
lower.startsWith("lan")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun formatDisplayName(name: String, role: InterfaceRole): String {
|
||||||
|
val type = when {
|
||||||
|
name.startsWith("eth") -> "Ethernet"
|
||||||
|
name.startsWith("usb") -> "USB Tethering"
|
||||||
|
name.startsWith("rndis") -> "RNDIS Interface"
|
||||||
|
name.startsWith("wlan") -> "Wi-Fi Interface"
|
||||||
|
name.startsWith("lo") -> "Loopback"
|
||||||
|
else -> "Network Interface"
|
||||||
|
}
|
||||||
|
return "$name ($type)"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun resolveMacAddress(iface: NetworkInterface?, name: String): String {
|
||||||
|
// 1. Try Java NetworkInterface hardwareAddress
|
||||||
|
try {
|
||||||
|
val hwBytes = iface?.hardwareAddress
|
||||||
|
if (hwBytes != null && hwBytes.isNotEmpty()) {
|
||||||
|
val formatted = hwBytes.joinToString(":") { String.format("%02X", it) }
|
||||||
|
if (formatted != "00:00:00:00:00:00") return formatted
|
||||||
|
}
|
||||||
|
} catch (_: Exception) {}
|
||||||
|
|
||||||
|
// 2. Try Sysfs address
|
||||||
|
val sysfsMac = SysfsReader.readMacAddress(name)
|
||||||
|
if (sysfsMac != "00:00:00:00:00:00" && sysfsMac.isNotBlank()) {
|
||||||
|
return sysfsMac
|
||||||
|
}
|
||||||
|
|
||||||
|
// Removed expensive shell execution ('ip link show') which caused app crashes due to high frequency calls.
|
||||||
|
return "00:00:00:00:00:00"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun formatMacAddress(macBytes: ByteArray?): String {
|
||||||
|
if (macBytes == null || macBytes.isEmpty()) return "00:00:00:00:00:00"
|
||||||
|
return macBytes.joinToString(":") { String.format("%02X", it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.example.netshareecohub.ethernet
|
||||||
|
|
||||||
|
enum class SpeedMode(val label: String, val speedMbps: Int?, val duplex: String?) {
|
||||||
|
AUTO("Auto-Negotiation", null, null),
|
||||||
|
SPEED_10_HALF("10 Mbps Half Duplex", 10, "half"),
|
||||||
|
SPEED_10_FULL("10 Mbps Full Duplex", 10, "full"),
|
||||||
|
SPEED_100_HALF("100 Mbps Half Duplex", 100, "half"),
|
||||||
|
SPEED_100_FULL("100 Mbps Full Duplex", 100, "full"),
|
||||||
|
SPEED_1000_FULL("1000 Mbps Full Duplex", 1000, "full")
|
||||||
|
}
|
||||||
|
|
||||||
|
data class EthernetSpeedConfig(
|
||||||
|
val selectedMode: SpeedMode = SpeedMode.AUTO,
|
||||||
|
val currentSpeedMbps: Int = -1,
|
||||||
|
val currentDuplex: String = "unknown"
|
||||||
|
)
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.example.netshareecohub.ethernet
|
||||||
|
|
||||||
|
data class EthernetStats(
|
||||||
|
val rxBytes: Long = 0L,
|
||||||
|
val txBytes: Long = 0L,
|
||||||
|
val rxPackets: Long = 0L,
|
||||||
|
val txPackets: Long = 0L,
|
||||||
|
val rxErrors: Long = 0L,
|
||||||
|
val txErrors: Long = 0L
|
||||||
|
)
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
package com.example.netshareecohub.ethernet
|
||||||
|
|
||||||
|
import com.example.netshareecohub.data.logging.Logger
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
object SysfsReader {
|
||||||
|
|
||||||
|
private const val TAG = "SysfsReader"
|
||||||
|
private const val SYS_CLASS_NET = "/sys/class/net"
|
||||||
|
|
||||||
|
fun readOperstate(iface: String): String {
|
||||||
|
return readSysFile("$SYS_CLASS_NET/$iface/operstate")?.lowercase()?.trim() ?: "unknown"
|
||||||
|
}
|
||||||
|
|
||||||
|
fun readCarrier(iface: String): Int {
|
||||||
|
val raw = readSysFile("$SYS_CLASS_NET/$iface/carrier")?.trim() ?: return -1
|
||||||
|
return raw.toIntOrNull() ?: -1
|
||||||
|
}
|
||||||
|
|
||||||
|
fun readSpeed(iface: String): Int {
|
||||||
|
val raw = readSysFile("$SYS_CLASS_NET/$iface/speed")?.trim() ?: return -1
|
||||||
|
return raw.toIntOrNull() ?: -1
|
||||||
|
}
|
||||||
|
|
||||||
|
fun readDuplex(iface: String): String {
|
||||||
|
return readSysFile("$SYS_CLASS_NET/$iface/duplex")?.lowercase()?.trim() ?: "unknown"
|
||||||
|
}
|
||||||
|
|
||||||
|
fun readMacAddress(iface: String): String {
|
||||||
|
return readSysFile("$SYS_CLASS_NET/$iface/address")?.uppercase()?.trim() ?: "00:00:00:00:00:00"
|
||||||
|
}
|
||||||
|
|
||||||
|
fun readMtu(iface: String): Int {
|
||||||
|
val raw = readSysFile("$SYS_CLASS_NET/$iface/mtu")?.trim() ?: return 1500
|
||||||
|
return raw.toIntOrNull() ?: 1500
|
||||||
|
}
|
||||||
|
|
||||||
|
fun readStats(iface: String): EthernetStats {
|
||||||
|
val rxBytes = readSysLong("$SYS_CLASS_NET/$iface/statistics/rx_bytes")
|
||||||
|
val txBytes = readSysLong("$SYS_CLASS_NET/$iface/statistics/tx_bytes")
|
||||||
|
val rxPackets = readSysLong("$SYS_CLASS_NET/$iface/statistics/rx_packets")
|
||||||
|
val txPackets = readSysLong("$SYS_CLASS_NET/$iface/statistics/tx_packets")
|
||||||
|
val rxErrors = readSysLong("$SYS_CLASS_NET/$iface/statistics/rx_errors")
|
||||||
|
val txErrors = readSysLong("$SYS_CLASS_NET/$iface/statistics/tx_errors")
|
||||||
|
|
||||||
|
if (rxBytes != 0L || txBytes != 0L || rxPackets != 0L || txPackets != 0L) {
|
||||||
|
return EthernetStats(
|
||||||
|
rxBytes = rxBytes,
|
||||||
|
txBytes = txBytes,
|
||||||
|
rxPackets = rxPackets,
|
||||||
|
txPackets = txPackets,
|
||||||
|
rxErrors = rxErrors,
|
||||||
|
txErrors = txErrors
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback to /proc/net/dev
|
||||||
|
val procStatsMap = parseProcNetDev()
|
||||||
|
return procStatsMap[iface] ?: EthernetStats()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun parseProcNetDev(): Map<String, EthernetStats> {
|
||||||
|
val result = mutableMapOf<String, EthernetStats>()
|
||||||
|
val procDevFile = File("/proc/net/dev")
|
||||||
|
if (!procDevFile.exists() || !procDevFile.canRead()) {
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
procDevFile.useLines { lines ->
|
||||||
|
lines.drop(2).forEach { line ->
|
||||||
|
val trimmed = line.trim()
|
||||||
|
if (trimmed.isEmpty()) return@forEach
|
||||||
|
val parts = trimmed.split(Regex("\\s+"))
|
||||||
|
if (parts.size >= 11) {
|
||||||
|
val ifaceName = parts[0].removeSuffix(":")
|
||||||
|
val rxBytes = parts[1].toLongOrNull() ?: 0L
|
||||||
|
val rxPackets = parts[2].toLongOrNull() ?: 0L
|
||||||
|
val rxErrs = parts[3].toLongOrNull() ?: 0L
|
||||||
|
val txBytes = parts[9].toLongOrNull() ?: 0L
|
||||||
|
val txPackets = parts[10].toLongOrNull() ?: 0L
|
||||||
|
val txErrs = parts.getOrNull(11)?.toLongOrNull() ?: 0L
|
||||||
|
|
||||||
|
result[ifaceName] = EthernetStats(
|
||||||
|
rxBytes = rxBytes,
|
||||||
|
txBytes = txBytes,
|
||||||
|
rxPackets = rxPackets,
|
||||||
|
txPackets = txPackets,
|
||||||
|
rxErrors = rxErrs,
|
||||||
|
txErrors = txErrs
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.debug(TAG, "Error parsing /proc/net/dev: ${e.message}")
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun readSysFile(path: String): String? {
|
||||||
|
val file = File(path)
|
||||||
|
if (!file.exists()) return null
|
||||||
|
return try {
|
||||||
|
file.readText().trim()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun readSysLong(path: String): Long {
|
||||||
|
val content = readSysFile(path) ?: return 0L
|
||||||
|
return content.toLongOrNull() ?: 0L
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package com.example.netshareecohub.ethernet
|
||||||
|
|
||||||
|
enum class UpstreamType {
|
||||||
|
NONE,
|
||||||
|
WIFI,
|
||||||
|
CELLULAR,
|
||||||
|
ETHERNET,
|
||||||
|
OTHER
|
||||||
|
}
|
||||||
|
|
||||||
|
data class UpstreamConnectivityInfo(
|
||||||
|
val type: UpstreamType = UpstreamType.NONE,
|
||||||
|
val isConnected: Boolean = false,
|
||||||
|
val isValidated: Boolean = false,
|
||||||
|
val interfaceName: String? = null,
|
||||||
|
val details: String = "No internet connection"
|
||||||
|
)
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
package com.example.netshareecohub.network
|
||||||
|
|
||||||
|
import retrofit2.Response
|
||||||
|
import retrofit2.http.Body
|
||||||
|
import retrofit2.http.GET
|
||||||
|
import retrofit2.http.Header
|
||||||
|
import retrofit2.http.POST
|
||||||
|
|
||||||
|
data class LoginRequest(
|
||||||
|
val user_id: String,
|
||||||
|
val password: String
|
||||||
|
)
|
||||||
|
|
||||||
|
data class LoginResponse(
|
||||||
|
val success: Boolean,
|
||||||
|
val message: String,
|
||||||
|
val user: ApiUser?,
|
||||||
|
val token: String?
|
||||||
|
)
|
||||||
|
|
||||||
|
data class MeResponse(
|
||||||
|
val success: Boolean,
|
||||||
|
val message: String,
|
||||||
|
val user: ApiUserProfile?
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ApiUser(
|
||||||
|
val id: Int,
|
||||||
|
val user_id: String,
|
||||||
|
val name: String
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ApiUserProfile(
|
||||||
|
val id: Int,
|
||||||
|
val user_id: String,
|
||||||
|
val name: String,
|
||||||
|
val status: String?,
|
||||||
|
val created_at: String?,
|
||||||
|
val updated_at: String?
|
||||||
|
)
|
||||||
|
|
||||||
|
data class LogRequest(
|
||||||
|
val action: String,
|
||||||
|
val device: String,
|
||||||
|
val mac_address: String
|
||||||
|
)
|
||||||
|
|
||||||
|
data class LogResponse(
|
||||||
|
val success: Boolean,
|
||||||
|
val message: String
|
||||||
|
)
|
||||||
|
|
||||||
|
interface AuthApiService {
|
||||||
|
@POST("auth/login")
|
||||||
|
suspend fun login(@Body request: LoginRequest): Response<LoginResponse>
|
||||||
|
|
||||||
|
@GET("auth/me")
|
||||||
|
suspend fun getMe(@Header("Authorization") token: String): Response<MeResponse>
|
||||||
|
|
||||||
|
@POST("users/logs")
|
||||||
|
suspend fun sendLog(@Header("Authorization") token: String, @Body request: LogRequest): Response<LogResponse>
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package com.example.netshareecohub.network
|
||||||
|
|
||||||
|
import com.squareup.moshi.Moshi
|
||||||
|
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.logging.HttpLoggingInterceptor
|
||||||
|
import retrofit2.Retrofit
|
||||||
|
import retrofit2.converter.moshi.MoshiConverterFactory
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
object RetrofitClient {
|
||||||
|
private const val DEFAULT_BASE_URL = "https://unlock.ecohub.cc/api/"
|
||||||
|
|
||||||
|
private val moshi = Moshi.Builder()
|
||||||
|
.add(KotlinJsonAdapterFactory())
|
||||||
|
.build()
|
||||||
|
|
||||||
|
private val loggingInterceptor = HttpLoggingInterceptor().apply {
|
||||||
|
level = HttpLoggingInterceptor.Level.BODY
|
||||||
|
}
|
||||||
|
|
||||||
|
private val okHttpClient = OkHttpClient.Builder()
|
||||||
|
.addInterceptor(loggingInterceptor)
|
||||||
|
.connectTimeout(30, TimeUnit.SECONDS)
|
||||||
|
.readTimeout(30, TimeUnit.SECONDS)
|
||||||
|
.writeTimeout(30, TimeUnit.SECONDS)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
val authApiService: AuthApiService by lazy {
|
||||||
|
Retrofit.Builder()
|
||||||
|
.baseUrl(DEFAULT_BASE_URL)
|
||||||
|
.client(okHttpClient)
|
||||||
|
.addConverterFactory(MoshiConverterFactory.create(moshi))
|
||||||
|
.build()
|
||||||
|
.create(AuthApiService::class.java)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package com.example.netshareecohub.routing
|
||||||
|
|
||||||
|
object ChecksumUtil {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculates the standard 16-bit 1's complement sum over a byte array.
|
||||||
|
*/
|
||||||
|
fun computeChecksum(buffer: ByteArray, offset: Int, length: Int): Int {
|
||||||
|
var sum = 0L
|
||||||
|
var i = offset
|
||||||
|
val end = offset + length
|
||||||
|
|
||||||
|
while (i < end - 1) {
|
||||||
|
val word = ((buffer[i].toInt() and 0xFF) shl 8) or (buffer[i + 1].toInt() and 0xFF)
|
||||||
|
sum += word
|
||||||
|
i += 2
|
||||||
|
}
|
||||||
|
|
||||||
|
if (i < end) {
|
||||||
|
sum += (buffer[i].toInt() and 0xFF) shl 8
|
||||||
|
}
|
||||||
|
|
||||||
|
while ((sum ushr 16) > 0) {
|
||||||
|
sum = (sum and 0xFFFF) + (sum ushr 16)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (sum.inv() and 0xFFFF).toInt()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculates the transport layer (UDP / TCP) checksum with pseudo-header.
|
||||||
|
*/
|
||||||
|
fun computeTransportChecksum(
|
||||||
|
srcIp: String,
|
||||||
|
dstIp: String,
|
||||||
|
protocol: Int,
|
||||||
|
transportData: ByteArray
|
||||||
|
): Int {
|
||||||
|
val srcBytes = PacketParser.ipStringToBytes(srcIp)
|
||||||
|
val dstBytes = PacketParser.ipStringToBytes(dstIp)
|
||||||
|
val length = transportData.size
|
||||||
|
|
||||||
|
var sum = 0L
|
||||||
|
|
||||||
|
// Pseudo-Header: Src IP (4 bytes) + Dst IP (4 bytes)
|
||||||
|
for (i in 0..3 step 2) {
|
||||||
|
sum += ((srcBytes[i].toInt() and 0xFF) shl 8) or (srcBytes[i + 1].toInt() and 0xFF)
|
||||||
|
sum += ((dstBytes[i].toInt() and 0xFF) shl 8) or (dstBytes[i + 1].toInt() and 0xFF)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pseudo-Header: Zero (1 byte) + Protocol (1 byte) + Transport Length (2 bytes)
|
||||||
|
sum += protocol and 0xFF
|
||||||
|
sum += length and 0xFFFF
|
||||||
|
|
||||||
|
var i = 0
|
||||||
|
while (i < length - 1) {
|
||||||
|
val word = ((transportData[i].toInt() and 0xFF) shl 8) or (transportData[i + 1].toInt() and 0xFF)
|
||||||
|
sum += word
|
||||||
|
i += 2
|
||||||
|
}
|
||||||
|
|
||||||
|
if (i < length) {
|
||||||
|
sum += (transportData[i].toInt() and 0xFF) shl 8
|
||||||
|
}
|
||||||
|
|
||||||
|
while ((sum ushr 16) > 0) {
|
||||||
|
sum = (sum and 0xFFFF) + (sum ushr 16)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (sum.inv() and 0xFFFF).toInt()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifies that the IPv4 header checksum is valid.
|
||||||
|
*/
|
||||||
|
fun verifyIPv4Checksum(header: ByteArray, ihl: Int): Boolean {
|
||||||
|
if (header.size < ihl) return false
|
||||||
|
val computed = computeChecksum(header, 0, ihl)
|
||||||
|
return computed == 0
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package com.example.netshareecohub.routing
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
|
||||||
|
/** Single entry point for app-level tethering requests; no shell/root/reflection fallbacks. */
|
||||||
|
class EthernetTetheringController(private val context: Context) {
|
||||||
|
private val systemTetheringManager = SystemTetheringManager()
|
||||||
|
|
||||||
|
fun start(onResult: (Boolean, String) -> Unit) {
|
||||||
|
systemTetheringManager.startTethering(context) { success, message ->
|
||||||
|
onResult(success, message.orEmpty())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stop(onResult: (Boolean, String) -> Unit) {
|
||||||
|
systemTetheringManager.stopTethering(context) { success, message ->
|
||||||
|
onResult(success, message.orEmpty())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
package com.example.netshareecohub.routing
|
||||||
|
|
||||||
|
import android.R
|
||||||
|
import android.app.NotificationChannel
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.ServiceInfo
|
||||||
|
import android.net.VpnService
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.ParcelFileDescriptor
|
||||||
|
import androidx.core.app.NotificationCompat
|
||||||
|
import com.example.netshareecohub.data.logging.Logger
|
||||||
|
import com.example.netshareecohub.dhcp.DhcpServer
|
||||||
|
|
||||||
|
class NetShareVpnService : VpnService() {
|
||||||
|
|
||||||
|
private val tag = "NetShareVpnService"
|
||||||
|
private var vpnInterface: ParcelFileDescriptor? = null
|
||||||
|
private var tunNatEngine: TunNatEngine? = null
|
||||||
|
|
||||||
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
|
val action = intent?.action ?: ACTION_START
|
||||||
|
|
||||||
|
if (action == ACTION_STOP) {
|
||||||
|
stopVpn()
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
val lanIface = intent?.getStringExtra(EXTRA_LAN_IFACE) ?: "eth0"
|
||||||
|
val upstreamIface = intent?.getStringExtra(EXTRA_UPSTREAM_IFACE) ?: "wlan0"
|
||||||
|
val dnsServer = intent?.getStringExtra(EXTRA_DNS_SERVER) ?: "8.8.8.8"
|
||||||
|
|
||||||
|
Logger.info(tag, "Starting NetShare VPN Service ($lanIface -> $upstreamIface, DNS: $dnsServer)")
|
||||||
|
|
||||||
|
startForegroundNotification()
|
||||||
|
|
||||||
|
try {
|
||||||
|
val builder = Builder()
|
||||||
|
.setMtu(1500)
|
||||||
|
.addAddress("10.0.0.1", 24)
|
||||||
|
.addRoute("0.0.0.0", 0)
|
||||||
|
.addDnsServer(dnsServer)
|
||||||
|
.setSession("NetShareEcoHub Non-Root VPN")
|
||||||
|
|
||||||
|
val pfd = builder.establish()
|
||||||
|
if (pfd != null) {
|
||||||
|
vpnInterface = pfd
|
||||||
|
val engine = TunNatEngine(
|
||||||
|
fileDescriptor = pfd.fileDescriptor,
|
||||||
|
dnsServer = dnsServer,
|
||||||
|
vpnService = this,
|
||||||
|
dhcpServer = activeDhcpServer,
|
||||||
|
onStatsUpdated = { stats ->
|
||||||
|
latestStats = stats
|
||||||
|
}
|
||||||
|
)
|
||||||
|
tunNatEngine = engine
|
||||||
|
engine.start()
|
||||||
|
Logger.info(tag, "VPN Interface established successfully")
|
||||||
|
} else {
|
||||||
|
Logger.error(tag, "Failed to establish VPN interface (pfd is null)")
|
||||||
|
stopSelf()
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.error(tag, "Error establishing VPN Service", e)
|
||||||
|
stopSelf()
|
||||||
|
}
|
||||||
|
|
||||||
|
return START_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startForegroundNotification() {
|
||||||
|
val channelId = "netshare_vpn_channel"
|
||||||
|
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
|
||||||
|
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
val channel = NotificationChannel(
|
||||||
|
channelId,
|
||||||
|
"NetShare Non-Root VPN Routing",
|
||||||
|
NotificationManager.IMPORTANCE_LOW
|
||||||
|
).apply {
|
||||||
|
description = "Active non-root packet routing and NAT service"
|
||||||
|
}
|
||||||
|
notificationManager.createNotificationChannel(channel)
|
||||||
|
}
|
||||||
|
|
||||||
|
val notification = NotificationCompat.Builder(this, channelId)
|
||||||
|
.setContentTitle("NetShare EcoHub VPN Active")
|
||||||
|
.setContentText("Routing packets in Non-Root mode")
|
||||||
|
.setSmallIcon(R.drawable.stat_sys_download)
|
||||||
|
.setOngoing(true)
|
||||||
|
.setPriority(NotificationCompat.PRIORITY_LOW)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
|
startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE)
|
||||||
|
} else {
|
||||||
|
startForeground(NOTIFICATION_ID, notification)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stopVpn() {
|
||||||
|
Logger.info(tag, "Stopping NetShare VPN Service")
|
||||||
|
tunNatEngine?.stop()
|
||||||
|
tunNatEngine = null
|
||||||
|
|
||||||
|
try {
|
||||||
|
vpnInterface?.close()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.warn(tag, "Error closing VPN ParcelFileDescriptor: ${e.message}")
|
||||||
|
}
|
||||||
|
vpnInterface = null
|
||||||
|
|
||||||
|
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||||
|
stopSelf()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
super.onDestroy()
|
||||||
|
stopVpn()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val ACTION_START = "com.example.netshareecohub.routing.START_VPN"
|
||||||
|
const val ACTION_STOP = "com.example.netshareecohub.routing.STOP_VPN"
|
||||||
|
|
||||||
|
const val EXTRA_LAN_IFACE = "extra_lan_iface"
|
||||||
|
const val EXTRA_UPSTREAM_IFACE = "extra_upstream_iface"
|
||||||
|
const val EXTRA_DNS_SERVER = "extra_dns_server"
|
||||||
|
|
||||||
|
private const val NOTIFICATION_ID = 2001
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
var activeDhcpServer: DhcpServer? = null
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var latestStats: NatStats = NatStats()
|
||||||
|
|
||||||
|
fun getMetrics(): NatStats = latestStats
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
package com.example.netshareecohub.routing
|
||||||
|
|
||||||
|
object PacketBuilder {
|
||||||
|
|
||||||
|
fun buildIPv4Header(
|
||||||
|
srcIp: String,
|
||||||
|
dstIp: String,
|
||||||
|
protocol: Int,
|
||||||
|
payloadLength: Int,
|
||||||
|
id: Int = (1..65535).random(),
|
||||||
|
ttl: Int = 64,
|
||||||
|
tos: Int = 0
|
||||||
|
): ByteArray {
|
||||||
|
val header = ByteArray(20)
|
||||||
|
val ihl = 5
|
||||||
|
val totalLength = 20 + payloadLength
|
||||||
|
|
||||||
|
header[0] = ((4 shl 4) or ihl).toByte() // Version 4, IHL 5 (20 bytes)
|
||||||
|
header[1] = tos.toByte()
|
||||||
|
header[2] = ((totalLength ushr 8) and 0xFF).toByte()
|
||||||
|
header[3] = (totalLength and 0xFF).toByte()
|
||||||
|
header[4] = ((id ushr 8) and 0xFF).toByte()
|
||||||
|
header[5] = (id and 0xFF).toByte()
|
||||||
|
header[6] = 0x40.toByte() // Don't Fragment flag set
|
||||||
|
header[7] = 0.toByte()
|
||||||
|
header[8] = ttl.toByte()
|
||||||
|
header[9] = protocol.toByte()
|
||||||
|
header[10] = 0 // Checksum placeholder
|
||||||
|
header[11] = 0
|
||||||
|
|
||||||
|
val srcBytes = PacketParser.ipStringToBytes(srcIp)
|
||||||
|
val dstBytes = PacketParser.ipStringToBytes(dstIp)
|
||||||
|
System.arraycopy(srcBytes, 0, header, 12, 4)
|
||||||
|
System.arraycopy(dstBytes, 0, header, 16, 4)
|
||||||
|
|
||||||
|
val checksum = ChecksumUtil.computeChecksum(header, 0, 20)
|
||||||
|
header[10] = ((checksum ushr 8) and 0xFF).toByte()
|
||||||
|
header[11] = (checksum and 0xFF).toByte()
|
||||||
|
|
||||||
|
return header
|
||||||
|
}
|
||||||
|
|
||||||
|
fun buildUdpPacket(
|
||||||
|
srcIp: String,
|
||||||
|
dstIp: String,
|
||||||
|
srcPort: Int,
|
||||||
|
dstPort: Int,
|
||||||
|
payload: ByteArray
|
||||||
|
): ByteArray {
|
||||||
|
val udpLen = 8 + payload.size
|
||||||
|
val udpHeader = ByteArray(8)
|
||||||
|
udpHeader[0] = ((srcPort ushr 8) and 0xFF).toByte()
|
||||||
|
udpHeader[1] = (srcPort and 0xFF).toByte()
|
||||||
|
udpHeader[2] = ((dstPort ushr 8) and 0xFF).toByte()
|
||||||
|
udpHeader[3] = (dstPort and 0xFF).toByte()
|
||||||
|
udpHeader[4] = ((udpLen ushr 8) and 0xFF).toByte()
|
||||||
|
udpHeader[5] = (udpLen and 0xFF).toByte()
|
||||||
|
udpHeader[6] = 0
|
||||||
|
udpHeader[7] = 0
|
||||||
|
|
||||||
|
val fullUdp = ByteArray(udpLen)
|
||||||
|
System.arraycopy(udpHeader, 0, fullUdp, 0, 8)
|
||||||
|
System.arraycopy(payload, 0, fullUdp, 8, payload.size)
|
||||||
|
|
||||||
|
val checksum = ChecksumUtil.computeTransportChecksum(
|
||||||
|
srcIp = srcIp,
|
||||||
|
dstIp = dstIp,
|
||||||
|
protocol = 17, // UDP
|
||||||
|
transportData = fullUdp
|
||||||
|
)
|
||||||
|
val finalChecksum = if (checksum == 0) 0xFFFF else checksum
|
||||||
|
fullUdp[6] = ((finalChecksum ushr 8) and 0xFF).toByte()
|
||||||
|
fullUdp[7] = (finalChecksum and 0xFF).toByte()
|
||||||
|
|
||||||
|
val ipHeader = buildIPv4Header(srcIp, dstIp, 17, udpLen)
|
||||||
|
|
||||||
|
val fullPacket = ByteArray(20 + udpLen)
|
||||||
|
System.arraycopy(ipHeader, 0, fullPacket, 0, 20)
|
||||||
|
System.arraycopy(fullUdp, 0, fullPacket, 20, udpLen)
|
||||||
|
|
||||||
|
return fullPacket
|
||||||
|
}
|
||||||
|
|
||||||
|
fun buildIcmpEchoReply(
|
||||||
|
srcIp: String,
|
||||||
|
dstIp: String,
|
||||||
|
identifier: Int,
|
||||||
|
sequence: Int,
|
||||||
|
payload: ByteArray
|
||||||
|
): ByteArray {
|
||||||
|
val icmpLen = 8 + payload.size
|
||||||
|
val icmpData = ByteArray(icmpLen)
|
||||||
|
icmpData[0] = 0 // Echo Reply
|
||||||
|
icmpData[1] = 0 // Code 0
|
||||||
|
icmpData[2] = 0 // Checksum placeholder
|
||||||
|
icmpData[3] = 0
|
||||||
|
icmpData[4] = ((identifier ushr 8) and 0xFF).toByte()
|
||||||
|
icmpData[5] = (identifier and 0xFF).toByte()
|
||||||
|
icmpData[6] = ((sequence ushr 8) and 0xFF).toByte()
|
||||||
|
icmpData[7] = (sequence and 0xFF).toByte()
|
||||||
|
|
||||||
|
if (payload.isNotEmpty()) {
|
||||||
|
System.arraycopy(payload, 0, icmpData, 8, payload.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
val checksum = ChecksumUtil.computeChecksum(icmpData, 0, icmpLen)
|
||||||
|
icmpData[2] = ((checksum ushr 8) and 0xFF).toByte()
|
||||||
|
icmpData[3] = (checksum and 0xFF).toByte()
|
||||||
|
|
||||||
|
val ipHeader = buildIPv4Header(srcIp, dstIp, 1, icmpLen)
|
||||||
|
|
||||||
|
val fullPacket = ByteArray(20 + icmpLen)
|
||||||
|
System.arraycopy(ipHeader, 0, fullPacket, 0, 20)
|
||||||
|
System.arraycopy(icmpData, 0, fullPacket, 20, icmpLen)
|
||||||
|
|
||||||
|
return fullPacket
|
||||||
|
}
|
||||||
|
|
||||||
|
fun buildTcpPacket(
|
||||||
|
srcIp: String,
|
||||||
|
dstIp: String,
|
||||||
|
srcPort: Int,
|
||||||
|
dstPort: Int,
|
||||||
|
seqNumber: Long,
|
||||||
|
ackNumber: Long,
|
||||||
|
flags: Int,
|
||||||
|
windowSize: Int = 65535,
|
||||||
|
payload: ByteArray = byteArrayOf()
|
||||||
|
): ByteArray {
|
||||||
|
val tcpHeaderLen = 20
|
||||||
|
val tcpLen = tcpHeaderLen + payload.size
|
||||||
|
val tcpData = ByteArray(tcpLen)
|
||||||
|
|
||||||
|
tcpData[0] = ((srcPort ushr 8) and 0xFF).toByte()
|
||||||
|
tcpData[1] = (srcPort and 0xFF).toByte()
|
||||||
|
tcpData[2] = ((dstPort ushr 8) and 0xFF).toByte()
|
||||||
|
tcpData[3] = (dstPort and 0xFF).toByte()
|
||||||
|
|
||||||
|
tcpData[4] = ((seqNumber ushr 24) and 0xFF).toByte()
|
||||||
|
tcpData[5] = ((seqNumber ushr 16) and 0xFF).toByte()
|
||||||
|
tcpData[6] = ((seqNumber ushr 8) and 0xFF).toByte()
|
||||||
|
tcpData[7] = (seqNumber and 0xFF).toByte()
|
||||||
|
|
||||||
|
tcpData[8] = ((ackNumber ushr 24) and 0xFF).toByte()
|
||||||
|
tcpData[9] = ((ackNumber ushr 16) and 0xFF).toByte()
|
||||||
|
tcpData[10] = ((ackNumber ushr 8) and 0xFF).toByte()
|
||||||
|
tcpData[11] = (ackNumber and 0xFF).toByte()
|
||||||
|
|
||||||
|
tcpData[12] = ((5 shl 4) and 0xF0).toByte() // Data offset = 5 (20 bytes)
|
||||||
|
tcpData[13] = (flags and 0xFF).toByte()
|
||||||
|
|
||||||
|
tcpData[14] = ((windowSize ushr 8) and 0xFF).toByte()
|
||||||
|
tcpData[15] = (windowSize and 0xFF).toByte()
|
||||||
|
|
||||||
|
tcpData[16] = 0 // Checksum placeholder
|
||||||
|
tcpData[17] = 0
|
||||||
|
|
||||||
|
tcpData[18] = 0 // Urgent pointer
|
||||||
|
tcpData[19] = 0
|
||||||
|
|
||||||
|
if (payload.isNotEmpty()) {
|
||||||
|
System.arraycopy(payload, 0, tcpData, 20, payload.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
val checksum = ChecksumUtil.computeTransportChecksum(
|
||||||
|
srcIp = srcIp,
|
||||||
|
dstIp = dstIp,
|
||||||
|
protocol = 6, // TCP
|
||||||
|
transportData = tcpData
|
||||||
|
)
|
||||||
|
tcpData[16] = ((checksum ushr 8) and 0xFF).toByte()
|
||||||
|
tcpData[17] = (checksum and 0xFF).toByte()
|
||||||
|
|
||||||
|
val ipHeader = buildIPv4Header(srcIp, dstIp, 6, tcpLen)
|
||||||
|
|
||||||
|
val fullPacket = ByteArray(20 + tcpLen)
|
||||||
|
System.arraycopy(ipHeader, 0, fullPacket, 0, 20)
|
||||||
|
System.arraycopy(tcpData, 0, fullPacket, 20, tcpLen)
|
||||||
|
|
||||||
|
return fullPacket
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
package com.example.netshareecohub.routing
|
||||||
|
|
||||||
|
data class IPv4Header(
|
||||||
|
val version: Int,
|
||||||
|
val ihl: Int, // Header length in bytes
|
||||||
|
val tos: Int,
|
||||||
|
val totalLength: Int,
|
||||||
|
val id: Int,
|
||||||
|
val flags: Int,
|
||||||
|
val fragmentOffset: Int,
|
||||||
|
val ttl: Int,
|
||||||
|
val protocol: Int,
|
||||||
|
val checksum: Int,
|
||||||
|
val srcIp: String,
|
||||||
|
val dstIp: String,
|
||||||
|
val srcIpBytes: ByteArray,
|
||||||
|
val dstIpBytes: ByteArray
|
||||||
|
) {
|
||||||
|
override fun equals(other: Any?): Boolean {
|
||||||
|
if (this === other) return true
|
||||||
|
if (javaClass != other?.javaClass) return false
|
||||||
|
|
||||||
|
other as IPv4Header
|
||||||
|
|
||||||
|
if (version != other.version) return false
|
||||||
|
if (ihl != other.ihl) return false
|
||||||
|
if (tos != other.tos) return false
|
||||||
|
if (totalLength != other.totalLength) return false
|
||||||
|
if (id != other.id) return false
|
||||||
|
if (flags != other.flags) return false
|
||||||
|
if (fragmentOffset != other.fragmentOffset) return false
|
||||||
|
if (ttl != other.ttl) return false
|
||||||
|
if (protocol != other.protocol) return false
|
||||||
|
if (checksum != other.checksum) return false
|
||||||
|
if (srcIp != other.srcIp) return false
|
||||||
|
if (dstIp != other.dstIp) return false
|
||||||
|
if (!srcIpBytes.contentEquals(other.srcIpBytes)) return false
|
||||||
|
if (!dstIpBytes.contentEquals(other.dstIpBytes)) return false
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun hashCode(): Int {
|
||||||
|
var result = version
|
||||||
|
result = 31 * result + ihl
|
||||||
|
result = 31 * result + tos
|
||||||
|
result = 31 * result + totalLength
|
||||||
|
result = 31 * result + id
|
||||||
|
result = 31 * result + flags
|
||||||
|
result = 31 * result + fragmentOffset
|
||||||
|
result = 31 * result + ttl
|
||||||
|
result = 31 * result + protocol
|
||||||
|
result = 31 * result + checksum
|
||||||
|
result = 31 * result + srcIp.hashCode()
|
||||||
|
result = 31 * result + dstIp.hashCode()
|
||||||
|
result = 31 * result + srcIpBytes.contentHashCode()
|
||||||
|
result = 31 * result + dstIpBytes.contentHashCode()
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
data class UdpHeader(
|
||||||
|
val srcPort: Int,
|
||||||
|
val dstPort: Int,
|
||||||
|
val length: Int,
|
||||||
|
val checksum: Int
|
||||||
|
)
|
||||||
|
|
||||||
|
data class TcpHeader(
|
||||||
|
val srcPort: Int,
|
||||||
|
val dstPort: Int,
|
||||||
|
val sequenceNumber: Long,
|
||||||
|
val ackNumber: Long,
|
||||||
|
val dataOffset: Int, // Header length in bytes
|
||||||
|
val flags: Int,
|
||||||
|
val windowSize: Int,
|
||||||
|
val checksum: Int,
|
||||||
|
val urgentPointer: Int
|
||||||
|
)
|
||||||
|
|
||||||
|
data class IcmpHeader(
|
||||||
|
val type: Int,
|
||||||
|
val code: Int,
|
||||||
|
val checksum: Int
|
||||||
|
)
|
||||||
|
|
||||||
|
object PacketParser {
|
||||||
|
|
||||||
|
fun parseIPv4(buffer: ByteArray, length: Int): IPv4Header? {
|
||||||
|
if (length < 20) return null
|
||||||
|
val versionIhl = buffer[0].toInt() and 0xFF
|
||||||
|
val version = versionIhl ushr 4
|
||||||
|
if (version != 4) return null
|
||||||
|
val ihl = (versionIhl and 0x0F) * 4
|
||||||
|
if (ihl < 20 || ihl > length) return null
|
||||||
|
|
||||||
|
val tos = buffer[1].toInt() and 0xFF
|
||||||
|
val totalLength = ((buffer[2].toInt() and 0xFF) shl 8) or (buffer[3].toInt() and 0xFF)
|
||||||
|
val id = ((buffer[4].toInt() and 0xFF) shl 8) or (buffer[5].toInt() and 0xFF)
|
||||||
|
val flagsAndOffset = ((buffer[6].toInt() and 0xFF) shl 8) or (buffer[7].toInt() and 0xFF)
|
||||||
|
val flags = flagsAndOffset ushr 13
|
||||||
|
val fragmentOffset = flagsAndOffset and 0x1FFF
|
||||||
|
val ttl = buffer[8].toInt() and 0xFF
|
||||||
|
val protocol = buffer[9].toInt() and 0xFF
|
||||||
|
val checksum = ((buffer[10].toInt() and 0xFF) shl 8) or (buffer[11].toInt() and 0xFF)
|
||||||
|
|
||||||
|
val srcIpBytes = buffer.copyOfRange(12, 16)
|
||||||
|
val dstIpBytes = buffer.copyOfRange(16, 20)
|
||||||
|
|
||||||
|
val srcIp = bytesToIpString(srcIpBytes)
|
||||||
|
val dstIp = bytesToIpString(dstIpBytes)
|
||||||
|
|
||||||
|
return IPv4Header(
|
||||||
|
version = version,
|
||||||
|
ihl = ihl,
|
||||||
|
tos = tos,
|
||||||
|
totalLength = totalLength,
|
||||||
|
id = id,
|
||||||
|
flags = flags,
|
||||||
|
fragmentOffset = fragmentOffset,
|
||||||
|
ttl = ttl,
|
||||||
|
protocol = protocol,
|
||||||
|
checksum = checksum,
|
||||||
|
srcIp = srcIp,
|
||||||
|
dstIp = dstIp,
|
||||||
|
srcIpBytes = srcIpBytes,
|
||||||
|
dstIpBytes = dstIpBytes
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun parseUdp(buffer: ByteArray, ipHeaderLength: Int, totalLength: Int): UdpHeader? {
|
||||||
|
if (totalLength < ipHeaderLength + 8) return null
|
||||||
|
val offset = ipHeaderLength
|
||||||
|
val srcPort = ((buffer[offset].toInt() and 0xFF) shl 8) or (buffer[offset + 1].toInt() and 0xFF)
|
||||||
|
val dstPort = ((buffer[offset + 2].toInt() and 0xFF) shl 8) or (buffer[offset + 3].toInt() and 0xFF)
|
||||||
|
val length = ((buffer[offset + 4].toInt() and 0xFF) shl 8) or (buffer[offset + 5].toInt() and 0xFF)
|
||||||
|
val checksum = ((buffer[offset + 6].toInt() and 0xFF) shl 8) or (buffer[offset + 7].toInt() and 0xFF)
|
||||||
|
|
||||||
|
return UdpHeader(srcPort, dstPort, length, checksum)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun parseTcp(buffer: ByteArray, ipHeaderLength: Int, totalLength: Int): TcpHeader? {
|
||||||
|
if (totalLength < ipHeaderLength + 20) return null
|
||||||
|
val offset = ipHeaderLength
|
||||||
|
val srcPort = ((buffer[offset].toInt() and 0xFF) shl 8) or (buffer[offset + 1].toInt() and 0xFF)
|
||||||
|
val dstPort = ((buffer[offset + 2].toInt() and 0xFF) shl 8) or (buffer[offset + 3].toInt() and 0xFF)
|
||||||
|
|
||||||
|
val seq = (((buffer[offset + 4].toLong() and 0xFF) shl 24) or
|
||||||
|
((buffer[offset + 5].toLong() and 0xFF) shl 16) or
|
||||||
|
((buffer[offset + 6].toLong() and 0xFF) shl 8) or
|
||||||
|
(buffer[offset + 7].toLong() and 0xFF))
|
||||||
|
|
||||||
|
val ack = (((buffer[offset + 8].toLong() and 0xFF) shl 24) or
|
||||||
|
((buffer[offset + 9].toLong() and 0xFF) shl 16) or
|
||||||
|
((buffer[offset + 10].toLong() and 0xFF) shl 8) or
|
||||||
|
(buffer[offset + 11].toLong() and 0xFF))
|
||||||
|
|
||||||
|
val dataOffsetRes = buffer[offset + 12].toInt() and 0xFF
|
||||||
|
val dataOffset = (dataOffsetRes ushr 4) * 4
|
||||||
|
val flags = buffer[offset + 13].toInt() and 0xFF
|
||||||
|
val window = ((buffer[offset + 14].toInt() and 0xFF) shl 8) or (buffer[offset + 15].toInt() and 0xFF)
|
||||||
|
val checksum = ((buffer[offset + 16].toInt() and 0xFF) shl 8) or (buffer[offset + 17].toInt() and 0xFF)
|
||||||
|
val urgentPointer = ((buffer[offset + 18].toInt() and 0xFF) shl 8) or (buffer[offset + 19].toInt() and 0xFF)
|
||||||
|
|
||||||
|
return TcpHeader(srcPort, dstPort, seq, ack, dataOffset, flags, window, checksum, urgentPointer)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun parseIcmp(buffer: ByteArray, ipHeaderLength: Int, totalLength: Int): IcmpHeader? {
|
||||||
|
if (totalLength < ipHeaderLength + 4) return null
|
||||||
|
val offset = ipHeaderLength
|
||||||
|
val type = buffer[offset].toInt() and 0xFF
|
||||||
|
val code = buffer[offset + 1].toInt() and 0xFF
|
||||||
|
val checksum = ((buffer[offset + 2].toInt() and 0xFF) shl 8) or (buffer[offset + 3].toInt() and 0xFF)
|
||||||
|
|
||||||
|
return IcmpHeader(type, code, checksum)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun bytesToIpString(bytes: ByteArray, offset: Int = 0): String {
|
||||||
|
return "${bytes[offset].toInt() and 0xFF}.${bytes[offset + 1].toInt() and 0xFF}.${bytes[offset + 2].toInt() and 0xFF}.${bytes[offset + 3].toInt() and 0xFF}"
|
||||||
|
}
|
||||||
|
|
||||||
|
fun ipStringToBytes(ip: String): ByteArray {
|
||||||
|
val parts = ip.split(".")
|
||||||
|
require(parts.size == 4) { "Invalid IP address: $ip" }
|
||||||
|
return byteArrayOf(
|
||||||
|
parts[0].toInt().toByte(),
|
||||||
|
parts[1].toInt().toByte(),
|
||||||
|
parts[2].toInt().toByte(),
|
||||||
|
parts[3].toInt().toByte()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
package com.example.netshareecohub.routing
|
||||||
|
|
||||||
|
import com.example.netshareecohub.data.logging.Logger
|
||||||
|
|
||||||
|
class RootRoutingManager(
|
||||||
|
val shellExecutor: ShellExecutor = DefaultShellExecutor()
|
||||||
|
) {
|
||||||
|
private val tag = "RootRoutingManager"
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var isRoutingActive = false
|
||||||
|
|
||||||
|
private val configuredRules = mutableListOf<String>()
|
||||||
|
|
||||||
|
fun isRootAvailable(): Boolean {
|
||||||
|
return shellExecutor.isRootAvailable()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun startRouting(
|
||||||
|
lanInterface: String,
|
||||||
|
upstreamInterface: String,
|
||||||
|
dnsServer: String = "8.8.8.8",
|
||||||
|
gatewayIpCidr: String = "192.168.50.1/24",
|
||||||
|
dhcpFallbackPort: Int = 6700
|
||||||
|
): Boolean {
|
||||||
|
if (!isRootAvailable()) {
|
||||||
|
Logger.error(tag, "Root access is not available")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.info(tag, "Starting Root IP Tables routing ($lanInterface -> $upstreamInterface, Gateway IP: $gatewayIpCidr, DNS: $dnsServer)")
|
||||||
|
|
||||||
|
val commands = mutableListOf<String>()
|
||||||
|
|
||||||
|
// 1. Enable IP Forwarding
|
||||||
|
commands.add("sysctl -w net.ipv4.ip_forward=1 || echo 1 > /proc/sys/net/ipv4/ip_forward")
|
||||||
|
|
||||||
|
// 2. Assign Gateway IP address to LAN Interface (eth0)
|
||||||
|
commands.add("ip addr add $gatewayIpCidr dev $lanInterface 2>/dev/null || ip addr replace $gatewayIpCidr dev $lanInterface")
|
||||||
|
commands.add("ip link set $lanInterface up")
|
||||||
|
|
||||||
|
// 3. iptables -t nat -A POSTROUTING -o <upstream> -j MASQUERADE
|
||||||
|
val masqueradeCmd = "iptables -t nat -A POSTROUTING -o $upstreamInterface -j MASQUERADE"
|
||||||
|
commands.add(masqueradeCmd)
|
||||||
|
|
||||||
|
// 4. iptables -A FORWARD -i <lan_iface> -o <upstream> -j ACCEPT
|
||||||
|
val forwardLanUpstreamCmd = "iptables -A FORWARD -i $lanInterface -o $upstreamInterface -j ACCEPT"
|
||||||
|
commands.add(forwardLanUpstreamCmd)
|
||||||
|
|
||||||
|
// 5. iptables -A FORWARD -i <upstream> -o <lan_iface> -m state --state RELATED,ESTABLISHED -j ACCEPT
|
||||||
|
val forwardUpstreamLanCmd = "iptables -A FORWARD -i $upstreamInterface -o $lanInterface -m state --state RELATED,ESTABLISHED -j ACCEPT"
|
||||||
|
commands.add(forwardUpstreamLanCmd)
|
||||||
|
|
||||||
|
// 6. Redirect DHCP port 67 UDP packets on lanInterface to local fallback port
|
||||||
|
val dhcpRedirectCmd = "iptables -t nat -A PREROUTING -i $lanInterface -p udp --dport 67 -j REDIRECT --to-ports $dhcpFallbackPort"
|
||||||
|
commands.add(dhcpRedirectCmd)
|
||||||
|
|
||||||
|
// 7. DNS DNAT Redirect if dnsServer is provided
|
||||||
|
val dnsRedirectCmd = if (dnsServer.isNotBlank()) {
|
||||||
|
"iptables -t nat -A PREROUTING -i $lanInterface -p udp --dport 53 -j DNAT --to-destination $dnsServer:53"
|
||||||
|
} else null
|
||||||
|
|
||||||
|
dnsRedirectCmd?.let { commands.add(it) }
|
||||||
|
|
||||||
|
val result = shellExecutor.executeSu(commands)
|
||||||
|
if (result.isSuccess) {
|
||||||
|
configuredRules.clear()
|
||||||
|
configuredRules.add(masqueradeCmd)
|
||||||
|
configuredRules.add(forwardLanUpstreamCmd)
|
||||||
|
configuredRules.add(forwardUpstreamLanCmd)
|
||||||
|
configuredRules.add(dhcpRedirectCmd)
|
||||||
|
dnsRedirectCmd?.let { configuredRules.add(it) }
|
||||||
|
|
||||||
|
isRoutingActive = true
|
||||||
|
Logger.info(tag, "Root routing successfully configured and active. Output: ${result.stdout}")
|
||||||
|
return true
|
||||||
|
} else {
|
||||||
|
Logger.error(tag, "Failed to configure root routing. Error output: ${result.stderr}")
|
||||||
|
stopRouting(lanInterface, upstreamInterface, dnsServer, dhcpFallbackPort)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun stopRouting(
|
||||||
|
lanInterface: String,
|
||||||
|
upstreamInterface: String,
|
||||||
|
dnsServer: String = "8.8.8.8",
|
||||||
|
dhcpFallbackPort: Int = 6700
|
||||||
|
): Boolean {
|
||||||
|
Logger.info(tag, "Stopping Root routing ($lanInterface -> $upstreamInterface)")
|
||||||
|
|
||||||
|
val commands = mutableListOf<String>()
|
||||||
|
|
||||||
|
// Remove created rules using -D
|
||||||
|
commands.add("iptables -t nat -D PREROUTING -i $lanInterface -p udp --dport 67 -j REDIRECT --to-ports $dhcpFallbackPort")
|
||||||
|
commands.add("iptables -t nat -D POSTROUTING -o $upstreamInterface -j MASQUERADE")
|
||||||
|
commands.add("iptables -D FORWARD -i $lanInterface -o $upstreamInterface -j ACCEPT")
|
||||||
|
commands.add("iptables -D FORWARD -i $upstreamInterface -o $lanInterface -m state --state RELATED,ESTABLISHED -j ACCEPT")
|
||||||
|
if (dnsServer.isNotBlank()) {
|
||||||
|
commands.add("iptables -t nat -D PREROUTING -i $lanInterface -p udp --dport 53 -j DNAT --to-destination $dnsServer:53")
|
||||||
|
}
|
||||||
|
|
||||||
|
shellExecutor.executeSu(commands)
|
||||||
|
configuredRules.clear()
|
||||||
|
isRoutingActive = false
|
||||||
|
Logger.info(tag, "Root routing teardown completed")
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isRoutingActive(): Boolean = isRoutingActive
|
||||||
|
|
||||||
|
fun getConfiguredRules(): List<String> = configuredRules.toList()
|
||||||
|
}
|
||||||
@@ -0,0 +1,274 @@
|
|||||||
|
package com.example.netshareecohub.routing
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Build
|
||||||
|
import com.example.netshareecohub.data.logging.Logger
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.isActive
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
enum class RoutingMode {
|
||||||
|
NON_ROOT_VPN,
|
||||||
|
ROOT_IPTABLES,
|
||||||
|
SYSTEM_TETHERING
|
||||||
|
}
|
||||||
|
|
||||||
|
enum class RoutingState {
|
||||||
|
STOPPED,
|
||||||
|
STARTING,
|
||||||
|
ACTIVE,
|
||||||
|
ERROR
|
||||||
|
}
|
||||||
|
|
||||||
|
data class RoutingStatus(
|
||||||
|
val mode: RoutingMode = RoutingMode.NON_ROOT_VPN,
|
||||||
|
val state: RoutingState = RoutingState.STOPPED,
|
||||||
|
val upstreamInterface: String? = null,
|
||||||
|
val lanInterface: String? = null,
|
||||||
|
val rxBytes: Long = 0L,
|
||||||
|
val txBytes: Long = 0L,
|
||||||
|
val rxPackets: Long = 0L,
|
||||||
|
val txPackets: Long = 0L,
|
||||||
|
val dnsServer: String = "8.8.8.8",
|
||||||
|
val errorMessage: String? = null
|
||||||
|
)
|
||||||
|
|
||||||
|
class RoutingManager(
|
||||||
|
val rootRoutingManager: RootRoutingManager = RootRoutingManager(),
|
||||||
|
val systemTetheringManager: SystemTetheringManager = SystemTetheringManager()
|
||||||
|
) {
|
||||||
|
private val tag = "RoutingManager"
|
||||||
|
private val scope = CoroutineScope(Dispatchers.IO + Job())
|
||||||
|
|
||||||
|
private val _status = MutableStateFlow(RoutingStatus())
|
||||||
|
val status: StateFlow<RoutingStatus> = _status.asStateFlow()
|
||||||
|
|
||||||
|
private var metricsJob: Job? = null
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun startRouting(
|
||||||
|
context: Context? = null,
|
||||||
|
mode: RoutingMode,
|
||||||
|
lanInterface: String,
|
||||||
|
upstreamInterface: String,
|
||||||
|
dnsServer: String = "8.8.8.8"
|
||||||
|
) {
|
||||||
|
if (_status.value.state == RoutingState.ACTIVE || _status.value.state == RoutingState.STARTING) {
|
||||||
|
Logger.warn(tag, "Routing is already active or starting. Stopping current session first.")
|
||||||
|
stopRouting(context)
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.info(tag, "Starting routing engine in mode: $mode ($lanInterface -> $upstreamInterface, DNS: $dnsServer)")
|
||||||
|
_status.value = RoutingStatus(
|
||||||
|
mode = mode,
|
||||||
|
state = RoutingState.STARTING,
|
||||||
|
lanInterface = lanInterface,
|
||||||
|
upstreamInterface = upstreamInterface,
|
||||||
|
dnsServer = dnsServer
|
||||||
|
)
|
||||||
|
|
||||||
|
when (mode) {
|
||||||
|
RoutingMode.ROOT_IPTABLES -> {
|
||||||
|
val success = rootRoutingManager.startRouting(
|
||||||
|
lanInterface = lanInterface,
|
||||||
|
upstreamInterface = upstreamInterface,
|
||||||
|
dnsServer = dnsServer
|
||||||
|
)
|
||||||
|
if (success) {
|
||||||
|
_status.value = _status.value.copy(
|
||||||
|
state = RoutingState.ACTIVE,
|
||||||
|
errorMessage = null
|
||||||
|
)
|
||||||
|
startMetricsMonitoring()
|
||||||
|
Logger.info(tag, "Root IP Tables routing successfully started")
|
||||||
|
} else {
|
||||||
|
val err = "Failed to start Root IP Tables routing"
|
||||||
|
_status.value = _status.value.copy(
|
||||||
|
state = RoutingState.ERROR,
|
||||||
|
errorMessage = err
|
||||||
|
)
|
||||||
|
Logger.error(tag, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RoutingMode.NON_ROOT_VPN -> {
|
||||||
|
try {
|
||||||
|
if (context == null) throw IllegalArgumentException("Context is required for NON_ROOT_VPN mode")
|
||||||
|
val intent = Intent(context, NetShareVpnService::class.java).apply {
|
||||||
|
action = NetShareVpnService.ACTION_START
|
||||||
|
putExtra(NetShareVpnService.EXTRA_LAN_IFACE, lanInterface)
|
||||||
|
putExtra(NetShareVpnService.EXTRA_UPSTREAM_IFACE, upstreamInterface)
|
||||||
|
putExtra(NetShareVpnService.EXTRA_DNS_SERVER, dnsServer)
|
||||||
|
}
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
context.startForegroundService(intent)
|
||||||
|
} else {
|
||||||
|
context.startService(intent)
|
||||||
|
}
|
||||||
|
_status.value = _status.value.copy(
|
||||||
|
state = RoutingState.ACTIVE,
|
||||||
|
errorMessage = null
|
||||||
|
)
|
||||||
|
startMetricsMonitoring()
|
||||||
|
Logger.info(tag, "Non-Root VPN Service started")
|
||||||
|
} catch (e: Exception) {
|
||||||
|
val err = "Failed to start VPN Service: ${e.message}"
|
||||||
|
_status.value = _status.value.copy(
|
||||||
|
state = RoutingState.ERROR,
|
||||||
|
errorMessage = err
|
||||||
|
)
|
||||||
|
Logger.error(tag, err, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RoutingMode.SYSTEM_TETHERING -> {
|
||||||
|
if (context == null) {
|
||||||
|
val error = "A Context is required to request system Ethernet Tethering."
|
||||||
|
_status.value = _status.value.copy(state = RoutingState.ERROR, errorMessage = error)
|
||||||
|
Logger.error(tag, error)
|
||||||
|
} else {
|
||||||
|
systemTetheringManager.startTethering(
|
||||||
|
context,
|
||||||
|
SystemTetheringManager.TETHERING_ETHERNET
|
||||||
|
) { success, message ->
|
||||||
|
_status.value = _status.value.copy(
|
||||||
|
state = if (success) RoutingState.ACTIVE else RoutingState.ERROR,
|
||||||
|
errorMessage = if (success) null else (message ?: "Ethernet Tethering start failed")
|
||||||
|
)
|
||||||
|
if (success) startMetricsMonitoring()
|
||||||
|
Logger.info(tag, message ?: "Ethernet Tethering result received")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun stopRouting(context: Context?) {
|
||||||
|
val currentStatus = _status.value
|
||||||
|
if (currentStatus.state == RoutingState.STOPPED) return
|
||||||
|
|
||||||
|
Logger.info(tag, "Stopping routing engine for mode: ${currentStatus.mode}")
|
||||||
|
stopMetricsMonitoring()
|
||||||
|
|
||||||
|
val lan = currentStatus.lanInterface ?: ""
|
||||||
|
val upstream = currentStatus.upstreamInterface ?: ""
|
||||||
|
val dns = currentStatus.dnsServer
|
||||||
|
|
||||||
|
when (currentStatus.mode) {
|
||||||
|
RoutingMode.ROOT_IPTABLES -> {
|
||||||
|
rootRoutingManager.stopRouting(lan, upstream, dns)
|
||||||
|
}
|
||||||
|
RoutingMode.NON_ROOT_VPN -> {
|
||||||
|
try {
|
||||||
|
if (context != null) {
|
||||||
|
val intent = Intent(context, NetShareVpnService::class.java).apply {
|
||||||
|
action = NetShareVpnService.ACTION_STOP
|
||||||
|
}
|
||||||
|
context.startService(intent)
|
||||||
|
} else {
|
||||||
|
Logger.warn(tag, "Cannot stop NON_ROOT_VPN without a Context")
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.warn(tag, "Error stopping VPN Service: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
RoutingMode.SYSTEM_TETHERING -> {
|
||||||
|
if (context == null) {
|
||||||
|
val error = "Context is null; cannot request Ethernet Tethering stop."
|
||||||
|
_status.value = currentStatus.copy(state = RoutingState.ERROR, errorMessage = error)
|
||||||
|
Logger.warn(tag, error)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
systemTetheringManager.stopTethering(
|
||||||
|
context,
|
||||||
|
SystemTetheringManager.TETHERING_ETHERNET
|
||||||
|
) { success, message ->
|
||||||
|
_status.value = if (success) {
|
||||||
|
RoutingStatus(
|
||||||
|
mode = currentStatus.mode,
|
||||||
|
state = RoutingState.STOPPED,
|
||||||
|
upstreamInterface = currentStatus.upstreamInterface,
|
||||||
|
lanInterface = currentStatus.lanInterface,
|
||||||
|
dnsServer = currentStatus.dnsServer
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
currentStatus.copy(
|
||||||
|
state = RoutingState.ERROR,
|
||||||
|
errorMessage = message ?: "Ethernet Tethering stop could not be verified"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Logger.info(tag, message ?: "Ethernet Tethering stop result received")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_status.value = RoutingStatus(
|
||||||
|
mode = currentStatus.mode,
|
||||||
|
state = RoutingState.STOPPED,
|
||||||
|
upstreamInterface = currentStatus.upstreamInterface,
|
||||||
|
lanInterface = currentStatus.lanInterface,
|
||||||
|
dnsServer = currentStatus.dnsServer
|
||||||
|
)
|
||||||
|
Logger.info(tag, "Routing engine stopped")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun switchMode(
|
||||||
|
context: Context,
|
||||||
|
newMode: RoutingMode,
|
||||||
|
lanInterface: String,
|
||||||
|
upstreamInterface: String,
|
||||||
|
dnsServer: String = "8.8.8.8"
|
||||||
|
) {
|
||||||
|
Logger.info(tag, "Switching routing mode from ${_status.value.mode} to $newMode")
|
||||||
|
stopRouting(context)
|
||||||
|
startRouting(context, newMode, lanInterface, upstreamInterface, dnsServer)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun updateMetrics(rxBytes: Long, txBytes: Long, rxPackets: Long, txPackets: Long) {
|
||||||
|
_status.value = _status.value.copy(
|
||||||
|
rxBytes = rxBytes,
|
||||||
|
txBytes = txBytes,
|
||||||
|
rxPackets = rxPackets,
|
||||||
|
txPackets = txPackets
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun updateUpstreamInterface(upstreamInterface: String?) {
|
||||||
|
if (_status.value.upstreamInterface != upstreamInterface) {
|
||||||
|
Logger.info(tag, "Upstream interface changed to: $upstreamInterface")
|
||||||
|
_status.value = _status.value.copy(upstreamInterface = upstreamInterface)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startMetricsMonitoring() {
|
||||||
|
stopMetricsMonitoring()
|
||||||
|
metricsJob = scope.launch {
|
||||||
|
while (isActive) {
|
||||||
|
delay(2000)
|
||||||
|
if (_status.value.mode == RoutingMode.NON_ROOT_VPN) {
|
||||||
|
val stats = NetShareVpnService.getMetrics()
|
||||||
|
updateMetrics(
|
||||||
|
rxBytes = stats.rxBytes,
|
||||||
|
txBytes = stats.txBytes,
|
||||||
|
rxPackets = stats.rxPackets,
|
||||||
|
txPackets = stats.txPackets
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stopMetricsMonitoring() {
|
||||||
|
metricsJob?.cancel()
|
||||||
|
metricsJob = null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
package com.example.netshareecohub.routing
|
||||||
|
|
||||||
|
import com.example.netshareecohub.data.logging.Logger
|
||||||
|
import java.io.BufferedReader
|
||||||
|
import java.io.DataOutputStream
|
||||||
|
|
||||||
|
data class CommandResult(
|
||||||
|
val exitCode: Int,
|
||||||
|
val stdout: String,
|
||||||
|
val stderr: String
|
||||||
|
) {
|
||||||
|
val isSuccess: Boolean get() = exitCode == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ShellExecutor {
|
||||||
|
fun isRootAvailable(): Boolean
|
||||||
|
fun executeSu(command: String): CommandResult
|
||||||
|
fun executeSu(commands: List<String>): CommandResult
|
||||||
|
fun executeSh(command: String): CommandResult
|
||||||
|
}
|
||||||
|
|
||||||
|
class DefaultShellExecutor : ShellExecutor {
|
||||||
|
private val tag = "ShellExecutor"
|
||||||
|
|
||||||
|
override fun isRootAvailable(): Boolean {
|
||||||
|
// -c "id" will output user id. We run "su -c id" directly using ProcessBuilder
|
||||||
|
// to properly trigger the Magisk/SuperSU prompt.
|
||||||
|
return try {
|
||||||
|
val process = ProcessBuilder("su", "-c", "id").redirectErrorStream(true).start()
|
||||||
|
val stdout = process.inputStream.bufferedReader().use(BufferedReader::readText)
|
||||||
|
process.waitFor() == 0 && stdout.contains("uid=0")
|
||||||
|
} catch (_: Exception) {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun executeSu(command: String): CommandResult {
|
||||||
|
return executeSu(listOf(command))
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun executeSu(commands: List<String>): CommandResult {
|
||||||
|
var process: Process? = null
|
||||||
|
return try {
|
||||||
|
process = ProcessBuilder("su").redirectErrorStream(false).start()
|
||||||
|
val os = DataOutputStream(process.outputStream)
|
||||||
|
for (cmd in commands) {
|
||||||
|
os.writeBytes("$cmd\n")
|
||||||
|
}
|
||||||
|
os.writeBytes("exit\n")
|
||||||
|
os.flush()
|
||||||
|
|
||||||
|
val stdout = process.inputStream.bufferedReader().use(BufferedReader::readText).trim()
|
||||||
|
val stderr = process.errorStream.bufferedReader().use(BufferedReader::readText).trim()
|
||||||
|
val exitCode = process.waitFor()
|
||||||
|
|
||||||
|
if (exitCode != 0) {
|
||||||
|
Logger.warn(tag, "su command failed (code $exitCode). Stderr: $stderr")
|
||||||
|
}
|
||||||
|
CommandResult(exitCode, stdout, stderr)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.error(tag, "Exception executing su command: $commands", e)
|
||||||
|
CommandResult(-1, "", e.message ?: "Execution failed")
|
||||||
|
} finally {
|
||||||
|
try { process?.destroy() } catch (_: Exception) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun executeSh(command: String): CommandResult {
|
||||||
|
var process: Process? = null
|
||||||
|
return try {
|
||||||
|
process = ProcessBuilder("sh", "-c", command).start()
|
||||||
|
val stdout = process.inputStream.bufferedReader().use(BufferedReader::readText).trim()
|
||||||
|
val stderr = process.errorStream.bufferedReader().use(BufferedReader::readText).trim()
|
||||||
|
val exitCode = process.waitFor()
|
||||||
|
|
||||||
|
CommandResult(exitCode, stdout, stderr)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.error(tag, "Exception executing sh command: $command", e)
|
||||||
|
CommandResult(-1, "", e.message ?: "Execution failed")
|
||||||
|
} finally {
|
||||||
|
try { process?.destroy() } catch (_: Exception) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,316 @@
|
|||||||
|
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<Boolean, String?> = 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<Boolean, String?> = 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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package com.example.netshareecohub.routing
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.os.Build
|
||||||
|
import android.provider.Settings
|
||||||
|
import com.example.netshareecohub.data.logging.Logger
|
||||||
|
import com.example.netshareecohub.R
|
||||||
|
|
||||||
|
data class DeviceCapabilityReport(
|
||||||
|
val manufacturer: String,
|
||||||
|
val model: String,
|
||||||
|
val androidVersion: String,
|
||||||
|
val apiLevel: Int,
|
||||||
|
val isDirectControlSupportedForNormalApp: Boolean,
|
||||||
|
val limitationReason: String
|
||||||
|
)
|
||||||
|
|
||||||
|
object TetheringCapabilityChecker {
|
||||||
|
private const val tag = "TetheringCapabilityChecker"
|
||||||
|
private const val PERMISSION_TETHER_PRIVILEGED = "android.permission.TETHER_PRIVILEGED"
|
||||||
|
|
||||||
|
fun inspectDevice(context: Context): DeviceCapabilityReport {
|
||||||
|
val privileged = context.checkSelfPermission(PERMISSION_TETHER_PRIVILEGED) ==
|
||||||
|
PackageManager.PERMISSION_GRANTED
|
||||||
|
val writeSettings = Settings.System.canWrite(context)
|
||||||
|
val apiLevel = Build.VERSION.SDK_INT
|
||||||
|
|
||||||
|
// API availability and permission are separate prerequisites. The actual Android callback is authoritative.
|
||||||
|
// Ordinary APKs can only make this attempt on the documented legacy/system API path when
|
||||||
|
// WRITE_SETTINGS is granted (or if the device has legitimately granted TETHER_PRIVILEGED).
|
||||||
|
val canAttempt = apiLevel in Build.VERSION_CODES.R..35 && (privileged || writeSettings)
|
||||||
|
val reason = when {
|
||||||
|
apiLevel >= 36 -> context.getString(R.string.tethering_android16_limit)
|
||||||
|
!privileged && !writeSettings -> context.getString(R.string.tethering_permission_missing)
|
||||||
|
canAttempt -> context.getString(R.string.tethering_starting)
|
||||||
|
else -> context.getString(R.string.tethering_api_unavailable)
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.info(
|
||||||
|
tag,
|
||||||
|
"Device report: manufacturer=${Build.MANUFACTURER}, model=${Build.MODEL}, " +
|
||||||
|
"Android=$apiLevel, privileged=$privileged, writeSettings=$writeSettings, " +
|
||||||
|
"canAttempt=$canAttempt"
|
||||||
|
)
|
||||||
|
return DeviceCapabilityReport(
|
||||||
|
manufacturer = Build.MANUFACTURER,
|
||||||
|
model = Build.MODEL,
|
||||||
|
androidVersion = Build.VERSION.RELEASE,
|
||||||
|
apiLevel = apiLevel,
|
||||||
|
isDirectControlSupportedForNormalApp = canAttempt,
|
||||||
|
limitationReason = reason
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,514 @@
|
|||||||
|
package com.example.netshareecohub.routing
|
||||||
|
|
||||||
|
import android.net.VpnService
|
||||||
|
import com.example.netshareecohub.data.logging.Logger
|
||||||
|
import com.example.netshareecohub.dhcp.DhcpServer
|
||||||
|
import java.io.FileDescriptor
|
||||||
|
import java.io.FileInputStream
|
||||||
|
import java.io.FileOutputStream
|
||||||
|
import java.io.InputStream
|
||||||
|
import java.io.OutputStream
|
||||||
|
import java.net.DatagramPacket
|
||||||
|
import java.net.DatagramSocket
|
||||||
|
import java.net.InetAddress
|
||||||
|
import java.net.InetSocketAddress
|
||||||
|
import java.net.Socket
|
||||||
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
import java.util.concurrent.ExecutorService
|
||||||
|
import java.util.concurrent.Executors
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
import java.util.concurrent.atomic.AtomicLong
|
||||||
|
|
||||||
|
data class NatStats(
|
||||||
|
val rxBytes: Long = 0L,
|
||||||
|
val txBytes: Long = 0L,
|
||||||
|
val rxPackets: Long = 0L,
|
||||||
|
val txPackets: Long = 0L
|
||||||
|
)
|
||||||
|
|
||||||
|
class TunNatEngine(
|
||||||
|
private val fileDescriptor: FileDescriptor,
|
||||||
|
private val dnsServer: String = "8.8.8.8",
|
||||||
|
private val vpnService: VpnService? = null,
|
||||||
|
private val dhcpServer: DhcpServer? = null,
|
||||||
|
private val inputStreamOverride: InputStream? = null,
|
||||||
|
private val outputStreamOverride: OutputStream? = null,
|
||||||
|
private val onStatsUpdated: ((NatStats) -> Unit)? = null
|
||||||
|
) {
|
||||||
|
private val tag = "TunNatEngine"
|
||||||
|
private val isRunning = AtomicBoolean(false)
|
||||||
|
|
||||||
|
private val rxBytes = AtomicLong(0L)
|
||||||
|
private val txBytes = AtomicLong(0L)
|
||||||
|
private val rxPackets = AtomicLong(0L)
|
||||||
|
private val txPackets = AtomicLong(0L)
|
||||||
|
|
||||||
|
private var executor: ExecutorService? = null
|
||||||
|
|
||||||
|
private data class UdpSessionKey(
|
||||||
|
val clientIp: String,
|
||||||
|
val clientPort: Int,
|
||||||
|
val targetIp: String,
|
||||||
|
val targetPort: Int
|
||||||
|
)
|
||||||
|
|
||||||
|
private data class UdpNatSession(
|
||||||
|
val key: UdpSessionKey,
|
||||||
|
val socket: DatagramSocket,
|
||||||
|
@Volatile var lastActive: Long = System.currentTimeMillis()
|
||||||
|
)
|
||||||
|
|
||||||
|
private val udpSessions = ConcurrentHashMap<UdpSessionKey, UdpNatSession>()
|
||||||
|
|
||||||
|
private data class TcpSessionKey(
|
||||||
|
val clientIp: String,
|
||||||
|
val clientPort: Int,
|
||||||
|
val targetIp: String,
|
||||||
|
val targetPort: Int
|
||||||
|
)
|
||||||
|
|
||||||
|
private data class TcpNatSession(
|
||||||
|
val key: TcpSessionKey,
|
||||||
|
val socket: Socket,
|
||||||
|
@Volatile var lastActive: Long = System.currentTimeMillis()
|
||||||
|
)
|
||||||
|
|
||||||
|
private val tcpSessions = ConcurrentHashMap<TcpSessionKey, TcpNatSession>()
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun start() {
|
||||||
|
if (isRunning.get()) return
|
||||||
|
isRunning.set(true)
|
||||||
|
|
||||||
|
val exec = Executors.newFixedThreadPool(16)
|
||||||
|
executor = exec
|
||||||
|
|
||||||
|
Logger.info(tag, "Starting TUN NAT Engine (DNS Server: $dnsServer)")
|
||||||
|
|
||||||
|
exec.execute { runReadingLoop() }
|
||||||
|
exec.execute { runSessionCleanupLoop() }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun stop() {
|
||||||
|
if (!isRunning.get()) return
|
||||||
|
isRunning.set(false)
|
||||||
|
|
||||||
|
Logger.info(tag, "Stopping TUN NAT Engine")
|
||||||
|
|
||||||
|
udpSessions.values.forEach { session ->
|
||||||
|
try { session.socket.close() } catch (_: Exception) {}
|
||||||
|
}
|
||||||
|
udpSessions.clear()
|
||||||
|
|
||||||
|
tcpSessions.values.forEach { session ->
|
||||||
|
try { session.socket.close() } catch (_: Exception) {}
|
||||||
|
}
|
||||||
|
tcpSessions.clear()
|
||||||
|
|
||||||
|
executor?.shutdownNow()
|
||||||
|
executor = null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getStats(): NatStats {
|
||||||
|
return NatStats(
|
||||||
|
rxBytes = rxBytes.get(),
|
||||||
|
txBytes = txBytes.get(),
|
||||||
|
rxPackets = rxPackets.get(),
|
||||||
|
txPackets = txPackets.get()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun runReadingLoop() {
|
||||||
|
val input = inputStreamOverride ?: FileInputStream(fileDescriptor)
|
||||||
|
val output = outputStreamOverride ?: FileOutputStream(fileDescriptor)
|
||||||
|
val buffer = ByteArray(32768)
|
||||||
|
|
||||||
|
while (isRunning.get()) {
|
||||||
|
try {
|
||||||
|
val length = input.read(buffer)
|
||||||
|
if (length <= 0) {
|
||||||
|
if (!isRunning.get()) break
|
||||||
|
Thread.sleep(10)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
rxBytes.addAndGet(length.toLong())
|
||||||
|
rxPackets.incrementAndGet()
|
||||||
|
notifyStats()
|
||||||
|
|
||||||
|
processPacket(buffer, length, output)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
if (isRunning.get()) {
|
||||||
|
Logger.debug(tag, "Reading loop exception: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun processPacket(buffer: ByteArray, length: Int, output: OutputStream) {
|
||||||
|
val ipHeader = PacketParser.parseIPv4(buffer, length) ?: return
|
||||||
|
|
||||||
|
when (ipHeader.protocol) {
|
||||||
|
1 -> handleIcmpPacket(buffer, ipHeader, length, output)
|
||||||
|
17 -> handleUdpPacket(buffer, ipHeader, length, output)
|
||||||
|
6 -> handleTcpPacket(buffer, ipHeader, length, output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleIcmpPacket(
|
||||||
|
buffer: ByteArray,
|
||||||
|
ipHeader: IPv4Header,
|
||||||
|
totalLength: Int,
|
||||||
|
output: OutputStream
|
||||||
|
) {
|
||||||
|
val icmp = PacketParser.parseIcmp(buffer, ipHeader.ihl, totalLength) ?: return
|
||||||
|
if (icmp.type == 8) { // Echo Request (Ping)
|
||||||
|
val offset = ipHeader.ihl
|
||||||
|
val identifier = if (totalLength >= offset + 6) {
|
||||||
|
((buffer[offset + 4].toInt() and 0xFF) shl 8) or (buffer[offset + 5].toInt() and 0xFF)
|
||||||
|
} else 0
|
||||||
|
|
||||||
|
val sequence = if (totalLength >= offset + 8) {
|
||||||
|
((buffer[offset + 6].toInt() and 0xFF) shl 8) or (buffer[offset + 7].toInt() and 0xFF)
|
||||||
|
} else 0
|
||||||
|
|
||||||
|
val payloadStart = offset + 8
|
||||||
|
val payload = if (totalLength > payloadStart) {
|
||||||
|
buffer.copyOfRange(payloadStart, totalLength)
|
||||||
|
} else byteArrayOf()
|
||||||
|
|
||||||
|
val reply = PacketBuilder.buildIcmpEchoReply(
|
||||||
|
srcIp = ipHeader.dstIp,
|
||||||
|
dstIp = ipHeader.srcIp,
|
||||||
|
identifier = identifier,
|
||||||
|
sequence = sequence,
|
||||||
|
payload = payload
|
||||||
|
)
|
||||||
|
|
||||||
|
sendPacketToTun(reply, output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleUdpPacket(
|
||||||
|
buffer: ByteArray,
|
||||||
|
ipHeader: IPv4Header,
|
||||||
|
totalLength: Int,
|
||||||
|
output: OutputStream
|
||||||
|
) {
|
||||||
|
val udp = PacketParser.parseUdp(buffer, ipHeader.ihl, totalLength) ?: return
|
||||||
|
val payloadStart = ipHeader.ihl + 8
|
||||||
|
val payloadLength = udp.length - 8
|
||||||
|
if (payloadLength < 0 || payloadStart + payloadLength > totalLength) return
|
||||||
|
|
||||||
|
val payload = buffer.copyOfRange(payloadStart, payloadStart + payloadLength)
|
||||||
|
|
||||||
|
// DHCP Intercept (Dst Port 67)
|
||||||
|
if (udp.dstPort == 67) {
|
||||||
|
val responseBytes = dhcpServer?.processRawDhcpPacket(payload, payload.size)
|
||||||
|
if (responseBytes != null) {
|
||||||
|
val serverIp = dhcpServer.leaseRepository.getConfig().routerIp
|
||||||
|
val srcIp = if (serverIp.isNotBlank() && serverIp != "0.0.0.0") serverIp else "10.0.0.1"
|
||||||
|
val dhcpReplyPacket = PacketBuilder.buildUdpPacket(
|
||||||
|
srcIp = srcIp,
|
||||||
|
dstIp = "255.255.255.255",
|
||||||
|
srcPort = 67,
|
||||||
|
dstPort = 68,
|
||||||
|
payload = responseBytes
|
||||||
|
)
|
||||||
|
sendPacketToTun(dhcpReplyPacket, output)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// DNS Intercept (Dst Port 53)
|
||||||
|
if (udp.dstPort == 53) {
|
||||||
|
handleDnsQuery(
|
||||||
|
clientIp = ipHeader.srcIp,
|
||||||
|
clientPort = udp.srcPort,
|
||||||
|
queryPayload = payload,
|
||||||
|
output = output
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Standard UDP NAT
|
||||||
|
val key = UdpSessionKey(ipHeader.srcIp, udp.srcPort, ipHeader.dstIp, udp.dstPort)
|
||||||
|
var session = udpSessions[key]
|
||||||
|
|
||||||
|
if (session == null) {
|
||||||
|
try {
|
||||||
|
val socket = DatagramSocket()
|
||||||
|
vpnService?.protect(socket)
|
||||||
|
session = UdpNatSession(key, socket)
|
||||||
|
udpSessions[key] = session
|
||||||
|
|
||||||
|
// Spawn background listener for incoming UDP response
|
||||||
|
executor?.execute {
|
||||||
|
runUdpResponseListener(session, output)
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.error(tag, "Failed to create UDP socket for session $key: ${e.message}")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
session.lastActive = System.currentTimeMillis()
|
||||||
|
try {
|
||||||
|
val targetAddr = InetAddress.getByName(ipHeader.dstIp)
|
||||||
|
val packet = DatagramPacket(payload, payload.size, targetAddr, udp.dstPort)
|
||||||
|
session.socket.send(packet)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.warn(tag, "Error sending UDP packet to ${ipHeader.dstIp}:${udp.dstPort}: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleDnsQuery(
|
||||||
|
clientIp: String,
|
||||||
|
clientPort: Int,
|
||||||
|
queryPayload: ByteArray,
|
||||||
|
output: OutputStream
|
||||||
|
) {
|
||||||
|
executor?.execute {
|
||||||
|
var socket: DatagramSocket? = null
|
||||||
|
try {
|
||||||
|
socket = DatagramSocket()
|
||||||
|
vpnService?.protect(socket)
|
||||||
|
socket.soTimeout = 3000
|
||||||
|
|
||||||
|
val targetDns = if (dnsServer.isNotBlank()) dnsServer else "8.8.8.8"
|
||||||
|
val dnsAddr = InetAddress.getByName(targetDns)
|
||||||
|
val outPacket = DatagramPacket(queryPayload, queryPayload.size, dnsAddr, 53)
|
||||||
|
socket.send(outPacket)
|
||||||
|
|
||||||
|
val respBuffer = ByteArray(4096)
|
||||||
|
val inPacket = DatagramPacket(respBuffer, respBuffer.size)
|
||||||
|
socket.receive(inPacket)
|
||||||
|
|
||||||
|
val responseData = respBuffer.copyOf(inPacket.length)
|
||||||
|
|
||||||
|
val dnsReplyPacket = PacketBuilder.buildUdpPacket(
|
||||||
|
srcIp = targetDns,
|
||||||
|
dstIp = clientIp,
|
||||||
|
srcPort = 53,
|
||||||
|
dstPort = clientPort,
|
||||||
|
payload = responseData
|
||||||
|
)
|
||||||
|
|
||||||
|
sendPacketToTun(dnsReplyPacket, output)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.debug(tag, "DNS resolution failed for client $clientIp:$clientPort: ${e.message}")
|
||||||
|
} finally {
|
||||||
|
try { socket?.close() } catch (_: Exception) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun runUdpResponseListener(session: UdpNatSession, output: OutputStream) {
|
||||||
|
val buffer = ByteArray(65535)
|
||||||
|
while (isRunning.get() && udpSessions.containsKey(session.key)) {
|
||||||
|
try {
|
||||||
|
val packet = DatagramPacket(buffer, buffer.size)
|
||||||
|
session.socket.receive(packet)
|
||||||
|
|
||||||
|
session.lastActive = System.currentTimeMillis()
|
||||||
|
val responsePayload = buffer.copyOf(packet.length)
|
||||||
|
|
||||||
|
val udpReply = PacketBuilder.buildUdpPacket(
|
||||||
|
srcIp = session.key.targetIp,
|
||||||
|
dstIp = session.key.clientIp,
|
||||||
|
srcPort = session.key.targetPort,
|
||||||
|
dstPort = session.key.clientPort,
|
||||||
|
payload = responsePayload
|
||||||
|
)
|
||||||
|
|
||||||
|
sendPacketToTun(udpReply, output)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleTcpPacket(
|
||||||
|
buffer: ByteArray,
|
||||||
|
ipHeader: IPv4Header,
|
||||||
|
totalLength: Int,
|
||||||
|
output: OutputStream
|
||||||
|
) {
|
||||||
|
val tcp = PacketParser.parseTcp(buffer, ipHeader.ihl, totalLength) ?: return
|
||||||
|
val payloadStart = ipHeader.ihl + tcp.dataOffset
|
||||||
|
val payloadLength = totalLength - payloadStart
|
||||||
|
val payload = if (payloadLength > 0 && payloadStart + payloadLength <= totalLength) {
|
||||||
|
buffer.copyOfRange(payloadStart, payloadStart + payloadLength)
|
||||||
|
} else byteArrayOf()
|
||||||
|
|
||||||
|
val key = TcpSessionKey(ipHeader.srcIp, tcp.srcPort, ipHeader.dstIp, tcp.dstPort)
|
||||||
|
|
||||||
|
val isSyn = (tcp.flags and 0x02) != 0
|
||||||
|
val isAck = (tcp.flags and 0x10) != 0
|
||||||
|
val isFin = (tcp.flags and 0x01) != 0
|
||||||
|
val isRst = (tcp.flags and 0x04) != 0
|
||||||
|
|
||||||
|
if (isSyn && !isAck) {
|
||||||
|
// New TCP connection request from LAN client
|
||||||
|
executor?.execute {
|
||||||
|
try {
|
||||||
|
val socket = Socket()
|
||||||
|
vpnService?.protect(socket)
|
||||||
|
socket.connect(InetSocketAddress(ipHeader.dstIp, tcp.dstPort), 5000)
|
||||||
|
|
||||||
|
val session = TcpNatSession(key, socket)
|
||||||
|
tcpSessions[key] = session
|
||||||
|
|
||||||
|
// Send SYN-ACK back to client
|
||||||
|
val synAckPacket = PacketBuilder.buildTcpPacket(
|
||||||
|
srcIp = ipHeader.dstIp,
|
||||||
|
dstIp = ipHeader.srcIp,
|
||||||
|
srcPort = tcp.dstPort,
|
||||||
|
dstPort = tcp.srcPort,
|
||||||
|
seqNumber = (1000..9999).random().toLong(),
|
||||||
|
ackNumber = tcp.sequenceNumber + 1,
|
||||||
|
flags = 0x12 // SYN + ACK
|
||||||
|
)
|
||||||
|
sendPacketToTun(synAckPacket, output)
|
||||||
|
|
||||||
|
// Start background reader for TCP upstream socket
|
||||||
|
executor?.execute {
|
||||||
|
runTcpResponseRelay(session, tcp.sequenceNumber + 1, output)
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
// Send RST back to client on failure
|
||||||
|
val rstPacket = PacketBuilder.buildTcpPacket(
|
||||||
|
srcIp = ipHeader.dstIp,
|
||||||
|
dstIp = ipHeader.srcIp,
|
||||||
|
srcPort = tcp.dstPort,
|
||||||
|
dstPort = tcp.srcPort,
|
||||||
|
seqNumber = 0,
|
||||||
|
ackNumber = tcp.sequenceNumber + 1,
|
||||||
|
flags = 0x04 // RST
|
||||||
|
)
|
||||||
|
sendPacketToTun(rstPacket, output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
val session = tcpSessions[key]
|
||||||
|
if (session != null) {
|
||||||
|
session.lastActive = System.currentTimeMillis()
|
||||||
|
if (payload.isNotEmpty()) {
|
||||||
|
try {
|
||||||
|
session.socket.outputStream.write(payload)
|
||||||
|
session.socket.outputStream.flush()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
closeTcpSession(session)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isFin || isRst) {
|
||||||
|
closeTcpSession(session)
|
||||||
|
val finAckPacket = PacketBuilder.buildTcpPacket(
|
||||||
|
srcIp = ipHeader.dstIp,
|
||||||
|
dstIp = ipHeader.srcIp,
|
||||||
|
srcPort = tcp.dstPort,
|
||||||
|
dstPort = tcp.srcPort,
|
||||||
|
seqNumber = tcp.ackNumber,
|
||||||
|
ackNumber = tcp.sequenceNumber + payload.size + 1,
|
||||||
|
flags = if (isFin) 0x11 else 0x04 // FIN+ACK or RST
|
||||||
|
)
|
||||||
|
sendPacketToTun(finAckPacket, output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun runTcpResponseRelay(
|
||||||
|
session: TcpNatSession,
|
||||||
|
initialClientSeq: Long,
|
||||||
|
output: OutputStream
|
||||||
|
) {
|
||||||
|
val buffer = ByteArray(16384)
|
||||||
|
var currentSeq = (1000..9999).random().toLong()
|
||||||
|
val currentAck = initialClientSeq
|
||||||
|
|
||||||
|
while (isRunning.get() && tcpSessions.containsKey(session.key)) {
|
||||||
|
try {
|
||||||
|
val read = session.socket.inputStream.read(buffer)
|
||||||
|
if (read <= 0) break
|
||||||
|
|
||||||
|
session.lastActive = System.currentTimeMillis()
|
||||||
|
val chunk = buffer.copyOf(read)
|
||||||
|
|
||||||
|
val tcpResponse = PacketBuilder.buildTcpPacket(
|
||||||
|
srcIp = session.key.targetIp,
|
||||||
|
dstIp = session.key.clientIp,
|
||||||
|
srcPort = session.key.targetPort,
|
||||||
|
dstPort = session.key.clientPort,
|
||||||
|
seqNumber = currentSeq,
|
||||||
|
ackNumber = currentAck,
|
||||||
|
flags = 0x18, // PSH + ACK
|
||||||
|
payload = chunk
|
||||||
|
)
|
||||||
|
|
||||||
|
currentSeq += read
|
||||||
|
sendPacketToTun(tcpResponse, output)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
closeTcpSession(session)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun closeTcpSession(session: TcpNatSession) {
|
||||||
|
tcpSessions.remove(session.key)
|
||||||
|
try { session.socket.close() } catch (_: Exception) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
private fun sendPacketToTun(packet: ByteArray, output: OutputStream) {
|
||||||
|
try {
|
||||||
|
output.write(packet)
|
||||||
|
output.flush()
|
||||||
|
txBytes.addAndGet(packet.size.toLong())
|
||||||
|
txPackets.incrementAndGet()
|
||||||
|
notifyStats()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Logger.debug(tag, "Error writing packet to TUN output: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun notifyStats() {
|
||||||
|
onStatsUpdated?.invoke(getStats())
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun runSessionCleanupLoop() {
|
||||||
|
while (isRunning.get()) {
|
||||||
|
try {
|
||||||
|
Thread.sleep(10000)
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
|
||||||
|
// Clean UDP sessions inactive for > 60 seconds
|
||||||
|
val udpIterator = udpSessions.entries.iterator()
|
||||||
|
while (udpIterator.hasNext()) {
|
||||||
|
val entry = udpIterator.next()
|
||||||
|
if (now - entry.value.lastActive > 60000) {
|
||||||
|
try { entry.value.socket.close() } catch (_: Exception) {}
|
||||||
|
udpIterator.remove()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clean TCP sessions inactive for > 120 seconds
|
||||||
|
val tcpIterator = tcpSessions.entries.iterator()
|
||||||
|
while (tcpIterator.hasNext()) {
|
||||||
|
val entry = tcpIterator.next()
|
||||||
|
if (now - entry.value.lastActive > 120000) {
|
||||||
|
try { entry.value.socket.close() } catch (_: Exception) {}
|
||||||
|
tcpIterator.remove()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
if (!isRunning.get()) break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
213
app/src/main/java/com/example/netshareecohub/ui/AppNavigation.kt
Normal file
@@ -0,0 +1,213 @@
|
|||||||
|
package com.example.netshareecohub.ui
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.automirrored.filled.List
|
||||||
|
import androidx.compose.material.icons.filled.Build
|
||||||
|
import androidx.compose.material.icons.filled.Home
|
||||||
|
import androidx.compose.material.icons.filled.Info
|
||||||
|
import androidx.compose.material.icons.filled.Person
|
||||||
|
import androidx.compose.material.icons.filled.Settings
|
||||||
|
import androidx.compose.material.icons.automirrored.filled.ExitToApp
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.NavigationBar
|
||||||
|
import androidx.compose.material3.NavigationBarItem
|
||||||
|
import androidx.compose.material3.Scaffold
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TopAppBar
|
||||||
|
import androidx.compose.material3.TopAppBarDefaults
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.collectAsState
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import android.content.Intent
|
||||||
|
import android.provider.Settings
|
||||||
|
import com.example.netshareecohub.routing.SystemTetheringManager
|
||||||
|
import com.example.netshareecohub.viewmodel.AppScreen
|
||||||
|
import com.example.netshareecohub.viewmodel.MainViewModel
|
||||||
|
import com.example.netshareecohub.viewmodel.AuthViewModel
|
||||||
|
import com.example.netshareecohub.ui.auth.AdminScreen
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun AppNavigation(viewModel: MainViewModel, authViewModel: AuthViewModel) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val currentScreen by viewModel.currentScreen.collectAsState()
|
||||||
|
val currentUser by authViewModel.currentUser.collectAsState()
|
||||||
|
val isRootAvailable by viewModel.isRootAvailable.collectAsState()
|
||||||
|
val activeAdapter by viewModel.activeAdapter.collectAsState()
|
||||||
|
val dhcpStatus by viewModel.dhcpStatus.collectAsState()
|
||||||
|
val dhcpConfig by viewModel.dhcpConfig.collectAsState()
|
||||||
|
val activeLeases by viewModel.activeLeases.collectAsState()
|
||||||
|
val routingStatus by viewModel.routingStatus.collectAsState()
|
||||||
|
val isSharingActive by viewModel.isSharingActive.collectAsState()
|
||||||
|
val isSpeedConfigSupported by viewModel.isSpeedConfigSupported.collectAsState()
|
||||||
|
val speedConfigMessage by viewModel.speedConfigMessage.collectAsState()
|
||||||
|
val diagnosticItems by viewModel.diagnosticItems.collectAsState()
|
||||||
|
val diagnosticOutput by viewModel.diagnosticOutput.collectAsState()
|
||||||
|
val logs by viewModel.logs.collectAsState()
|
||||||
|
val pendingVpnIntent by viewModel.vpnPermissionIntent.collectAsState()
|
||||||
|
val tetheringStatusMessage by viewModel.tetheringStatusMessage.collectAsState()
|
||||||
|
val isOperationInProgress by viewModel.isOperationInProgress.collectAsState()
|
||||||
|
val connectionState by viewModel.connectionState.collectAsState()
|
||||||
|
|
||||||
|
val vpnLauncher = rememberLauncherForActivityResult(
|
||||||
|
contract = ActivityResultContracts.StartActivityForResult()
|
||||||
|
) { result ->
|
||||||
|
if (result.resultCode == Activity.RESULT_OK) {
|
||||||
|
viewModel.onVpnPermissionGranted(context)
|
||||||
|
} else {
|
||||||
|
Toast.makeText(context, "VPN permission is required to enable Non-Root sharing.", Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(pendingVpnIntent) {
|
||||||
|
pendingVpnIntent?.let { intent ->
|
||||||
|
vpnLauncher.launch(intent)
|
||||||
|
viewModel.onVpnPermissionIntentHandled()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Scaffold(
|
||||||
|
topBar = {
|
||||||
|
TopAppBar(
|
||||||
|
title = {
|
||||||
|
Text(
|
||||||
|
text = "iPhone Unlock",
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
},
|
||||||
|
actions = {
|
||||||
|
IconButton(onClick = { authViewModel.logout() }) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.AutoMirrored.Filled.ExitToApp,
|
||||||
|
contentDescription = "Logout"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
colors = TopAppBarDefaults.topAppBarColors(
|
||||||
|
containerColor = MaterialTheme.colorScheme.primaryContainer,
|
||||||
|
titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer
|
||||||
|
)
|
||||||
|
)
|
||||||
|
},
|
||||||
|
bottomBar = {
|
||||||
|
NavigationBar {
|
||||||
|
AppScreen.entries.forEach { screen ->
|
||||||
|
if (screen == AppScreen.ADMIN && currentUser?.role != "ADMIN") return@forEach
|
||||||
|
|
||||||
|
// Hide other menus to make it clean as requested
|
||||||
|
if (screen != AppScreen.DASHBOARD && screen != AppScreen.ADMIN) return@forEach
|
||||||
|
|
||||||
|
val icon = when (screen) {
|
||||||
|
AppScreen.DASHBOARD -> Icons.Default.Home
|
||||||
|
AppScreen.ADMIN -> Icons.Default.Person
|
||||||
|
else -> Icons.Default.Info
|
||||||
|
}
|
||||||
|
|
||||||
|
NavigationBarItem(
|
||||||
|
selected = currentScreen == screen,
|
||||||
|
onClick = { viewModel.navigateTo(screen) },
|
||||||
|
icon = { Icon(icon, contentDescription = screen.title) }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
) { innerPadding ->
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(innerPadding)
|
||||||
|
) {
|
||||||
|
when (currentScreen) {
|
||||||
|
AppScreen.DASHBOARD -> {
|
||||||
|
val context = LocalContext.current
|
||||||
|
DashboardScreen(
|
||||||
|
isRootAvailable = isRootAvailable,
|
||||||
|
adapter = activeAdapter,
|
||||||
|
dhcpStatus = dhcpStatus,
|
||||||
|
dhcpConfig = dhcpConfig,
|
||||||
|
activeLeases = activeLeases,
|
||||||
|
routingStatus = routingStatus,
|
||||||
|
isSharingActive = isSharingActive,
|
||||||
|
tetheringStatusMessage = tetheringStatusMessage,
|
||||||
|
isOperationInProgress = isOperationInProgress,
|
||||||
|
connectionState = connectionState,
|
||||||
|
authViewModel = authViewModel,
|
||||||
|
onToggleSharing = { viewModel.toggleSharing(context) },
|
||||||
|
onNavigate = { screen -> viewModel.navigateTo(screen) },
|
||||||
|
onRefresh = { viewModel.refreshEthernetInterfaces() },
|
||||||
|
onOpenSystemTethering = {
|
||||||
|
SystemTetheringManager().openSystemTetheringSettings(context)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
AppScreen.SETTINGS -> {
|
||||||
|
val context = LocalContext.current
|
||||||
|
EthernetSettingsScreen(
|
||||||
|
adapter = activeAdapter,
|
||||||
|
dhcpConfig = dhcpConfig,
|
||||||
|
isSpeedConfigSupported = isSpeedConfigSupported,
|
||||||
|
speedConfigMessage = speedConfigMessage,
|
||||||
|
onApplySpeed = { iface, mode -> viewModel.applySpeedConfig(iface, mode) },
|
||||||
|
onSaveDhcpConfig = { newConfig -> viewModel.updateDhcpConfig(newConfig) },
|
||||||
|
onOpenSystemTethering = {
|
||||||
|
SystemTetheringManager().openSystemTetheringSettings(context)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
AppScreen.DEVICES -> ConnectedDevicesScreen(
|
||||||
|
leases = activeLeases
|
||||||
|
)
|
||||||
|
|
||||||
|
AppScreen.DIAGNOSTICS -> {
|
||||||
|
val context = LocalContext.current
|
||||||
|
DiagnosticsScreen(
|
||||||
|
items = diagnosticItems,
|
||||||
|
outputLog = diagnosticOutput,
|
||||||
|
onRunFullDiagnostics = { viewModel.runFullDiagnostics() },
|
||||||
|
onPingGateway = { viewModel.pingGateway() },
|
||||||
|
onPingInternet = { viewModel.pingInternet() },
|
||||||
|
onTestDns = { viewModel.testDns() },
|
||||||
|
onTraceroute = { viewModel.runTraceroute() },
|
||||||
|
onOpenSystemTethering = {
|
||||||
|
SystemTetheringManager().openSystemTetheringSettings(context)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
AppScreen.LOGS -> NetworkLogsScreen(
|
||||||
|
logs = logs,
|
||||||
|
onClearLogs = { viewModel.clearLogs() },
|
||||||
|
onCopyLogs = { context -> viewModel.copyLogsToClipboard(context) }
|
||||||
|
)
|
||||||
|
|
||||||
|
AppScreen.ADMIN -> AdminScreen(
|
||||||
|
authViewModel = authViewModel
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
package com.example.netshareecohub.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material3.Card
|
||||||
|
import androidx.compose.material3.CardDefaults
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import com.example.netshareecohub.dhcp.DhcpClientLease
|
||||||
|
import com.example.netshareecohub.dhcp.LeaseStatus
|
||||||
|
import com.example.netshareecohub.dhcp.MacVendorResolver
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun ConnectedDevicesScreen(
|
||||||
|
leases: List<DhcpClientLease>
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(16.dp)
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Connected Clients (${leases.size})",
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
|
|
||||||
|
if (leases.isEmpty()) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
contentAlignment = Alignment.Center
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "No active DHCP client leases found.",
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
LazyColumn(
|
||||||
|
verticalArrangement = Arrangement.spacedBy(10.dp)
|
||||||
|
) {
|
||||||
|
items(leases) { lease ->
|
||||||
|
ConnectedDeviceCard(lease = lease)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun ConnectedDeviceCard(lease: DhcpClientLease) {
|
||||||
|
val statusColor = when (lease.status) {
|
||||||
|
LeaseStatus.ONLINE -> Color(0xFF2E7D32)
|
||||||
|
LeaseStatus.OFFERED -> Color(0xFFF57F17)
|
||||||
|
LeaseStatus.EXPIRED -> Color.Gray
|
||||||
|
LeaseStatus.RELEASED -> Color(0xFFC62828)
|
||||||
|
}
|
||||||
|
|
||||||
|
val remainingTimeStr = formatRemainingTime(lease.leaseExpirationTime - System.currentTimeMillis())
|
||||||
|
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
|
||||||
|
elevation = CardDefaults.cardElevation(2.dp)
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.padding(14.dp)) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = MacVendorResolver.formatDeviceName(lease.hostName, lease.macAddress),
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
fontSize = 16.sp,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
|
||||||
|
Surface(
|
||||||
|
color = statusColor,
|
||||||
|
shape = RoundedCornerShape(12.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = lease.status.name,
|
||||||
|
color = Color.White,
|
||||||
|
fontSize = 11.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(6.dp))
|
||||||
|
|
||||||
|
DashboardDetailRow("Assigned IP", lease.ipAddress)
|
||||||
|
DashboardDetailRow("MAC Address", lease.macAddress)
|
||||||
|
DashboardDetailRow("Lease Expiry", remainingTimeStr)
|
||||||
|
DashboardDetailRow("Interface", lease.interfaceName ?: "N/A")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun formatRemainingTime(millis: Long): String {
|
||||||
|
if (millis <= 0) return "Expired"
|
||||||
|
val seconds = millis / 1000
|
||||||
|
val hours = seconds / 3600
|
||||||
|
val minutes = (seconds % 3600) / 60
|
||||||
|
val secs = seconds % 60
|
||||||
|
return if (hours > 0) {
|
||||||
|
"${hours}h ${minutes}m ${secs}s"
|
||||||
|
} else if (minutes > 0) {
|
||||||
|
"${minutes}m ${secs}s"
|
||||||
|
} else {
|
||||||
|
"${secs}s"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,465 @@
|
|||||||
|
package com.example.netshareecohub.ui
|
||||||
|
|
||||||
|
import android.os.Build
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.layout.widthIn
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.automirrored.filled.List
|
||||||
|
import androidx.compose.material.icons.filled.Build
|
||||||
|
import androidx.compose.material.icons.filled.PlayArrow
|
||||||
|
import androidx.compose.material.icons.filled.Refresh
|
||||||
|
import androidx.compose.material.icons.filled.Settings
|
||||||
|
import androidx.compose.material.icons.filled.Stop
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.ButtonDefaults
|
||||||
|
import androidx.compose.material3.Card
|
||||||
|
import androidx.compose.material3.CardDefaults
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedButton
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.collectAsState
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.res.painterResource
|
||||||
|
import androidx.compose.ui.text.font.FontFamily
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import com.example.netshareecohub.R
|
||||||
|
import com.example.netshareecohub.data.logging.Logger
|
||||||
|
import com.example.netshareecohub.dhcp.DhcpClientLease
|
||||||
|
import com.example.netshareecohub.dhcp.DhcpServerConfig
|
||||||
|
import com.example.netshareecohub.dhcp.DhcpServerStatus
|
||||||
|
import com.example.netshareecohub.dhcp.MacVendorResolver
|
||||||
|
import com.example.netshareecohub.dhcp.ServerState
|
||||||
|
import com.example.netshareecohub.ethernet.EthernetAdapterInfo
|
||||||
|
import com.example.netshareecohub.routing.RoutingStatus
|
||||||
|
import com.example.netshareecohub.viewmodel.AppScreen
|
||||||
|
import com.example.netshareecohub.viewmodel.AuthViewModel
|
||||||
|
import com.example.netshareecohub.viewmodel.MainViewModel
|
||||||
|
import com.example.netshareecohub.ui.components.EcohubWatermark
|
||||||
|
import com.example.netshareecohub.ui.components.EcohubRepeatingWatermark
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun DashboardScreen(
|
||||||
|
isRootAvailable: Boolean,
|
||||||
|
adapter: EthernetAdapterInfo?,
|
||||||
|
dhcpStatus: DhcpServerStatus,
|
||||||
|
dhcpConfig: DhcpServerConfig,
|
||||||
|
activeLeases: List<DhcpClientLease>,
|
||||||
|
routingStatus: RoutingStatus,
|
||||||
|
isSharingActive: Boolean,
|
||||||
|
tetheringStatusMessage: String?,
|
||||||
|
isOperationInProgress: Boolean,
|
||||||
|
connectionState: MainViewModel.ConnectionState,
|
||||||
|
authViewModel: AuthViewModel,
|
||||||
|
onToggleSharing: () -> Unit,
|
||||||
|
onNavigate: (AppScreen) -> Unit,
|
||||||
|
onRefresh: () -> Unit,
|
||||||
|
onOpenSystemTethering: () -> Unit
|
||||||
|
) {
|
||||||
|
val scrollState = rememberScrollState()
|
||||||
|
val apiProfile by authViewModel.apiUserProfile.collectAsState()
|
||||||
|
|
||||||
|
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) {
|
||||||
|
EcohubRepeatingWatermark()
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.widthIn(max = 600.dp)
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.weight(1f)
|
||||||
|
.verticalScroll(scrollState)
|
||||||
|
.padding(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||||
|
) {
|
||||||
|
// Header
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
) {
|
||||||
|
Image(
|
||||||
|
painter = painterResource(id = R.drawable.ic_logo),
|
||||||
|
contentDescription = "App Logo",
|
||||||
|
modifier = Modifier.height(44.dp).width(44.dp).padding(end = 8.dp)
|
||||||
|
)
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
text = "iPhone Unlock",
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = MaterialTheme.colorScheme.primary,
|
||||||
|
maxLines = 1
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
IconButton(onClick = {
|
||||||
|
onRefresh()
|
||||||
|
authViewModel.fetchUserProfile()
|
||||||
|
}) {
|
||||||
|
Icon(Icons.Default.Refresh, contentDescription = "Refresh")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (apiProfile != null) {
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer)
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.padding(16.dp)) {
|
||||||
|
Text(
|
||||||
|
text = "User Profile",
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onPrimaryContainer
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
DashboardDetailRow("Name", apiProfile!!.name)
|
||||||
|
DashboardDetailRow("User ID", apiProfile!!.user_id)
|
||||||
|
DashboardDetailRow("Status", apiProfile!!.status?.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() } ?: "Unknown")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ethernet Adapter Card
|
||||||
|
val isConnected = adapter != null && (
|
||||||
|
adapter.carrier == 1 ||
|
||||||
|
adapter.operstate.equals("up", ignoreCase = true) ||
|
||||||
|
adapter.operstate.equals("lower_up", ignoreCase = true) ||
|
||||||
|
(!adapter.primaryIpv4.isNullOrBlank() && !adapter.primaryIpv4.startsWith("127."))
|
||||||
|
) && !adapter.operstate.equals("down", ignoreCase = true) && adapter.carrier != 0
|
||||||
|
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
colors = CardDefaults.cardColors(
|
||||||
|
containerColor = MaterialTheme.colorScheme.surfaceVariant
|
||||||
|
),
|
||||||
|
elevation = CardDefaults.cardElevation(2.dp)
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.padding(16.dp)) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.ethernet_link_status),
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
style = MaterialTheme.typography.titleSmall
|
||||||
|
)
|
||||||
|
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text(
|
||||||
|
text = if (isConnected) "● ${stringResource(R.string.connected)}" else "○ ${stringResource(R.string.disconnected)}",
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
color = if (isConnected) Color(0xFF2E7D32) else Color(0xFFD32F2F),
|
||||||
|
fontSize = 13.sp
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Control Status Card
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
|
||||||
|
elevation = CardDefaults.cardElevation(2.dp)
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.padding(14.dp)) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.control_status),
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
style = MaterialTheme.typography.titleSmall
|
||||||
|
)
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
val isVerifiedActive = isSharingActive && isConnected &&
|
||||||
|
connectionState == MainViewModel.ConnectionState.TETHERING_ACTIVE
|
||||||
|
val statusText = when {
|
||||||
|
isOperationInProgress -> stringResource(R.string.connecting)
|
||||||
|
isVerifiedActive -> stringResource(R.string.tethering_active)
|
||||||
|
connectionState == MainViewModel.ConnectionState.TETHERING_ACTIVE ->
|
||||||
|
stringResource(R.string.tethering_active)
|
||||||
|
connectionState == MainViewModel.ConnectionState.UNSUPPORTED_ON_DEVICE ->
|
||||||
|
stringResource(R.string.tethering_unavailable)
|
||||||
|
connectionState == MainViewModel.ConnectionState.FAILED ->
|
||||||
|
stringResource(R.string.connection_failed)
|
||||||
|
connectionState == MainViewModel.ConnectionState.DISCONNECTED ->
|
||||||
|
stringResource(R.string.disconnected)
|
||||||
|
else -> stringResource(R.string.status_idle)
|
||||||
|
}
|
||||||
|
val statusColor = when {
|
||||||
|
isVerifiedActive -> Color(0xFF2E7D32)
|
||||||
|
connectionState == MainViewModel.ConnectionState.FAILED ||
|
||||||
|
connectionState == MainViewModel.ConnectionState.UNSUPPORTED_ON_DEVICE ->
|
||||||
|
Color(0xFFD32F2F)
|
||||||
|
else -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
}
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = statusText,
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
color = statusColor,
|
||||||
|
fontSize = 12.sp
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.width(6.dp))
|
||||||
|
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(10.dp)
|
||||||
|
.background(
|
||||||
|
color = when {
|
||||||
|
isVerifiedActive -> Color(0xFF2E7D32)
|
||||||
|
connectionState == MainViewModel.ConnectionState.FAILED ||
|
||||||
|
connectionState == MainViewModel.ConnectionState.UNSUPPORTED_ON_DEVICE ->
|
||||||
|
Color(0xFFD32F2F)
|
||||||
|
else -> Color.Gray
|
||||||
|
},
|
||||||
|
shape = CircleShape
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val statusMessage = tetheringStatusMessage?.takeIf { it.isNotBlank() }
|
||||||
|
if (statusMessage != null) {
|
||||||
|
Spacer(modifier = Modifier.height(6.dp))
|
||||||
|
Text(
|
||||||
|
text = statusMessage,
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = if (isSharingActive && isConnected) Color(0xFF2E7D32)
|
||||||
|
else MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Script Terminal Card
|
||||||
|
val logs by Logger.logs.collectAsState()
|
||||||
|
|
||||||
|
val rawConnectionLogs = logs.filter {
|
||||||
|
it.tag in setOf("MainViewModel", "SystemTetheringManager", "TetheringCapabilityChecker", "EthernetMonitor", "RoutingManager")
|
||||||
|
}.takeLast(160)
|
||||||
|
val connectionLogs = buildList {
|
||||||
|
for (entry in rawConnectionLogs) {
|
||||||
|
if (lastOrNull()?.tag != entry.tag || lastOrNull()?.message != entry.message) add(entry)
|
||||||
|
}
|
||||||
|
}.takeLast(80)
|
||||||
|
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth().height(280.dp),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = Color.Black),
|
||||||
|
elevation = CardDefaults.cardElevation(2.dp)
|
||||||
|
) {
|
||||||
|
LazyColumn(
|
||||||
|
modifier = Modifier.fillMaxSize().padding(8.dp),
|
||||||
|
reverseLayout = true
|
||||||
|
) {
|
||||||
|
items(connectionLogs.reversed()) { log ->
|
||||||
|
Text(
|
||||||
|
text = log.message,
|
||||||
|
color = Color.Green,
|
||||||
|
fontFamily = FontFamily.Monospace,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
lineHeight = 14.sp
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only show a network hint when a client actually reports a self-assigned address.
|
||||||
|
// Do not instruct the user to leave the app or imply that this app can enable a system feature.
|
||||||
|
val hasSelfAssignedClient = activeLeases.any { it.ipAddress.startsWith("169.254") }
|
||||||
|
if (hasSelfAssignedClient) {
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer)
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.padding(14.dp)) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.self_assigned_ip_title),
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
style = MaterialTheme.typography.titleSmall,
|
||||||
|
color = MaterialTheme.colorScheme.onErrorContainer
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.height(4.dp))
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.self_assigned_ip_message),
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onErrorContainer
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Connected Clients Preview Section
|
||||||
|
if (activeLeases.isNotEmpty()) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.connected_client_devices, activeLeases.size),
|
||||||
|
style = MaterialTheme.typography.titleSmall,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
modifier = Modifier.padding(top = 4.dp)
|
||||||
|
)
|
||||||
|
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.padding(14.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||||
|
) {
|
||||||
|
activeLeases.forEach { lease ->
|
||||||
|
val deviceName = MacVendorResolver.formatDeviceName(lease.hostName, lease.macAddress)
|
||||||
|
Column {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = deviceName,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
fontSize = 14.sp
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = lease.ipAddress,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = MaterialTheme.colorScheme.primary,
|
||||||
|
fontSize = 14.sp
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.client_mac_status, lease.macAddress, lease.status.name),
|
||||||
|
fontSize = 11.sp,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Device Model Card
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
|
||||||
|
elevation = CardDefaults.cardElevation(2.dp)
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.padding(14.dp)) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.device_label, "${Build.MANUFACTURER} ${Build.MODEL}"),
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
style = MaterialTheme.typography.bodyMedium
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|
||||||
|
EcohubWatermark()
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sharing Control Button Pinned to Bottom
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
|
||||||
|
elevation = CardDefaults.cardElevation(4.dp)
|
||||||
|
) {
|
||||||
|
Button(
|
||||||
|
onClick = onToggleSharing,
|
||||||
|
enabled = !isOperationInProgress,
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.height(64.dp),
|
||||||
|
colors = ButtonDefaults.buttonColors(
|
||||||
|
containerColor = if (isSharingActive) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary
|
||||||
|
),
|
||||||
|
shape = RoundedCornerShape(12.dp)
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = if (isSharingActive) Icons.Default.Stop else Icons.Default.PlayArrow,
|
||||||
|
contentDescription = null,
|
||||||
|
modifier = Modifier.size(28.dp)
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.width(12.dp))
|
||||||
|
Text(
|
||||||
|
text = if (isOperationInProgress) stringResource(R.string.processing)
|
||||||
|
else if (isSharingActive) stringResource(R.string.stop_sharing)
|
||||||
|
else stringResource(R.string.start_sharing),
|
||||||
|
fontSize = 20.sp,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun DashboardDetailRow(
|
||||||
|
label: String,
|
||||||
|
value: String,
|
||||||
|
valueColor: Color = MaterialTheme.colorScheme.onSurface
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(vertical = 3.dp),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = label,
|
||||||
|
fontSize = 13.sp,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = value,
|
||||||
|
fontSize = 13.sp,
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
color = valueColor
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
package com.example.netshareecohub.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.Card
|
||||||
|
import androidx.compose.material3.CardDefaults
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedButton
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.text.font.FontFamily
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import com.example.netshareecohub.diagnostics.DiagnosticItem
|
||||||
|
import com.example.netshareecohub.diagnostics.DiagnosticStatus
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun DiagnosticsScreen(
|
||||||
|
items: List<DiagnosticItem>,
|
||||||
|
outputLog: String,
|
||||||
|
onRunFullDiagnostics: () -> Unit,
|
||||||
|
onPingGateway: () -> Unit,
|
||||||
|
onPingInternet: () -> Unit,
|
||||||
|
onTestDns: () -> Unit,
|
||||||
|
onTraceroute: () -> Unit,
|
||||||
|
onOpenSystemTethering: () -> Unit
|
||||||
|
) {
|
||||||
|
val scrollState = rememberScrollState()
|
||||||
|
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.verticalScroll(scrollState)
|
||||||
|
.padding(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Network Diagnostics Engine",
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
|
||||||
|
// Action Buttons Row
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||||
|
) {
|
||||||
|
Button(
|
||||||
|
onClick = onRunFullDiagnostics,
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
) {
|
||||||
|
Text("Run Full Diagnostics", fontSize = 12.sp)
|
||||||
|
}
|
||||||
|
|
||||||
|
OutlinedButton(
|
||||||
|
onClick = onOpenSystemTethering,
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
) {
|
||||||
|
Text(stringResource(R.string.tethering_support), fontSize = 12.sp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(6.dp)
|
||||||
|
) {
|
||||||
|
OutlinedButton(
|
||||||
|
onClick = onPingGateway,
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
) {
|
||||||
|
Text("Ping Gateway", fontSize = 11.sp)
|
||||||
|
}
|
||||||
|
|
||||||
|
OutlinedButton(
|
||||||
|
onClick = onPingInternet,
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
) {
|
||||||
|
Text("Ping Internet", fontSize = 11.sp)
|
||||||
|
}
|
||||||
|
|
||||||
|
OutlinedButton(
|
||||||
|
onClick = onTestDns,
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
) {
|
||||||
|
Text("DNS Test", fontSize = 11.sp)
|
||||||
|
}
|
||||||
|
|
||||||
|
OutlinedButton(
|
||||||
|
onClick = onTraceroute,
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
) {
|
||||||
|
Text("Traceroute", fontSize = 11.sp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Diagnostic Checklist Table
|
||||||
|
Text(
|
||||||
|
text = "Diagnostic Checklist (8 Tests)",
|
||||||
|
style = MaterialTheme.typography.titleSmall,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
|
||||||
|
Card(modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.padding(12.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||||
|
) {
|
||||||
|
items.forEach { item ->
|
||||||
|
DiagnosticChecklistRow(item = item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output Console Area
|
||||||
|
Text(
|
||||||
|
text = "Diagnostic Output Log",
|
||||||
|
style = MaterialTheme.typography.titleSmall,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.height(260.dp)
|
||||||
|
.background(Color(0xFF1E1E1E), RoundedCornerShape(8.dp))
|
||||||
|
.padding(12.dp)
|
||||||
|
) {
|
||||||
|
val consoleScroll = rememberScrollState()
|
||||||
|
Text(
|
||||||
|
text = outputLog,
|
||||||
|
color = Color(0xFF00FF66),
|
||||||
|
fontSize = 11.sp,
|
||||||
|
fontFamily = FontFamily.Monospace,
|
||||||
|
modifier = Modifier.verticalScroll(consoleScroll)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun DiagnosticChecklistRow(item: DiagnosticItem) {
|
||||||
|
val (statusSymbol, statusColor, statusText) = when (item.status) {
|
||||||
|
DiagnosticStatus.SUCCESS -> Triple("✓", Color(0xFF2E7D32), "Success")
|
||||||
|
DiagnosticStatus.FAILED -> Triple("✗", Color(0xFFD32F2F), "Failed")
|
||||||
|
DiagnosticStatus.RUNNING -> Triple("⏳", Color(0xFFF57F17), "Running")
|
||||||
|
DiagnosticStatus.PENDING -> Triple("○", Color.Gray, "Pending")
|
||||||
|
}
|
||||||
|
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(vertical = 4.dp),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
text = "${item.id}. ${item.name}",
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
fontSize = 13.sp
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = item.message ?: item.description,
|
||||||
|
fontSize = 11.sp,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
|
|
||||||
|
Surface(
|
||||||
|
color = statusColor,
|
||||||
|
shape = RoundedCornerShape(12.dp)
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "$statusSymbol $statusText",
|
||||||
|
color = Color.White,
|
||||||
|
fontSize = 11.sp,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,407 @@
|
|||||||
|
package com.example.netshareecohub.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.layout.widthIn
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Info
|
||||||
|
import androidx.compose.material.icons.filled.PlayArrow
|
||||||
|
import androidx.compose.material.icons.filled.Refresh
|
||||||
|
import androidx.compose.material.icons.filled.Stop
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.ButtonDefaults
|
||||||
|
import androidx.compose.material3.Card
|
||||||
|
import androidx.compose.material3.CardDefaults
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedButton
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.PrimaryTabRow
|
||||||
|
import androidx.compose.material3.Scaffold
|
||||||
|
import androidx.compose.material3.Tab
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TopAppBar
|
||||||
|
import androidx.compose.material3.TopAppBarDefaults
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.collectAsState
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.text.font.FontFamily
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import com.example.netshareecohub.data.logging.LogEntry
|
||||||
|
import com.example.netshareecohub.data.logging.LogLevel
|
||||||
|
import com.example.netshareecohub.data.logging.Logger
|
||||||
|
import com.example.netshareecohub.dhcp.DhcpServer
|
||||||
|
import com.example.netshareecohub.dhcp.DhcpServerConfig
|
||||||
|
import com.example.netshareecohub.dhcp.DhcpServerStatus
|
||||||
|
import com.example.netshareecohub.dhcp.ServerState
|
||||||
|
import com.example.netshareecohub.ethernet.EthernetInterfaceInfo
|
||||||
|
import com.example.netshareecohub.ethernet.EthernetManager
|
||||||
|
import com.example.netshareecohub.ethernet.InterfaceRole
|
||||||
|
import com.example.netshareecohub.ethernet.UpstreamConnectivityInfo
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun EthernetDhcpDashboard(
|
||||||
|
ethernetManager: EthernetManager,
|
||||||
|
dhcpServer: DhcpServer
|
||||||
|
) {
|
||||||
|
val interfaces by ethernetManager.interfaces.collectAsState()
|
||||||
|
val upstreamInfo by ethernetManager.upstreamInfo.collectAsState()
|
||||||
|
val serverStatus by dhcpServer.status.collectAsState()
|
||||||
|
val config by dhcpServer.leaseRepository.config.collectAsState()
|
||||||
|
val logs by Logger.logs.collectAsState()
|
||||||
|
|
||||||
|
var selectedTabIndex by remember { mutableIntStateOf(0) }
|
||||||
|
val tabs = listOf("Interfaces", "DHCP Server", "Logs")
|
||||||
|
|
||||||
|
Scaffold(
|
||||||
|
topBar = {
|
||||||
|
TopAppBar(
|
||||||
|
title = { Text("Ecohub iphone unlocker app") },
|
||||||
|
colors = TopAppBarDefaults.topAppBarColors(
|
||||||
|
containerColor = MaterialTheme.colorScheme.primaryContainer,
|
||||||
|
titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer
|
||||||
|
),
|
||||||
|
actions = {
|
||||||
|
IconButton(onClick = { ethernetManager.refreshAll() }) {
|
||||||
|
Icon(Icons.Default.Refresh, contentDescription = "Refresh Interfaces")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
) { innerPadding ->
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(innerPadding)
|
||||||
|
) {
|
||||||
|
// Upstream Status Banner
|
||||||
|
UpstreamBanner(upstreamInfo = upstreamInfo)
|
||||||
|
|
||||||
|
// Tabs
|
||||||
|
PrimaryTabRow(selectedTabIndex = selectedTabIndex) {
|
||||||
|
tabs.forEachIndexed { index, title ->
|
||||||
|
Tab(
|
||||||
|
selected = selectedTabIndex == index,
|
||||||
|
onClick = { selectedTabIndex = index },
|
||||||
|
text = { Text(title) }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(12.dp),
|
||||||
|
contentAlignment = Alignment.TopCenter
|
||||||
|
) {
|
||||||
|
Box(modifier = Modifier.widthIn(max = 600.dp).fillMaxSize()) {
|
||||||
|
when (selectedTabIndex) {
|
||||||
|
0 -> InterfacesList(interfaces = interfaces)
|
||||||
|
1 -> DhcpServerControlScreen(
|
||||||
|
serverStatus = serverStatus,
|
||||||
|
config = config,
|
||||||
|
onStartServer = { dhcpServer.start() },
|
||||||
|
onStopServer = { dhcpServer.stop() },
|
||||||
|
onUpdateConfig = { dhcpServer.updateConfig(it) }
|
||||||
|
)
|
||||||
|
2 -> LogsConsoleScreen(logs = logs, onClear = { Logger.clear() })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun UpstreamBanner(upstreamInfo: UpstreamConnectivityInfo) {
|
||||||
|
val bgColor = if (upstreamInfo.isConnected) Color(0xFF1B5E20) else Color(0xFFB71C1C)
|
||||||
|
Card(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(8.dp),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = bgColor)
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.padding(12.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.Info,
|
||||||
|
contentDescription = null,
|
||||||
|
tint = Color.White
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
|
Column {
|
||||||
|
Text(
|
||||||
|
text = "Upstream: ${upstreamInfo.type.name} (${if (upstreamInfo.isConnected) "Connected" else "Disconnected"})",
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = Color.White
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = upstreamInfo.details,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
color = Color.White.copy(alpha = 0.8f)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun InterfacesList(interfaces: List<EthernetInterfaceInfo>) {
|
||||||
|
if (interfaces.isEmpty()) {
|
||||||
|
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||||
|
Text("No network interfaces detected.")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
items(interfaces) { iface ->
|
||||||
|
InterfaceCard(iface = iface)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun InterfaceCard(iface: EthernetInterfaceInfo) {
|
||||||
|
val statusColor = if (iface.isUp) Color(0xFF2E7D32) else Color.Gray
|
||||||
|
val roleColor = when (iface.role) {
|
||||||
|
InterfaceRole.LAN -> MaterialTheme.colorScheme.primary
|
||||||
|
InterfaceRole.UPSTREAM -> MaterialTheme.colorScheme.tertiary
|
||||||
|
InterfaceRole.LOOPBACK -> Color.DarkGray
|
||||||
|
InterfaceRole.UNKNOWN -> Color.Gray
|
||||||
|
}
|
||||||
|
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
elevation = CardDefaults.cardElevation(2.dp)
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.padding(12.dp)) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Text(text = iface.displayName, fontWeight = FontWeight.Bold, fontSize = 16.sp)
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.background(statusColor, RoundedCornerShape(4.dp))
|
||||||
|
.padding(horizontal = 8.dp, vertical = 2.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = if (iface.isUp) "UP" else "DOWN",
|
||||||
|
color = Color.White,
|
||||||
|
fontSize = 11.sp,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(4.dp))
|
||||||
|
Row {
|
||||||
|
Text("Role: ", fontWeight = FontWeight.SemiBold, fontSize = 12.sp)
|
||||||
|
Text(iface.role.name, color = roleColor, fontWeight = FontWeight.Bold, fontSize = 12.sp)
|
||||||
|
Spacer(modifier = Modifier.width(16.dp))
|
||||||
|
Text("MAC: ", fontWeight = FontWeight.SemiBold, fontSize = 12.sp)
|
||||||
|
Text(iface.macAddress, fontSize = 12.sp)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(2.dp))
|
||||||
|
Text("Link Address: ${iface.linkAddress ?: "N/A"}", fontSize = 12.sp)
|
||||||
|
Text("Broadcast Address: ${iface.broadcastAddress ?: "N/A"}", fontSize = 12.sp)
|
||||||
|
Text("MTU: ${iface.mtu} | Multicast: ${iface.supportsMulticast}", fontSize = 12.sp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun DhcpServerControlScreen(
|
||||||
|
serverStatus: DhcpServerStatus,
|
||||||
|
config: DhcpServerConfig,
|
||||||
|
onStartServer: () -> Unit,
|
||||||
|
onStopServer: () -> Unit,
|
||||||
|
onUpdateConfig: (DhcpServerConfig) -> Unit
|
||||||
|
) {
|
||||||
|
var poolStart by remember(config) { mutableStateOf(config.poolStartIp) }
|
||||||
|
var poolEnd by remember(config) { mutableStateOf(config.poolEndIp) }
|
||||||
|
var gateway by remember(config) { mutableStateOf(config.routerIp) }
|
||||||
|
var subnet by remember(config) { mutableStateOf(config.subnetMask) }
|
||||||
|
var dns by remember(config) { mutableStateOf(config.dnsServers.joinToString(", ")) }
|
||||||
|
var leaseDuration by remember(config) { mutableStateOf(config.defaultLeaseTimeSeconds.toString()) }
|
||||||
|
|
||||||
|
Column(modifier = Modifier.fillMaxSize()) {
|
||||||
|
Card(modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Column(modifier = Modifier.padding(12.dp)) {
|
||||||
|
Text("DHCP Server Status", fontWeight = FontWeight.Bold, fontSize = 16.sp)
|
||||||
|
Spacer(modifier = Modifier.height(4.dp))
|
||||||
|
Text("State: ${serverStatus.state}", fontWeight = FontWeight.SemiBold)
|
||||||
|
Text("Bound Port: ${serverStatus.boundPort} | Address: ${serverStatus.boundAddress ?: "0.0.0.0"}")
|
||||||
|
Text("Active Leases: ${serverStatus.activeLeaseCount}")
|
||||||
|
Text("Packets Received: ${serverStatus.totalPacketsReceived} | Sent: ${serverStatus.totalPacketsSent}")
|
||||||
|
|
||||||
|
if (serverStatus.errorMessage != null) {
|
||||||
|
Text("Error: ${serverStatus.errorMessage}", color = MaterialTheme.colorScheme.error)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
Row {
|
||||||
|
if (serverStatus.state != ServerState.RUNNING) {
|
||||||
|
Button(onClick = onStartServer) {
|
||||||
|
Icon(Icons.Default.PlayArrow, contentDescription = null)
|
||||||
|
Spacer(modifier = Modifier.width(4.dp))
|
||||||
|
Text("Start Server")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Button(
|
||||||
|
onClick = onStopServer,
|
||||||
|
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error)
|
||||||
|
) {
|
||||||
|
Icon(Icons.Default.Stop, contentDescription = null)
|
||||||
|
Spacer(modifier = Modifier.width(4.dp))
|
||||||
|
Text("Stop Server")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
|
|
||||||
|
Text("Pool Configuration", fontWeight = FontWeight.Bold, fontSize = 16.sp)
|
||||||
|
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
item {
|
||||||
|
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = poolStart,
|
||||||
|
onValueChange = { poolStart = it },
|
||||||
|
label = { Text("Pool Start IP") },
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
)
|
||||||
|
OutlinedTextField(
|
||||||
|
value = poolEnd,
|
||||||
|
onValueChange = { poolEnd = it },
|
||||||
|
label = { Text("Pool End IP") },
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item {
|
||||||
|
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = gateway,
|
||||||
|
onValueChange = { gateway = it },
|
||||||
|
label = { Text("Gateway IP") },
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
)
|
||||||
|
OutlinedTextField(
|
||||||
|
value = subnet,
|
||||||
|
onValueChange = { subnet = it },
|
||||||
|
label = { Text("Subnet Mask") },
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = dns,
|
||||||
|
onValueChange = { dns = it },
|
||||||
|
label = { Text("DNS Servers (comma separated)") },
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
item {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = leaseDuration,
|
||||||
|
onValueChange = { leaseDuration = it },
|
||||||
|
label = { Text("Lease Time (seconds)") },
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
item {
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
val duration = leaseDuration.toLongOrNull() ?: 86400L
|
||||||
|
val dnsList = dns.split(",").map { it.trim() }.filter { it.isNotEmpty() }
|
||||||
|
onUpdateConfig(
|
||||||
|
config.copy(
|
||||||
|
poolStartIp = poolStart.trim(),
|
||||||
|
poolEndIp = poolEnd.trim(),
|
||||||
|
routerIp = gateway.trim(),
|
||||||
|
subnetMask = subnet.trim(),
|
||||||
|
dnsServers = dnsList,
|
||||||
|
defaultLeaseTimeSeconds = duration
|
||||||
|
)
|
||||||
|
)
|
||||||
|
},
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
Text("Apply Configuration Changes")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun LogsConsoleScreen(logs: List<LogEntry>, onClear: () -> Unit) {
|
||||||
|
Column(modifier = Modifier.fillMaxSize()) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Text("Structured Event Console (${logs.size} entries)", fontWeight = FontWeight.Bold)
|
||||||
|
OutlinedButton(onClick = onClear) {
|
||||||
|
Text("Clear")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Spacer(modifier = Modifier.height(4.dp))
|
||||||
|
LazyColumn(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.background(Color.Black, RoundedCornerShape(4.dp))
|
||||||
|
.padding(8.dp)
|
||||||
|
) {
|
||||||
|
items(logs.reversed()) { entry ->
|
||||||
|
val logColor = when (entry.level) {
|
||||||
|
LogLevel.INFO -> Color(0xFF81C784)
|
||||||
|
LogLevel.WARN -> Color(0xFFFFB74D)
|
||||||
|
LogLevel.ERROR -> Color(0xFFE57373)
|
||||||
|
LogLevel.DEBUG -> Color.LightGray
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
text = entry.toString(),
|
||||||
|
color = logColor,
|
||||||
|
fontSize = 11.sp,
|
||||||
|
fontFamily = FontFamily.Monospace
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,308 @@
|
|||||||
|
package com.example.netshareecohub.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Warning
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.Card
|
||||||
|
import androidx.compose.material3.CardDefaults
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.ExposedDropdownMenuBox
|
||||||
|
import androidx.compose.material3.ExposedDropdownMenuDefaults
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import com.example.netshareecohub.dhcp.DhcpServerConfig
|
||||||
|
import com.example.netshareecohub.ethernet.EthernetAdapterInfo
|
||||||
|
import com.example.netshareecohub.ethernet.SpeedMode
|
||||||
|
|
||||||
|
import androidx.compose.material3.MenuAnchorType
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.material3.ButtonDefaults
|
||||||
|
import com.example.netshareecohub.util.AppLanguageManager
|
||||||
|
import com.example.netshareecohub.ui.components.EcohubWatermark
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun EthernetSettingsScreen(
|
||||||
|
adapter: EthernetAdapterInfo?,
|
||||||
|
dhcpConfig: DhcpServerConfig,
|
||||||
|
isSpeedConfigSupported: Boolean,
|
||||||
|
speedConfigMessage: String,
|
||||||
|
onApplySpeed: (iface: String, mode: SpeedMode) -> Unit,
|
||||||
|
onSaveDhcpConfig: (DhcpServerConfig) -> Unit,
|
||||||
|
onOpenSystemTethering: () -> Unit
|
||||||
|
) {
|
||||||
|
val scrollState = rememberScrollState()
|
||||||
|
val context = LocalContext.current
|
||||||
|
val currentLang = AppLanguageManager.getSavedLanguage(context)
|
||||||
|
|
||||||
|
var selectedSpeedMode by remember { mutableStateOf(SpeedMode.AUTO) }
|
||||||
|
var speedDropdownExpanded by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.verticalScroll(scrollState)
|
||||||
|
.padding(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||||
|
) {
|
||||||
|
// Language Selector Card
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.padding(16.dp)) {
|
||||||
|
Text(
|
||||||
|
text = "Language / 语言",
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
style = MaterialTheme.typography.titleMedium
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||||
|
) {
|
||||||
|
Button(
|
||||||
|
onClick = { AppLanguageManager.setLanguage(context, "en") },
|
||||||
|
colors = ButtonDefaults.buttonColors(
|
||||||
|
containerColor = if (currentLang == "en") MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surface
|
||||||
|
),
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "English",
|
||||||
|
color = if (currentLang == "en") MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurface
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Button(
|
||||||
|
onClick = { AppLanguageManager.setLanguage(context, "zh-CN") },
|
||||||
|
colors = ButtonDefaults.buttonColors(
|
||||||
|
containerColor = if (currentLang == "zh-CN") MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surface
|
||||||
|
),
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "简体中文",
|
||||||
|
color = if (currentLang == "zh-CN") MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurface
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Section 1: Adapter Info
|
||||||
|
Text(
|
||||||
|
text = "Adapter Details",
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
|
||||||
|
if (adapter == null) {
|
||||||
|
Card(
|
||||||
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer),
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "🔌 No USB Ethernet Adapter Connected. Please connect a USB Ethernet OTG adapter (eth0 / usb0) to view details.",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = MaterialTheme.colorScheme.onSecondaryContainer,
|
||||||
|
modifier = Modifier.padding(14.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Card(modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Column(modifier = Modifier.padding(16.dp)) {
|
||||||
|
DashboardDetailRow("Interface Name", adapter?.name ?: "N/A")
|
||||||
|
DashboardDetailRow("MAC Address", adapter?.macAddress ?: "00:00:00:00:00:00")
|
||||||
|
DashboardDetailRow("Link Status", if (adapter?.isUp == true) "UP (${adapter.operstate.uppercase()})" else "DOWN")
|
||||||
|
DashboardDetailRow("Negotiated Speed", if (adapter != null && adapter.speedMbps > 0) "${adapter.speedMbps} Mbps" else "Unknown")
|
||||||
|
DashboardDetailRow("Duplex Mode", adapter?.duplex ?: "Unknown")
|
||||||
|
DashboardDetailRow("MTU", "${adapter?.mtu ?: 1500}")
|
||||||
|
DashboardDetailRow("RX Bytes", "${adapter?.stats?.rxBytes ?: 0L}")
|
||||||
|
DashboardDetailRow("TX Bytes", "${adapter?.stats?.txBytes ?: 0L}")
|
||||||
|
DashboardDetailRow("RX Packets", "${adapter?.stats?.rxPackets ?: 0L}")
|
||||||
|
DashboardDetailRow("TX Packets", "${adapter?.stats?.txPackets ?: 0L}")
|
||||||
|
DashboardDetailRow("RX Errors", "${adapter?.stats?.rxErrors ?: 0L}")
|
||||||
|
DashboardDetailRow("TX Errors", "${adapter?.stats?.txErrors ?: 0L}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Section 2: Speed Configuration
|
||||||
|
Text(
|
||||||
|
text = "Ethernet Speed Configuration",
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
|
||||||
|
Card(modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Column(modifier = Modifier.padding(16.dp)) {
|
||||||
|
Text(
|
||||||
|
text = "Current Speed: ${if (adapter != null && adapter.speedMbps > 0) "${adapter.speedMbps} Mbps (${adapter.duplex})" else "Auto / Unknown"}",
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
fontWeight = FontWeight.SemiBold
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
|
|
||||||
|
ExposedDropdownMenuBox(
|
||||||
|
expanded = speedDropdownExpanded,
|
||||||
|
onExpandedChange = { speedDropdownExpanded = !speedDropdownExpanded }
|
||||||
|
) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = selectedSpeedMode.label,
|
||||||
|
onValueChange = {},
|
||||||
|
readOnly = true,
|
||||||
|
label = { Text("Speed Mode") },
|
||||||
|
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = speedDropdownExpanded) },
|
||||||
|
modifier = Modifier
|
||||||
|
.menuAnchor(MenuAnchorType.PrimaryNotEditable)
|
||||||
|
.fillMaxWidth()
|
||||||
|
)
|
||||||
|
|
||||||
|
ExposedDropdownMenu(
|
||||||
|
expanded = speedDropdownExpanded,
|
||||||
|
onDismissRequest = { speedDropdownExpanded = false }
|
||||||
|
) {
|
||||||
|
SpeedMode.entries.forEach { mode ->
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text(mode.label) },
|
||||||
|
onClick = {
|
||||||
|
selectedSpeedMode = mode
|
||||||
|
speedDropdownExpanded = false
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
|
|
||||||
|
if (!isSpeedConfigSupported) {
|
||||||
|
Card(
|
||||||
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer),
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.padding(12.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
Icons.Default.Warning,
|
||||||
|
contentDescription = null,
|
||||||
|
tint = MaterialTheme.colorScheme.error
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
|
Text(
|
||||||
|
text = speedConfigMessage,
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onErrorContainer
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
|
}
|
||||||
|
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
val iface = adapter?.name ?: "eth0"
|
||||||
|
onApplySpeed(iface, selectedSpeedMode)
|
||||||
|
},
|
||||||
|
enabled = isSpeedConfigSupported,
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
Text("Apply Speed Configuration")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Section 3: Automatic LAN / Gateway Configuration
|
||||||
|
Text(
|
||||||
|
text = "Automatic LAN & Gateway Configuration",
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
|
||||||
|
Card(modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.padding(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(10.dp)
|
||||||
|
) {
|
||||||
|
Card(
|
||||||
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer),
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "● Automatic Management Active: IP, Gateway, and DHCP ranges are dynamically managed by the system.",
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||||
|
modifier = Modifier.padding(12.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
DashboardDetailRow("Gateway IP (Auto)", dhcpConfig.routerIp)
|
||||||
|
DashboardDetailRow("Subnet Mask (Auto)", dhcpConfig.subnetMask)
|
||||||
|
DashboardDetailRow("DHCP Start IP", dhcpConfig.poolStartIp)
|
||||||
|
DashboardDetailRow("DHCP End IP", dhcpConfig.poolEndIp)
|
||||||
|
DashboardDetailRow("DNS Server(s)", dhcpConfig.dnsServers.joinToString(", "))
|
||||||
|
DashboardDetailRow("Default Lease Time", "${dhcpConfig.defaultLeaseTimeSeconds} seconds")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Section 4: System Tethering Settings Integration
|
||||||
|
Text(
|
||||||
|
text = "Android System Tethering",
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
|
||||||
|
Card(modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.padding(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "For physical USB-Ethernet connections on non-rooted Android, kernel permissions block direct UDP port 67 binding. Use native Android System Ethernet Tethering to enable hardware clients to obtain IP leases seamlessly.",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
|
||||||
|
Button(
|
||||||
|
onClick = onOpenSystemTethering,
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
Text(stringResource(R.string.tethering_support))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
EcohubWatermark()
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
package com.example.netshareecohub.ui
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Clear
|
||||||
|
import androidx.compose.material.icons.filled.Search
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.FilterChip
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedButton
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.font.FontFamily
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import com.example.netshareecohub.data.logging.LogEntry
|
||||||
|
import com.example.netshareecohub.data.logging.LogLevel
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun NetworkLogsScreen(
|
||||||
|
logs: List<LogEntry>,
|
||||||
|
onClearLogs: () -> Unit,
|
||||||
|
onCopyLogs: (context: Context) -> Unit
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
var searchQuery by remember { mutableStateOf("") }
|
||||||
|
var selectedLevelFilter by remember { mutableStateOf<LogLevel?>(null) }
|
||||||
|
|
||||||
|
val filteredLogs = remember(logs, searchQuery, selectedLevelFilter) {
|
||||||
|
logs.filter { entry ->
|
||||||
|
val matchesLevel = selectedLevelFilter == null || entry.level == selectedLevelFilter
|
||||||
|
val matchesQuery = searchQuery.isBlank() ||
|
||||||
|
entry.message.contains(searchQuery, ignoreCase = true) ||
|
||||||
|
entry.tag.contains(searchQuery, ignoreCase = true)
|
||||||
|
matchesLevel && matchesQuery
|
||||||
|
}.reversed()
|
||||||
|
}
|
||||||
|
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||||
|
) {
|
||||||
|
// Title & Top Action Buttons
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Live Network Logs (${filteredLogs.size})",
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
OutlinedButton(onClick = { onCopyLogs(context) }) {
|
||||||
|
Text("Copy All", fontSize = 11.sp)
|
||||||
|
}
|
||||||
|
Button(onClick = onClearLogs) {
|
||||||
|
Text("Clear", fontSize = 11.sp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Search Text Field
|
||||||
|
OutlinedTextField(
|
||||||
|
value = searchQuery,
|
||||||
|
onValueChange = { searchQuery = it },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
label = { Text("Search logs...") },
|
||||||
|
leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) },
|
||||||
|
trailingIcon = {
|
||||||
|
if (searchQuery.isNotEmpty()) {
|
||||||
|
IconButton(onClick = { searchQuery = "" }) {
|
||||||
|
Icon(Icons.Default.Clear, contentDescription = "Clear search")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
singleLine = true
|
||||||
|
)
|
||||||
|
|
||||||
|
// Level Selector Chips
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(6.dp)
|
||||||
|
) {
|
||||||
|
FilterChip(
|
||||||
|
selected = selectedLevelFilter == null,
|
||||||
|
onClick = { selectedLevelFilter = null },
|
||||||
|
label = { Text("ALL", fontSize = 10.sp) }
|
||||||
|
)
|
||||||
|
|
||||||
|
LogLevel.entries.forEach { level ->
|
||||||
|
FilterChip(
|
||||||
|
selected = selectedLevelFilter == level,
|
||||||
|
onClick = { selectedLevelFilter = if (selectedLevelFilter == level) null else level },
|
||||||
|
label = { Text(level.name, fontSize = 10.sp) }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Log Console Area
|
||||||
|
if (filteredLogs.isEmpty()) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
contentAlignment = Alignment.Center
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "No log entries found.",
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
LazyColumn(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.background(Color(0xFF121212), RoundedCornerShape(8.dp))
|
||||||
|
.padding(10.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(4.dp)
|
||||||
|
) {
|
||||||
|
items(filteredLogs) { entry ->
|
||||||
|
val textColor = when (entry.level) {
|
||||||
|
LogLevel.INFO -> Color(0xFF81C784)
|
||||||
|
LogLevel.WARN -> Color(0xFFFFB74D)
|
||||||
|
LogLevel.ERROR -> Color(0xFFE57373)
|
||||||
|
LogLevel.DEBUG -> Color.LightGray
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
text = entry.toString(),
|
||||||
|
color = textColor,
|
||||||
|
fontSize = 11.sp,
|
||||||
|
fontFamily = FontFamily.Monospace
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
package com.example.netshareecohub.ui.auth
|
||||||
|
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.widthIn
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Add
|
||||||
|
import androidx.compose.material.icons.filled.Delete
|
||||||
|
import androidx.compose.material.icons.filled.Edit
|
||||||
|
import androidx.compose.material.icons.automirrored.filled.ExitToApp
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
|
||||||
|
import androidx.compose.material3.Card
|
||||||
|
import androidx.compose.material3.CardDefaults
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.collectAsState
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import com.example.netshareecohub.data.auth.User
|
||||||
|
import com.example.netshareecohub.viewmodel.AuthViewModel
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun AdminScreen(authViewModel: AuthViewModel) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val allUsers by authViewModel.allUsers.collectAsState(initial = emptyList())
|
||||||
|
val currentUser by authViewModel.currentUser.collectAsState()
|
||||||
|
|
||||||
|
var showCreateDialog by remember { mutableStateOf(false) }
|
||||||
|
var selectedUserForPasswordChange by remember { mutableStateOf<User?>(null) }
|
||||||
|
|
||||||
|
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.widthIn(max = 600.dp)
|
||||||
|
.padding(16.dp),
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "User Management",
|
||||||
|
style = MaterialTheme.typography.titleLarge,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
IconButton(onClick = { authViewModel.logout() }) {
|
||||||
|
Icon(Icons.AutoMirrored.Filled.ExitToApp, contentDescription = "Logout", tint = MaterialTheme.colorScheme.error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|
||||||
|
if (currentUser?.role == "ADMIN") {
|
||||||
|
Button(
|
||||||
|
onClick = { showCreateDialog = true },
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
Icon(Icons.Default.Add, contentDescription = null)
|
||||||
|
Text(" Create New User")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|
||||||
|
Text("Registered Users", fontWeight = FontWeight.Bold, modifier = Modifier.padding(bottom = 8.dp))
|
||||||
|
|
||||||
|
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
items(allUsers) { user ->
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(16.dp),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Column {
|
||||||
|
Text(user.username, fontWeight = FontWeight.Bold, fontSize = 16.sp)
|
||||||
|
Text(user.role, color = if (user.role == "ADMIN") MaterialTheme.colorScheme.primary else Color.Gray, fontSize = 12.sp)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentUser?.role == "ADMIN" || currentUser?.id == user.id) {
|
||||||
|
Row {
|
||||||
|
IconButton(onClick = { selectedUserForPasswordChange = user }) {
|
||||||
|
Icon(Icons.Default.Edit, contentDescription = "Change Password", tint = MaterialTheme.colorScheme.primary)
|
||||||
|
}
|
||||||
|
if (currentUser?.role == "ADMIN" && user.username != "Ecohub") {
|
||||||
|
IconButton(onClick = {
|
||||||
|
authViewModel.deleteUser(user) { _, msg ->
|
||||||
|
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}) {
|
||||||
|
Icon(Icons.Default.Delete, contentDescription = "Delete User", tint = MaterialTheme.colorScheme.error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (showCreateDialog) {
|
||||||
|
var newUsername by remember { mutableStateOf("") }
|
||||||
|
var newPassword by remember { mutableStateOf("") }
|
||||||
|
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { showCreateDialog = false },
|
||||||
|
title = { Text("Create New Normal User") },
|
||||||
|
text = {
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = newUsername,
|
||||||
|
onValueChange = { newUsername = it },
|
||||||
|
label = { Text("Username") },
|
||||||
|
singleLine = true
|
||||||
|
)
|
||||||
|
OutlinedTextField(
|
||||||
|
value = newPassword,
|
||||||
|
onValueChange = { newPassword = it },
|
||||||
|
label = { Text("Password") },
|
||||||
|
singleLine = true
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = {
|
||||||
|
Button(onClick = {
|
||||||
|
if (newUsername.isNotBlank() && newPassword.isNotBlank()) {
|
||||||
|
authViewModel.createNewUser(newUsername.trim(), newPassword, "NORMAL") { success, msg ->
|
||||||
|
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
|
||||||
|
if (success) showCreateDialog = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}) {
|
||||||
|
Text("Create")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = { showCreateDialog = false }) {
|
||||||
|
Text("Cancel")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (selectedUserForPasswordChange != null) {
|
||||||
|
var newPassword by remember { mutableStateOf("") }
|
||||||
|
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { selectedUserForPasswordChange = null },
|
||||||
|
title = { Text("Change Password for ${selectedUserForPasswordChange?.username}") },
|
||||||
|
text = {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = newPassword,
|
||||||
|
onValueChange = { newPassword = it },
|
||||||
|
label = { Text("New Password") },
|
||||||
|
singleLine = true
|
||||||
|
)
|
||||||
|
},
|
||||||
|
confirmButton = {
|
||||||
|
Button(onClick = {
|
||||||
|
if (newPassword.isNotBlank()) {
|
||||||
|
authViewModel.changePassword(selectedUserForPasswordChange!!, newPassword)
|
||||||
|
Toast.makeText(context, "Password updated", Toast.LENGTH_SHORT).show()
|
||||||
|
selectedUserForPasswordChange = null
|
||||||
|
}
|
||||||
|
}) {
|
||||||
|
Text("Update")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = { selectedUserForPasswordChange = null }) {
|
||||||
|
Text("Cancel")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
package com.example.netshareecohub.ui.auth
|
||||||
|
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.widthIn
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.text.KeyboardActions
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Visibility
|
||||||
|
import androidx.compose.material.icons.filled.VisibilityOff
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.collectAsState
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.focus.FocusDirection
|
||||||
|
import androidx.compose.ui.platform.LocalFocusManager
|
||||||
|
import androidx.compose.ui.res.painterResource
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.input.ImeAction
|
||||||
|
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||||
|
import androidx.compose.ui.text.input.VisualTransformation
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import com.example.netshareecohub.R
|
||||||
|
import com.example.netshareecohub.viewmodel.AuthViewModel
|
||||||
|
import com.example.netshareecohub.ui.components.EcohubWatermark
|
||||||
|
import com.example.netshareecohub.ui.components.EcohubRepeatingWatermark
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun LoginScreen(authViewModel: AuthViewModel) {
|
||||||
|
var username by remember { mutableStateOf("") }
|
||||||
|
var password by remember { mutableStateOf("") }
|
||||||
|
var passwordVisible by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
|
val loginError by authViewModel.loginError.collectAsState()
|
||||||
|
val isLoginInProgress by authViewModel.isLoginInProgress.collectAsState()
|
||||||
|
val focusManager = LocalFocusManager.current
|
||||||
|
val scrollState = rememberScrollState()
|
||||||
|
|
||||||
|
Surface(
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
color = MaterialTheme.colorScheme.background
|
||||||
|
) {
|
||||||
|
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) {
|
||||||
|
EcohubRepeatingWatermark()
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.widthIn(max = 400.dp)
|
||||||
|
.verticalScroll(scrollState)
|
||||||
|
.padding(horizontal = 24.dp, vertical = 24.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally
|
||||||
|
) {
|
||||||
|
Spacer(modifier = Modifier.height(20.dp))
|
||||||
|
|
||||||
|
Image(
|
||||||
|
painter = painterResource(id = R.drawable.ic_logo),
|
||||||
|
contentDescription = "App Logo",
|
||||||
|
modifier = Modifier.size(80.dp)
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = "Ecohub iphone unlocker app",
|
||||||
|
style = MaterialTheme.typography.titleLarge,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = MaterialTheme.colorScheme.primary
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(4.dp))
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = "Please log in to continue",
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(24.dp))
|
||||||
|
|
||||||
|
OutlinedTextField(
|
||||||
|
value = username,
|
||||||
|
onValueChange = {
|
||||||
|
username = it
|
||||||
|
authViewModel.clearError()
|
||||||
|
},
|
||||||
|
label = { Text("User ID") },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
singleLine = true,
|
||||||
|
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
|
||||||
|
keyboardActions = KeyboardActions(
|
||||||
|
onNext = { focusManager.moveFocus(FocusDirection.Down) }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
|
|
||||||
|
OutlinedTextField(
|
||||||
|
value = password,
|
||||||
|
onValueChange = {
|
||||||
|
password = it
|
||||||
|
authViewModel.clearError()
|
||||||
|
},
|
||||||
|
label = { Text("Password") },
|
||||||
|
visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
|
||||||
|
trailingIcon = {
|
||||||
|
val image = if (passwordVisible)
|
||||||
|
Icons.Filled.Visibility
|
||||||
|
else
|
||||||
|
Icons.Filled.VisibilityOff
|
||||||
|
|
||||||
|
val description = if (passwordVisible) "Hide password" else "Show password"
|
||||||
|
|
||||||
|
IconButton(onClick = { passwordVisible = !passwordVisible }) {
|
||||||
|
Icon(imageVector = image, contentDescription = description)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
singleLine = true,
|
||||||
|
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
|
||||||
|
keyboardActions = KeyboardActions(
|
||||||
|
onDone = {
|
||||||
|
focusManager.clearFocus()
|
||||||
|
authViewModel.login(username, password)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
if (loginError != null) {
|
||||||
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
Text(
|
||||||
|
text = loginError!!,
|
||||||
|
color = MaterialTheme.colorScheme.error,
|
||||||
|
style = MaterialTheme.typography.bodySmall
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(24.dp))
|
||||||
|
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
focusManager.clearFocus()
|
||||||
|
authViewModel.login(username, password)
|
||||||
|
},
|
||||||
|
enabled = !isLoginInProgress,
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.height(50.dp),
|
||||||
|
shape = RoundedCornerShape(12.dp)
|
||||||
|
) {
|
||||||
|
if (isLoginInProgress) {
|
||||||
|
CircularProgressIndicator(
|
||||||
|
modifier = Modifier.size(24.dp),
|
||||||
|
color = MaterialTheme.colorScheme.onPrimary,
|
||||||
|
strokeWidth = 2.dp
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Text(stringResource(R.string.login), fontWeight = FontWeight.Bold)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
EcohubWatermark()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package com.example.netshareecohub.ui.components
|
||||||
|
|
||||||
|
import androidx.compose.foundation.Canvas
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.geometry.Offset
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.drawscope.rotate
|
||||||
|
import androidx.compose.ui.text.TextStyle
|
||||||
|
import androidx.compose.ui.text.drawText
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.rememberTextMeasurer
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun EcohubRepeatingWatermark(modifier: Modifier = Modifier) {
|
||||||
|
val textMeasurer = rememberTextMeasurer()
|
||||||
|
val watermarkText = "ECOHUB"
|
||||||
|
val textColor = Color.Gray.copy(alpha = 0.06f)
|
||||||
|
|
||||||
|
Box(modifier = modifier.fillMaxSize()) {
|
||||||
|
Canvas(modifier = Modifier.fillMaxSize()) {
|
||||||
|
val measuredText = textMeasurer.measure(
|
||||||
|
text = watermarkText,
|
||||||
|
style = TextStyle(
|
||||||
|
color = textColor,
|
||||||
|
fontSize = 20.sp,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
val spacingX = measuredText.size.width * 2.5f
|
||||||
|
val spacingY = measuredText.size.height * 3.5f
|
||||||
|
|
||||||
|
val cols = (size.width / spacingX).toInt() + 2
|
||||||
|
val rows = (size.height / spacingY).toInt() + 2
|
||||||
|
|
||||||
|
for (row in -1..rows) {
|
||||||
|
for (col in -1..cols) {
|
||||||
|
val x = col * spacingX + (if (row % 2 == 0) 0f else spacingX / 2f)
|
||||||
|
val y = row * spacingY
|
||||||
|
|
||||||
|
rotate(degrees = -30f, pivot = Offset(x, y)) {
|
||||||
|
drawText(
|
||||||
|
textLayoutResult = measuredText,
|
||||||
|
topLeft = Offset(x, y)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package com.example.netshareecohub.ui.components
|
||||||
|
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.painterResource
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import com.example.netshareecohub.R
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun EcohubWatermark(modifier: Modifier = Modifier) {
|
||||||
|
Row(
|
||||||
|
modifier = modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(vertical = 4.dp, horizontal = 8.dp),
|
||||||
|
horizontalArrangement = Arrangement.Center,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Image(
|
||||||
|
painter = painterResource(id = R.drawable.ic_logo),
|
||||||
|
contentDescription = "ECOHUB Logo",
|
||||||
|
modifier = Modifier.size(16.dp)
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.width(6.dp))
|
||||||
|
Text(
|
||||||
|
text = "ECOHUB Technologies Limited",
|
||||||
|
fontSize = 11.sp,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.example.netshareecohub.ui.theme
|
||||||
|
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
|
||||||
|
val Purple80 = Color(0xFFD0BCFF)
|
||||||
|
val PurpleGrey80 = Color(0xFFCCC2DC)
|
||||||
|
val Pink80 = Color(0xFFEFB8C8)
|
||||||
|
|
||||||
|
val Purple40 = Color(0xFF6650a4)
|
||||||
|
val PurpleGrey40 = Color(0xFF625b71)
|
||||||
|
val Pink40 = Color(0xFF7D5260)
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package com.example.netshareecohub.ui.theme
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.os.Build
|
||||||
|
import androidx.compose.foundation.isSystemInDarkTheme
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.darkColorScheme
|
||||||
|
import androidx.compose.material3.dynamicDarkColorScheme
|
||||||
|
import androidx.compose.material3.dynamicLightColorScheme
|
||||||
|
import androidx.compose.material3.lightColorScheme
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
|
||||||
|
private val DarkColorScheme = darkColorScheme(
|
||||||
|
primary = Purple80,
|
||||||
|
secondary = PurpleGrey80,
|
||||||
|
tertiary = Pink80
|
||||||
|
)
|
||||||
|
|
||||||
|
private val LightColorScheme = lightColorScheme(
|
||||||
|
primary = Purple40,
|
||||||
|
secondary = PurpleGrey40,
|
||||||
|
tertiary = Pink40
|
||||||
|
|
||||||
|
/* Other default colors to override
|
||||||
|
background = Color(0xFFFFFBFE),
|
||||||
|
surface = Color(0xFFFFFBFE),
|
||||||
|
onPrimary = Color.White,
|
||||||
|
onSecondary = Color.White,
|
||||||
|
onTertiary = Color.White,
|
||||||
|
onBackground = Color(0xFF1C1B1F),
|
||||||
|
onSurface = Color(0xFF1C1B1F),
|
||||||
|
*/
|
||||||
|
)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun NetShareEcohubTheme(
|
||||||
|
darkTheme: Boolean = isSystemInDarkTheme(),
|
||||||
|
// Dynamic color is available on Android 12+
|
||||||
|
dynamicColor: Boolean = true,
|
||||||
|
content: @Composable () -> Unit
|
||||||
|
) {
|
||||||
|
val colorScheme = when {
|
||||||
|
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
|
||||||
|
val context = LocalContext.current
|
||||||
|
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
|
||||||
|
}
|
||||||
|
|
||||||
|
darkTheme -> DarkColorScheme
|
||||||
|
else -> LightColorScheme
|
||||||
|
}
|
||||||
|
|
||||||
|
MaterialTheme(
|
||||||
|
colorScheme = colorScheme,
|
||||||
|
typography = Typography,
|
||||||
|
content = content
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package com.example.netshareecohub.ui.theme
|
||||||
|
|
||||||
|
import androidx.compose.material3.Typography
|
||||||
|
import androidx.compose.ui.text.TextStyle
|
||||||
|
import androidx.compose.ui.text.font.FontFamily
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
|
||||||
|
// Set of Material typography styles to start with
|
||||||
|
val Typography = Typography(
|
||||||
|
bodyLarge = TextStyle(
|
||||||
|
fontFamily = FontFamily.Default,
|
||||||
|
fontWeight = FontWeight.Normal,
|
||||||
|
fontSize = 16.sp,
|
||||||
|
lineHeight = 24.sp,
|
||||||
|
letterSpacing = 0.5.sp
|
||||||
|
)
|
||||||
|
/* Other default text styles to override
|
||||||
|
titleLarge = TextStyle(
|
||||||
|
fontFamily = FontFamily.Default,
|
||||||
|
fontWeight = FontWeight.Normal,
|
||||||
|
fontSize = 22.sp,
|
||||||
|
lineHeight = 28.sp,
|
||||||
|
letterSpacing = 0.sp
|
||||||
|
),
|
||||||
|
labelSmall = TextStyle(
|
||||||
|
fontFamily = FontFamily.Default,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
fontSize = 11.sp,
|
||||||
|
lineHeight = 16.sp,
|
||||||
|
letterSpacing = 0.5.sp
|
||||||
|
)
|
||||||
|
*/
|
||||||
|
)
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package com.example.netshareecohub.util
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.appcompat.app.AppCompatDelegate
|
||||||
|
import androidx.core.os.LocaleListCompat
|
||||||
|
|
||||||
|
object AppLanguageManager {
|
||||||
|
private const val PREFS_NAME = "language_prefs"
|
||||||
|
private const val KEY_LANGUAGE = "selected_language"
|
||||||
|
|
||||||
|
fun setLanguage(context: Context, languageCode: String) {
|
||||||
|
val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||||
|
prefs.edit().putString(KEY_LANGUAGE, languageCode).apply()
|
||||||
|
|
||||||
|
val appLocale = LocaleListCompat.forLanguageTags(languageCode)
|
||||||
|
AppCompatDelegate.setApplicationLocales(appLocale)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getSavedLanguage(context: Context): String {
|
||||||
|
val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||||
|
return prefs.getString(KEY_LANGUAGE, "en") ?: "en"
|
||||||
|
}
|
||||||
|
|
||||||
|
fun initLanguage(context: Context) {
|
||||||
|
val lang = getSavedLanguage(context)
|
||||||
|
val appLocale = LocaleListCompat.forLanguageTags(lang)
|
||||||
|
AppCompatDelegate.setApplicationLocales(appLocale)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
package com.example.netshareecohub.viewmodel
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.lifecycle.AndroidViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import android.os.Build
|
||||||
|
import com.example.netshareecohub.data.auth.AuthRepository
|
||||||
|
import com.example.netshareecohub.data.auth.User
|
||||||
|
import com.example.netshareecohub.network.ApiUserProfile
|
||||||
|
import com.example.netshareecohub.network.LoginRequest
|
||||||
|
import com.example.netshareecohub.network.LogRequest
|
||||||
|
import com.example.netshareecohub.network.RetrofitClient
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import java.net.NetworkInterface
|
||||||
|
import java.util.Collections
|
||||||
|
|
||||||
|
class AuthViewModel(
|
||||||
|
application: Application,
|
||||||
|
private val repository: AuthRepository
|
||||||
|
) : AndroidViewModel(application) {
|
||||||
|
|
||||||
|
private val prefs = application.getSharedPreferences("auth_session_prefs", Context.MODE_PRIVATE)
|
||||||
|
|
||||||
|
private val _currentUser = MutableStateFlow<User?>(null)
|
||||||
|
val currentUser: StateFlow<User?> = _currentUser.asStateFlow()
|
||||||
|
|
||||||
|
private val _apiUserProfile = MutableStateFlow<ApiUserProfile?>(null)
|
||||||
|
val apiUserProfile: StateFlow<ApiUserProfile?> = _apiUserProfile.asStateFlow()
|
||||||
|
|
||||||
|
private val _authToken = MutableStateFlow<String?>(null)
|
||||||
|
|
||||||
|
private val _loginError = MutableStateFlow<String?>(null)
|
||||||
|
val loginError: StateFlow<String?> = _loginError.asStateFlow()
|
||||||
|
|
||||||
|
private val _isLoginInProgress = MutableStateFlow(false)
|
||||||
|
val isLoginInProgress: StateFlow<Boolean> = _isLoginInProgress.asStateFlow()
|
||||||
|
|
||||||
|
val allUsers = repository.allUsers
|
||||||
|
|
||||||
|
init {
|
||||||
|
viewModelScope.launch {
|
||||||
|
repository.initializeDefaultUsers()
|
||||||
|
checkExistingSession()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun checkExistingSession() {
|
||||||
|
val token = prefs.getString("auth_token", null)
|
||||||
|
val username = prefs.getString("auth_username", null)
|
||||||
|
val role = prefs.getString("auth_role", "NORMAL")
|
||||||
|
val expiryTime = prefs.getLong("auth_expiry", 0L)
|
||||||
|
|
||||||
|
val currentTime = System.currentTimeMillis()
|
||||||
|
if (!token.isNullOrBlank() && !username.isNullOrBlank() && currentTime < expiryTime) {
|
||||||
|
_authToken.value = token
|
||||||
|
_currentUser.value = User(
|
||||||
|
username = username,
|
||||||
|
passwordHash = "",
|
||||||
|
role = role ?: "NORMAL"
|
||||||
|
)
|
||||||
|
fetchUserProfile()
|
||||||
|
} else {
|
||||||
|
clearSession()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun saveSession(token: String, username: String, role: String) {
|
||||||
|
val expiryTime = System.currentTimeMillis() + (12 * 60 * 60 * 1000L) // 12 hours
|
||||||
|
prefs.edit()
|
||||||
|
.putString("auth_token", token)
|
||||||
|
.putString("auth_username", username)
|
||||||
|
.putString("auth_role", role)
|
||||||
|
.putLong("auth_expiry", expiryTime)
|
||||||
|
.apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun clearSession() {
|
||||||
|
prefs.edit().clear().apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun login(username: String, pass: String) {
|
||||||
|
if (_isLoginInProgress.value) return
|
||||||
|
|
||||||
|
viewModelScope.launch {
|
||||||
|
_isLoginInProgress.value = true
|
||||||
|
_loginError.value = null
|
||||||
|
try {
|
||||||
|
val response = RetrofitClient.authApiService.login(LoginRequest(user_id = username, password = pass))
|
||||||
|
if (response.isSuccessful) {
|
||||||
|
val body = response.body()
|
||||||
|
if (body != null && body.success && body.user != null) {
|
||||||
|
val userRole = if (body.user.user_id.equals("Ecohub", ignoreCase = true)) "ADMIN" else "NORMAL"
|
||||||
|
|
||||||
|
val user = User(
|
||||||
|
username = body.user.user_id,
|
||||||
|
passwordHash = pass,
|
||||||
|
role = userRole
|
||||||
|
)
|
||||||
|
_currentUser.value = user
|
||||||
|
|
||||||
|
if (!body.token.isNullOrBlank()) {
|
||||||
|
_authToken.value = body.token
|
||||||
|
saveSession(body.token, body.user.user_id, userRole)
|
||||||
|
fetchUserProfile()
|
||||||
|
sendLog("login")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
_loginError.value = body?.message ?: "Invalid username or password"
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
_loginError.value = "Authentication failed: ${response.code()}"
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
_loginError.value = "Network error: ${e.localizedMessage}"
|
||||||
|
} finally {
|
||||||
|
_isLoginInProgress.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getMacAddress(): String {
|
||||||
|
try {
|
||||||
|
val all = Collections.list(NetworkInterface.getNetworkInterfaces())
|
||||||
|
for (nif in all) {
|
||||||
|
if (nif.name.lowercase() != "wlan0" && nif.name.lowercase() != "eth0") continue
|
||||||
|
val macBytes = nif.hardwareAddress
|
||||||
|
if (macBytes != null) {
|
||||||
|
return macBytes.joinToString(":") { String.format("%02X", it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {}
|
||||||
|
return "02:00:00:00:00:00"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sendLog(action: String) {
|
||||||
|
val token = _authToken.value ?: return
|
||||||
|
val tokenHeader = "Bearer $token"
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
val deviceName = "${Build.MANUFACTURER} ${Build.MODEL}"
|
||||||
|
val macAddress = getMacAddress()
|
||||||
|
RetrofitClient.authApiService.sendLog(tokenHeader, LogRequest(action = action, device = deviceName, mac_address = macAddress))
|
||||||
|
} catch (e: Exception) {
|
||||||
|
// Ignore log error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun fetchUserProfile() {
|
||||||
|
val token = _authToken.value ?: return
|
||||||
|
val tokenHeader = "Bearer $token"
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
val meResponse = RetrofitClient.authApiService.getMe(tokenHeader)
|
||||||
|
if (meResponse.isSuccessful) {
|
||||||
|
val body = meResponse.body()
|
||||||
|
if (body != null && body.success) {
|
||||||
|
_apiUserProfile.value = body.user
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
// Ignore error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun logout() {
|
||||||
|
sendLog("logout")
|
||||||
|
clearSession()
|
||||||
|
_currentUser.value = null
|
||||||
|
_apiUserProfile.value = null
|
||||||
|
_authToken.value = null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clearError() {
|
||||||
|
_loginError.value = null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun createNewUser(username: String, pass: String, role: String, onResult: (Boolean, String) -> Unit) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
val existing = repository.getUserByUsername(username)
|
||||||
|
if (existing != null) {
|
||||||
|
onResult(false, "Username already exists")
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
val newUser = User(username = username, passwordHash = pass, role = role)
|
||||||
|
repository.insertUser(newUser)
|
||||||
|
onResult(true, "User created successfully")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun changePassword(user: User, newPass: String) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
val updatedUser = user.copy(passwordHash = newPass)
|
||||||
|
repository.updateUser(updatedUser)
|
||||||
|
|
||||||
|
if (_currentUser.value?.id == user.id) {
|
||||||
|
_currentUser.value = updatedUser
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun deleteUser(user: User, onResult: (Boolean, String) -> Unit) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
if (user.role == "ADMIN" && user.username == "Ecohub") {
|
||||||
|
onResult(false, "Cannot delete the master Admin account.")
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
repository.deleteUser(user)
|
||||||
|
onResult(true, "User deleted.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,462 @@
|
|||||||
|
package com.example.netshareecohub.viewmodel
|
||||||
|
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
|
||||||
|
import android.net.VpnService
|
||||||
|
import android.os.Build
|
||||||
|
import android.provider.Settings
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.lifecycle.ViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import com.example.netshareecohub.MainActivity
|
||||||
|
import com.example.netshareecohub.data.logging.LogEntry
|
||||||
|
import com.example.netshareecohub.data.logging.Logger
|
||||||
|
import com.example.netshareecohub.dhcp.DhcpClientLease
|
||||||
|
import com.example.netshareecohub.dhcp.DhcpServer
|
||||||
|
import com.example.netshareecohub.dhcp.DhcpServerConfig
|
||||||
|
import com.example.netshareecohub.dhcp.DhcpServerStatus
|
||||||
|
import com.example.netshareecohub.dhcp.LeaseStatus
|
||||||
|
import com.example.netshareecohub.dhcp.ServerState
|
||||||
|
import com.example.netshareecohub.dhcp.ArpScanner
|
||||||
|
import com.example.netshareecohub.diagnostics.DiagnosticItem
|
||||||
|
import com.example.netshareecohub.diagnostics.NetworkDiagnostics
|
||||||
|
import com.example.netshareecohub.ethernet.EtToolSpeedManager
|
||||||
|
import com.example.netshareecohub.ethernet.EthernetAdapterInfo
|
||||||
|
import com.example.netshareecohub.ethernet.EthernetMonitor
|
||||||
|
import com.example.netshareecohub.ethernet.SpeedMode
|
||||||
|
import com.example.netshareecohub.routing.NetShareVpnService
|
||||||
|
import com.example.netshareecohub.routing.RootRoutingManager
|
||||||
|
import com.example.netshareecohub.routing.RoutingManager
|
||||||
|
import com.example.netshareecohub.routing.RoutingMode
|
||||||
|
import com.example.netshareecohub.routing.RoutingState
|
||||||
|
import com.example.netshareecohub.routing.RoutingStatus
|
||||||
|
import com.example.netshareecohub.routing.SystemTetheringManager
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.flow.combine
|
||||||
|
import kotlinx.coroutines.flow.stateIn
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
import com.example.netshareecohub.R
|
||||||
|
import com.example.netshareecohub.routing.TetheringCapabilityChecker
|
||||||
|
|
||||||
|
enum class AppScreen(val title: String) {
|
||||||
|
DASHBOARD("Dashboard"),
|
||||||
|
SETTINGS("Ethernet Settings"),
|
||||||
|
DEVICES("Connected Devices"),
|
||||||
|
DIAGNOSTICS("Network Diagnostics"),
|
||||||
|
LOGS("Network Logs"),
|
||||||
|
ADMIN("User Admin")
|
||||||
|
}
|
||||||
|
|
||||||
|
class MainViewModel(
|
||||||
|
val ethernetMonitor: EthernetMonitor,
|
||||||
|
val dhcpServer: DhcpServer,
|
||||||
|
val routingManager: RoutingManager = RoutingManager(),
|
||||||
|
val rootRoutingManager: RootRoutingManager = RootRoutingManager(),
|
||||||
|
val speedManager: EtToolSpeedManager = EtToolSpeedManager(),
|
||||||
|
val networkDiagnostics: NetworkDiagnostics = NetworkDiagnostics(
|
||||||
|
ethernetMonitor = ethernetMonitor,
|
||||||
|
dhcpServer = dhcpServer,
|
||||||
|
dhcpLeaseRepository = dhcpServer.leaseRepository,
|
||||||
|
routingManager = routingManager
|
||||||
|
)
|
||||||
|
) : ViewModel() {
|
||||||
|
|
||||||
|
private val tag = "MainViewModel"
|
||||||
|
|
||||||
|
private val _currentScreen = MutableStateFlow(AppScreen.DASHBOARD)
|
||||||
|
val currentScreen: StateFlow<AppScreen> = _currentScreen.asStateFlow()
|
||||||
|
|
||||||
|
private val _isRootAvailable = MutableStateFlow(false)
|
||||||
|
val isRootAvailable: StateFlow<Boolean> = _isRootAvailable.asStateFlow()
|
||||||
|
|
||||||
|
val activeAdapter: StateFlow<EthernetAdapterInfo?> = ethernetMonitor.activeAdapter
|
||||||
|
val adapters: StateFlow<List<EthernetAdapterInfo>> = ethernetMonitor.adapters
|
||||||
|
val dhcpStatus: StateFlow<DhcpServerStatus> = dhcpServer.status
|
||||||
|
val dhcpConfig: StateFlow<DhcpServerConfig> = dhcpServer.leaseRepository.config
|
||||||
|
val activeLeases: StateFlow<List<DhcpClientLease>> = dhcpServer.leaseRepository.leases
|
||||||
|
val routingStatus: StateFlow<RoutingStatus> = routingManager.status
|
||||||
|
val diagnosticItems: StateFlow<List<DiagnosticItem>> = networkDiagnostics.items
|
||||||
|
val diagnosticOutput: StateFlow<String> = networkDiagnostics.outputLog
|
||||||
|
val logs: StateFlow<List<LogEntry>> = Logger.logs
|
||||||
|
|
||||||
|
private val _speedConfigMessage = MutableStateFlow(speedManager.getStatusMessage())
|
||||||
|
val speedConfigMessage: StateFlow<String> = _speedConfigMessage.asStateFlow()
|
||||||
|
|
||||||
|
private val _isSpeedConfigSupported = MutableStateFlow(speedManager.isSpeedConfigSupported())
|
||||||
|
val isSpeedConfigSupported: StateFlow<Boolean> = _isSpeedConfigSupported.asStateFlow()
|
||||||
|
|
||||||
|
private val _isSharingActive = MutableStateFlow(false)
|
||||||
|
val isSharingActive: StateFlow<Boolean> = _isSharingActive.asStateFlow()
|
||||||
|
|
||||||
|
init {
|
||||||
|
ethernetMonitor.startMonitoring()
|
||||||
|
checkRootAccess()
|
||||||
|
startArpScanner()
|
||||||
|
monitorActiveAdapterForDhcpConfig()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun monitorActiveAdapterForDhcpConfig() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
activeAdapter.collect { adapter ->
|
||||||
|
if (adapter != null && adapter.primaryIpv4 != null) {
|
||||||
|
val ip = adapter.primaryIpv4
|
||||||
|
val parts = ip.split(".")
|
||||||
|
if (parts.size == 4) {
|
||||||
|
val baseIp = "${parts[0]}.${parts[1]}.${parts[2]}"
|
||||||
|
val newConfig = dhcpConfig.value.copy(
|
||||||
|
routerIp = ip,
|
||||||
|
poolStartIp = "$baseIp.50",
|
||||||
|
poolEndIp = "$baseIp.150"
|
||||||
|
)
|
||||||
|
updateDhcpConfig(newConfig)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// An IP address alone does not prove that Ethernet Tethering is active.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startArpScanner() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
while (true) {
|
||||||
|
delay(5000)
|
||||||
|
if (isSharingActive.value) {
|
||||||
|
val adapter = activeAdapter.value
|
||||||
|
if (adapter != null) {
|
||||||
|
val arpEntries = withContext(Dispatchers.IO) { ArpScanner.scan(adapter.name) }
|
||||||
|
for (entry in arpEntries) {
|
||||||
|
val existingLease = dhcpServer.leaseRepository.leases.value.find {
|
||||||
|
it.macAddress.equals(entry.macAddress, ignoreCase = true)
|
||||||
|
}
|
||||||
|
if (existingLease == null) {
|
||||||
|
// Inject discovered client into repository
|
||||||
|
dhcpServer.leaseRepository.injectExternalLease(
|
||||||
|
macAddress = entry.macAddress,
|
||||||
|
ipAddress = entry.ipAddress,
|
||||||
|
hostName = "Unknown (${entry.macAddress.substring(0, 8)})",
|
||||||
|
interfaceName = entry.interfaceName
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// Update existing lease last seen time
|
||||||
|
dhcpServer.leaseRepository.injectExternalLease(
|
||||||
|
macAddress = existingLease.macAddress,
|
||||||
|
ipAddress = existingLease.ipAddress,
|
||||||
|
hostName = existingLease.hostName,
|
||||||
|
interfaceName = existingLease.interfaceName
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun checkRootAccess() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
val (root, speedSupported, speedMessage) = withContext(Dispatchers.IO) {
|
||||||
|
Triple(
|
||||||
|
rootRoutingManager.isRootAvailable(),
|
||||||
|
speedManager.isSpeedConfigSupported(),
|
||||||
|
speedManager.getStatusMessage()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
_isRootAvailable.value = root
|
||||||
|
_isSpeedConfigSupported.value = speedSupported
|
||||||
|
_speedConfigMessage.value = speedMessage
|
||||||
|
Logger.info(tag, "Root access check complete. Root available: $root")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val _vpnPermissionIntent = MutableStateFlow<Intent?>(null)
|
||||||
|
val vpnPermissionIntent: StateFlow<Intent?> = _vpnPermissionIntent.asStateFlow()
|
||||||
|
|
||||||
|
fun onVpnPermissionIntentHandled() {
|
||||||
|
_vpnPermissionIntent.value = null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onVpnPermissionGranted(context: Context) {
|
||||||
|
// Native Ethernet Tethering does not require the app's separate VPN service.
|
||||||
|
startSharing(context)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun navigateTo(screen: AppScreen) {
|
||||||
|
_currentScreen.value = screen
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Refresh Ethernet discovery off the UI thread to avoid blocking Compose interactions. */
|
||||||
|
fun refreshEthernetInterfaces() {
|
||||||
|
viewModelScope.launch(Dispatchers.IO) {
|
||||||
|
ethernetMonitor.refresh()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun toggleSharing(context: Context) {
|
||||||
|
if (_isSharingActive.value) {
|
||||||
|
stopSharing(context)
|
||||||
|
} else {
|
||||||
|
startSharing(context)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
private val _tetheringStatusMessage = MutableStateFlow<String?>(null)
|
||||||
|
val tetheringStatusMessage: StateFlow<String?> = _tetheringStatusMessage.asStateFlow()
|
||||||
|
|
||||||
|
private val _isOperationInProgress = MutableStateFlow(false)
|
||||||
|
val isOperationInProgress: StateFlow<Boolean> = _isOperationInProgress.asStateFlow()
|
||||||
|
|
||||||
|
enum class ConnectionState {
|
||||||
|
READY,
|
||||||
|
CHECKING_DEVICE,
|
||||||
|
CHECKING_ETHERNET_INTERFACE,
|
||||||
|
CHECKING_CONTROL_ACCESS,
|
||||||
|
STARTING_TETHERING,
|
||||||
|
VERIFYING_TETHERING,
|
||||||
|
TETHERING_ACTIVE,
|
||||||
|
CONNECTING_TO_SERVICE,
|
||||||
|
VERIFYING_SERVICE,
|
||||||
|
CONNECTED,
|
||||||
|
FAILED,
|
||||||
|
STOPPING,
|
||||||
|
DISCONNECTED,
|
||||||
|
UNSUPPORTED_ON_DEVICE
|
||||||
|
}
|
||||||
|
|
||||||
|
private val _connectionState = MutableStateFlow(ConnectionState.READY)
|
||||||
|
val connectionState: StateFlow<ConnectionState> = _connectionState.asStateFlow()
|
||||||
|
|
||||||
|
private val _connectionMessage = MutableStateFlow("Ready to start the connection process.")
|
||||||
|
val connectionMessage: StateFlow<String> = _connectionMessage.asStateFlow()
|
||||||
|
|
||||||
|
private val sharingOperationLock = AtomicBoolean(false)
|
||||||
|
|
||||||
|
fun startSharing(context: Context) {
|
||||||
|
if (!sharingOperationLock.compareAndSet(false, true)) {
|
||||||
|
Logger.warn(tag, "A tethering operation is already in progress; duplicate tap ignored.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
viewModelScope.launch {
|
||||||
|
_isOperationInProgress.value = true
|
||||||
|
_isSharingActive.value = false
|
||||||
|
_connectionState.value = ConnectionState.CHECKING_DEVICE
|
||||||
|
_connectionMessage.value = context.getString(R.string.tethering_checking_device)
|
||||||
|
_tetheringStatusMessage.value = context.getString(R.string.tethering_checking_device)
|
||||||
|
|
||||||
|
try {
|
||||||
|
withContext(Dispatchers.IO) { ethernetMonitor.refresh() }
|
||||||
|
val adapterBeforeRequest = activeAdapter.value
|
||||||
|
if (adapterBeforeRequest == null) {
|
||||||
|
// Do not block the system tethering request just because an Ethernet interface
|
||||||
|
// is not yet visible to the app. On some builds, the interface is published or
|
||||||
|
// brought up as tethering starts. The system callback remains authoritative.
|
||||||
|
Logger.warn(
|
||||||
|
tag,
|
||||||
|
"No Ethernet interface is currently visible to the app; submitting a supported system request may still cause the platform to expose one."
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Logger.info(
|
||||||
|
tag,
|
||||||
|
"Ethernet interface detected before request: ${adapterBeforeRequest.name}, " +
|
||||||
|
"carrier=${adapterBeforeRequest.carrier}, operstate=${adapterBeforeRequest.operstate}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
_connectionState.value = ConnectionState.CHECKING_CONTROL_ACCESS
|
||||||
|
_connectionMessage.value = context.getString(R.string.tethering_checking_access)
|
||||||
|
_tetheringStatusMessage.value = _connectionMessage.value
|
||||||
|
|
||||||
|
val capability = TetheringCapabilityChecker.inspectDevice(context)
|
||||||
|
Logger.info(tag, "Tethering capability: ${capability.limitationReason}")
|
||||||
|
if (!capability.isDirectControlSupportedForNormalApp) {
|
||||||
|
val message = capability.limitationReason
|
||||||
|
val apiUnavailable = Build.VERSION.SDK_INT < Build.VERSION_CODES.R || Build.VERSION.SDK_INT >= 36
|
||||||
|
setConnectionFailure(message, unsupported = apiUnavailable)
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
|
||||||
|
_connectionState.value = ConnectionState.STARTING_TETHERING
|
||||||
|
_connectionMessage.value = context.getString(R.string.tethering_starting)
|
||||||
|
_tetheringStatusMessage.value = _connectionMessage.value
|
||||||
|
Logger.info(tag, "Submitting an Ethernet Tethering request to Android.")
|
||||||
|
|
||||||
|
val (success, resultMessage) = routingManager.systemTetheringManager
|
||||||
|
.startTetheringAwait(context, SystemTetheringManager.TETHERING_ETHERNET)
|
||||||
|
|
||||||
|
_tetheringStatusMessage.value = resultMessage
|
||||||
|
?: context.getString(R.string.tethering_result_unknown)
|
||||||
|
|
||||||
|
if (!success) {
|
||||||
|
setConnectionFailure(
|
||||||
|
resultMessage ?: context.getString(R.string.tethering_start_failed_generic),
|
||||||
|
unsupported = Build.VERSION.SDK_INT >= 36
|
||||||
|
)
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
|
||||||
|
// The system callback confirmed that its tethering request started. This does not
|
||||||
|
// prove a physical client link or a connection to any remote service.
|
||||||
|
_isSharingActive.value = true
|
||||||
|
_connectionState.value = ConnectionState.TETHERING_ACTIVE
|
||||||
|
withContext(Dispatchers.IO) { ethernetMonitor.refresh() }
|
||||||
|
val refreshedAdapter = activeAdapter.value
|
||||||
|
_connectionMessage.value = if (isEthernetLinkUp(refreshedAdapter)) {
|
||||||
|
context.getString(R.string.tethering_started_link_up)
|
||||||
|
} else {
|
||||||
|
context.getString(R.string.tethering_started_waiting_for_link)
|
||||||
|
}
|
||||||
|
_tetheringStatusMessage.value = _connectionMessage.value
|
||||||
|
Logger.info(tag, _connectionMessage.value.orEmpty())
|
||||||
|
} catch (e: Exception) {
|
||||||
|
val message = context.getString(
|
||||||
|
R.string.tethering_start_exception,
|
||||||
|
e.localizedMessage ?: e.javaClass.simpleName
|
||||||
|
)
|
||||||
|
Logger.error(tag, message, e)
|
||||||
|
setConnectionFailure(message)
|
||||||
|
} finally {
|
||||||
|
_isOperationInProgress.value = false
|
||||||
|
sharingOperationLock.set(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun setConnectionFailure(message: String, unsupported: Boolean = false) {
|
||||||
|
_isSharingActive.value = false
|
||||||
|
_connectionState.value = if (unsupported) ConnectionState.UNSUPPORTED_ON_DEVICE else ConnectionState.FAILED
|
||||||
|
_connectionMessage.value = message
|
||||||
|
_tetheringStatusMessage.value = message
|
||||||
|
Logger.warn(tag, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isEthernetLinkUp(adapter: EthernetAdapterInfo?): Boolean {
|
||||||
|
if (adapter == null) return false
|
||||||
|
if (adapter.carrier == 0 || adapter.operstate.equals("down", ignoreCase = true)) return false
|
||||||
|
return adapter.carrier == 1 ||
|
||||||
|
adapter.operstate.equals("up", ignoreCase = true) ||
|
||||||
|
adapter.operstate.equals("lower_up", ignoreCase = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stopSharing(context: Context) {
|
||||||
|
if (!sharingOperationLock.compareAndSet(false, true)) {
|
||||||
|
Logger.warn(tag, "A tethering operation is already in progress; duplicate tap ignored.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
viewModelScope.launch {
|
||||||
|
_isOperationInProgress.value = true
|
||||||
|
_connectionState.value = ConnectionState.STOPPING
|
||||||
|
_connectionMessage.value = context.getString(R.string.tethering_stopping)
|
||||||
|
_tetheringStatusMessage.value = _connectionMessage.value
|
||||||
|
|
||||||
|
try {
|
||||||
|
val (success, message) = routingManager.systemTetheringManager
|
||||||
|
.stopTetheringAwait(context, SystemTetheringManager.TETHERING_ETHERNET)
|
||||||
|
_tetheringStatusMessage.value = message
|
||||||
|
?: context.getString(R.string.tethering_result_unknown)
|
||||||
|
|
||||||
|
if (success) {
|
||||||
|
_isSharingActive.value = false
|
||||||
|
_connectionState.value = ConnectionState.DISCONNECTED
|
||||||
|
_connectionMessage.value = message
|
||||||
|
?: context.getString(R.string.tethering_stop_confirmed)
|
||||||
|
} else {
|
||||||
|
// Do not claim disconnected until the platform confirms it. Retain the last
|
||||||
|
// known state because a failed stop request does not prove that tethering ended.
|
||||||
|
_connectionState.value = ConnectionState.FAILED
|
||||||
|
_connectionMessage.value = message
|
||||||
|
?: context.getString(R.string.tethering_stop_unverified)
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
val message = context.getString(
|
||||||
|
R.string.tethering_stop_exception,
|
||||||
|
e.localizedMessage ?: e.javaClass.simpleName
|
||||||
|
)
|
||||||
|
_connectionState.value = ConnectionState.FAILED
|
||||||
|
_connectionMessage.value = message
|
||||||
|
_tetheringStatusMessage.value = message
|
||||||
|
Logger.error(tag, message, e)
|
||||||
|
} finally {
|
||||||
|
_isOperationInProgress.value = false
|
||||||
|
sharingOperationLock.set(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun updateDhcpConfig(newConfig: DhcpServerConfig) {
|
||||||
|
dhcpServer.updateConfig(newConfig)
|
||||||
|
Logger.info(tag, "Updated DHCP Server Configuration: $newConfig")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun applySpeedConfig(ifaceName: String, mode: SpeedMode) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
val (success, msg) = speedManager.configureSpeed(ifaceName, mode)
|
||||||
|
_speedConfigMessage.value = msg
|
||||||
|
if (success) {
|
||||||
|
ethernetMonitor.refresh()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun runFullDiagnostics() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
networkDiagnostics.runFullDiagnostics()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun pingGateway() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
networkDiagnostics.pingGateway()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun pingInternet() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
networkDiagnostics.pingInternet("8.8.8.8")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun testDns() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
networkDiagnostics.testDnsResolution("google.com")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun runTraceroute() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
networkDiagnostics.traceroute("8.8.8.8")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clearLogs() {
|
||||||
|
Logger.clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun copyLogsToClipboard(context: Context) {
|
||||||
|
val allLogsText = Logger.logs.value.joinToString("\n") { it.toString() }
|
||||||
|
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||||
|
val clip = ClipData.newPlainText("Network Logs", allLogsText)
|
||||||
|
clipboard.setPrimaryClip(clip)
|
||||||
|
Logger.info(tag, "Copied ${Logger.logs.value.size} log entries to clipboard.")
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCleared() {
|
||||||
|
super.onCleared()
|
||||||
|
ethernetMonitor.stopMonitoring()
|
||||||
|
}
|
||||||
|
}
|
||||||
12
app/src/main/keepRules/rules.keep
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
# Add project specific R8 rules here.
|
||||||
|
# AGP will combine all keep rule files in src/main/keepRules to pass to R8
|
||||||
|
#
|
||||||
|
# For more details, see
|
||||||
|
# https://d.android.com/r/tools/r8/keep-rules
|
||||||
|
|
||||||
|
# If your project uses WebView with JS, uncomment the following
|
||||||
|
# and specify the fully qualified class name to the JavaScript interface
|
||||||
|
# class:
|
||||||
|
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||||
|
# public *;
|
||||||
|
#}
|
||||||
10
app/src/main/res/drawable/ic_launcher_background.xml
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="108dp"
|
||||||
|
android:height="108dp"
|
||||||
|
android:viewportWidth="108"
|
||||||
|
android:viewportHeight="108">
|
||||||
|
<path
|
||||||
|
android:fillColor="#FFFFFF"
|
||||||
|
android:pathData="M0,0h108v108h-108z" />
|
||||||
|
</vector>
|
||||||
BIN
app/src/main/res/drawable/ic_logo.png
Normal file
|
After Width: | Height: | Size: 99 KiB |
BIN
app/src/main/res/drawable/placeholder.png
Normal file
|
After Width: | Height: | Size: 4.6 KiB |
6
app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<background android:drawable="@drawable/ic_launcher_background" />
|
||||||
|
<foreground android:drawable="@drawable/ic_logo" />
|
||||||
|
<monochrome android:drawable="@drawable/ic_logo" />
|
||||||
|
</adaptive-icon>
|
||||||
6
app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<background android:drawable="@drawable/ic_launcher_background" />
|
||||||
|
<foreground android:drawable="@drawable/ic_logo" />
|
||||||
|
<monochrome android:drawable="@drawable/ic_logo" />
|
||||||
|
</adaptive-icon>
|
||||||
BIN
app/src/main/res/mipmap-hdpi/ic_launcher.webp
Normal file
|
After Width: | Height: | Size: 1.4 KiB |
BIN
app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
Normal file
|
After Width: | Height: | Size: 2.8 KiB |
BIN
app/src/main/res/mipmap-mdpi/ic_launcher.webp
Normal file
|
After Width: | Height: | Size: 982 B |
BIN
app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
Normal file
|
After Width: | Height: | Size: 1.7 KiB |
BIN
app/src/main/res/mipmap-xhdpi/ic_launcher.webp
Normal file
|
After Width: | Height: | Size: 1.9 KiB |
BIN
app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
Normal file
|
After Width: | Height: | Size: 3.8 KiB |
BIN
app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
Normal file
|
After Width: | Height: | Size: 2.8 KiB |
BIN
app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
Normal file
|
After Width: | Height: | Size: 5.8 KiB |
BIN
app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
Normal file
|
After Width: | Height: | Size: 3.8 KiB |
BIN
app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
Normal file
|
After Width: | Height: | Size: 7.6 KiB |
77
app/src/main/res/values-b+zh+Hans+CN/strings.xml
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
<?xml version='1.0' encoding='utf-8'?>
|
||||||
|
<resources>
|
||||||
|
<string name="app_name">iPhone Unlocker</string>
|
||||||
|
<string name="accessibility_service_description">显示并管理受支持的以太网网络状态。</string>
|
||||||
|
<string name="start_sharing">开始共享</string>
|
||||||
|
<string name="stop_sharing">停止共享</string>
|
||||||
|
<string name="processing">处理中…</string>
|
||||||
|
<string name="control_status">控制状态</string>
|
||||||
|
<string name="connecting">连接中...</string>
|
||||||
|
<string name="status_idle">空闲</string>
|
||||||
|
<string name="status_active">共享已启动</string>
|
||||||
|
<string name="status_stopped">共享已停止</string>
|
||||||
|
<string name="device_label">设备: %1$s</string>
|
||||||
|
<string name="user_profile">用户资料</string>
|
||||||
|
<string name="name_label">姓名</string>
|
||||||
|
<string name="user_id_label">用户 ID</string>
|
||||||
|
<string name="password_label">密码</string>
|
||||||
|
<string name="login">登录</string>
|
||||||
|
<string name="login_prompt">请登录后继续</string>
|
||||||
|
<string name="settings">设置</string>
|
||||||
|
<string name="language">语言</string>
|
||||||
|
<string name="english">English</string>
|
||||||
|
<string name="chinese">简体中文</string>
|
||||||
|
<string name="logs">日志</string>
|
||||||
|
<string name="interfaces">网络接口</string>
|
||||||
|
<string name="dhcp_server">DHCP 服务器</string>
|
||||||
|
<string name="ethernet_link_status">以太网接口</string>
|
||||||
|
<string name="connected">已连接</string>
|
||||||
|
<string name="disconnected">未连接</string>
|
||||||
|
<string name="ethernet_disconnected_hint">未检测到活动的以太网链路。请检查兼容的以太网适配器和网线是否已连接。</string>
|
||||||
|
<string name="connected_client_devices">已连接的客户端设备(%1$d)</string>
|
||||||
|
<string name="client_mac_status">MAC:%1$s | 状态:%2$s</string>
|
||||||
|
<string name="tethering_settings_not_opened">未打开系统设置。应用无法自行授予系统网络共享权限。</string>
|
||||||
|
<string name="tethering_permission_missing">此应用尚未启用一次性 WRITE_SETTINGS 特殊访问权限。本应用不会自动打开系统设置。请在自己的开发设备上手动启用“修改系统设置”,或在已授权 USB 调试的电脑上运行 tools\\grant_write_settings.bat,然后重新打开应用。即使已授权,Android 仍可能因设备不支持以太网共享而拒绝请求。</string>
|
||||||
|
<string name="tethering_only_ethernet_supported">此控制器仅支持以太网共享请求。</string>
|
||||||
|
<string name="tethering_api_unavailable">此 Android 版本没有可供普通应用使用的以太网共享控制 API。</string>
|
||||||
|
<string name="tethering_android16_limit">Android 16 的公共 API 未将以太网列为普通应用支持的共享请求类型。本应用不会使用未公开的变通方案;可能需要制造商授权的系统集成。</string>
|
||||||
|
<string name="tethering_already_started">此应用已有一个已确认的网络共享会话。</string>
|
||||||
|
<string name="tethering_request_in_progress">网络共享请求正在进行中。</string>
|
||||||
|
<string name="tethering_service_unavailable">此设备上的 Android 网络共享服务不可用。</string>
|
||||||
|
<string name="tethering_start_timeout">等待 Android 确认网络共享请求超时。</string>
|
||||||
|
<string name="tethering_start_confirmed">Android 已确认网络共享请求启动,但尚未确认客户端链路。</string>
|
||||||
|
<string name="tethering_start_failed_code">网络共享请求失败(错误 %1$d):%2$s</string>
|
||||||
|
<string name="tethering_permission_denied">Android 拒绝了控制以太网共享的权限。</string>
|
||||||
|
<string name="tethering_type_not_supported">此设备不支持请求的以太网共享类型。</string>
|
||||||
|
<string name="tethering_start_exception">无法启动以太网共享:%1$s</string>
|
||||||
|
<string name="tethering_stop_confirmed">Android 已报告以太网共享不再处于活动状态。</string>
|
||||||
|
<string name="tethering_stop_unverified">已提交停止请求,但 Android 未确认以太网共享已停止。</string>
|
||||||
|
<string name="tethering_no_owned_session">此应用没有可停止的已确认网络共享会话。</string>
|
||||||
|
<string name="tethering_stop_exception">无法停止以太网共享:%1$s</string>
|
||||||
|
<string name="tethering_error_unknown_interface">网络共享服务无法识别合适的网络接口。</string>
|
||||||
|
<string name="tethering_error_service_unavailable">Android 网络共享服务不可用。</string>
|
||||||
|
<string name="tethering_error_unsupported">此设备的系统实现不支持以太网共享。</string>
|
||||||
|
<string name="tethering_error_interface_unavailable">以太网接口不可用或尚未连接。</string>
|
||||||
|
<string name="tethering_error_provisioning">系统网络共享配置检查失败。</string>
|
||||||
|
<string name="tethering_error_dhcp">系统无法启动 DHCP 服务。</string>
|
||||||
|
<string name="tethering_error_entitlement">系统网络共享授权检查失败。</string>
|
||||||
|
<string name="tethering_error_permission">Android 拒绝了所需的网络共享权限。</string>
|
||||||
|
<string name="tethering_error_generic">Android 返回了网络共享错误。</string>
|
||||||
|
<string name="tethering_checking_device">正在检查设备和以太网接口…</string>
|
||||||
|
<string name="tethering_no_ethernet_interface">未检测到可用的以太网接口。请连接受支持的以太网适配器和网线后重试。</string>
|
||||||
|
<string name="tethering_checking_access">正在检查 Android 是否允许直接控制以太网共享…</string>
|
||||||
|
<string name="tethering_starting">正在请求 Android 启动以太网共享…</string>
|
||||||
|
<string name="tethering_result_unknown">Android 未提供明确的网络共享状态。</string>
|
||||||
|
<string name="tethering_start_failed_generic">无法启动以太网共享。</string>
|
||||||
|
<string name="tethering_started_link_up">网络共享请求已启动,并检测到以太网链路。</string>
|
||||||
|
<string name="tethering_started_waiting_for_link">Android 已接受网络共享请求,但尚未检测到活动的以太网链路。</string>
|
||||||
|
<string name="tethering_stopping">正在请求停止以太网共享…</string>
|
||||||
|
<string name="tethering_support">网络共享支持</string>
|
||||||
|
<string name="self_assigned_ip_title">以太网连接需要检查</string>
|
||||||
|
<string name="self_assigned_ip_message">客户端使用了自动分配的 IP 地址(169.254.x.x)。请检查适配器、网线、IP 配置以及操作系统是否已启用网络共享。</string>
|
||||||
|
<string name="unknown">未知</string>
|
||||||
|
<string name="tethering_unavailable">不可用</string>
|
||||||
|
<string name="connection_failed">失败</string>
|
||||||
|
<string name="tethering_active">网络共享已启动</string>
|
||||||
|
<string name="status_ready">就绪</string>
|
||||||
|
</resources>
|
||||||
10
app/src/main/res/values/colors.xml
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<color name="purple_200">#FFBB86FC</color>
|
||||||
|
<color name="purple_500">#FF6200EE</color>
|
||||||
|
<color name="purple_700">#FF3700B3</color>
|
||||||
|
<color name="teal_200">#FF03DAC5</color>
|
||||||
|
<color name="teal_700">#FF018786</color>
|
||||||
|
<color name="black">#FF000000</color>
|
||||||
|
<color name="white">#FFFFFFFF</color>
|
||||||
|
</resources>
|
||||||
77
app/src/main/res/values/strings.xml
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
<?xml version='1.0' encoding='utf-8'?>
|
||||||
|
<resources>
|
||||||
|
<string name="app_name">iPhone Unlocker</string>
|
||||||
|
<string name="accessibility_service_description">Shows and manages supported Ethernet networking status.</string>
|
||||||
|
<string name="start_sharing">Start Sharing</string>
|
||||||
|
<string name="stop_sharing">Stop Sharing</string>
|
||||||
|
<string name="processing">Processing…</string>
|
||||||
|
<string name="control_status">Control Status</string>
|
||||||
|
<string name="connecting">Connecting...</string>
|
||||||
|
<string name="status_idle">Idle</string>
|
||||||
|
<string name="status_active">Sharing Active</string>
|
||||||
|
<string name="status_stopped">Sharing Stopped</string>
|
||||||
|
<string name="device_label">Device: %1$s</string>
|
||||||
|
<string name="user_profile">User Profile</string>
|
||||||
|
<string name="name_label">Name</string>
|
||||||
|
<string name="user_id_label">User ID</string>
|
||||||
|
<string name="password_label">Password</string>
|
||||||
|
<string name="login">Login</string>
|
||||||
|
<string name="login_prompt">Please log in to continue</string>
|
||||||
|
<string name="settings">Settings</string>
|
||||||
|
<string name="language">Language</string>
|
||||||
|
<string name="english">English</string>
|
||||||
|
<string name="chinese">简体中文</string>
|
||||||
|
<string name="logs">Logs</string>
|
||||||
|
<string name="interfaces">Interfaces</string>
|
||||||
|
<string name="dhcp_server">DHCP Server</string>
|
||||||
|
<string name="ethernet_link_status">Ethernet Interface</string>
|
||||||
|
<string name="connected">Connected</string>
|
||||||
|
<string name="disconnected">Disconnected</string>
|
||||||
|
<string name="ethernet_disconnected_hint">No active Ethernet link is detected. Check that a compatible Ethernet adapter and cable are connected.</string>
|
||||||
|
<string name="connected_client_devices">Connected Client Devices (%1$d)</string>
|
||||||
|
<string name="client_mac_status">MAC: %1$s | Status: %2$s</string>
|
||||||
|
<string name="tethering_settings_not_opened">Settings was not opened. This app cannot grant itself system tethering access.</string>
|
||||||
|
<string name="tethering_permission_missing">One-time WRITE_SETTINGS access is not enabled for this app. This app will not open Settings. For your own development device, enable Modify system settings manually or run tools\\grant_write_settings.bat from a PC with USB debugging authorized, then reopen the app. Android may still reject Ethernet tethering if the device does not support it.</string>
|
||||||
|
<string name="tethering_only_ethernet_supported">This controller only supports Ethernet Tethering requests.</string>
|
||||||
|
<string name="tethering_api_unavailable">A supported Ethernet Tethering control API is unavailable on this Android version.</string>
|
||||||
|
<string name="tethering_android16_limit">The public Android 16 API does not document Ethernet as a supported request type for ordinary apps. This app will not use an undocumented workaround; manufacturer-authorized system integration may be required.</string>
|
||||||
|
<string name="tethering_already_started">This app already has a confirmed tethering session.</string>
|
||||||
|
<string name="tethering_request_in_progress">A tethering request is already in progress.</string>
|
||||||
|
<string name="tethering_service_unavailable">Android tethering service is unavailable on this device.</string>
|
||||||
|
<string name="tethering_start_timeout">Android did not confirm the tethering request before the timeout.</string>
|
||||||
|
<string name="tethering_start_confirmed">Android confirmed that the tethering request started. A client link is not yet confirmed.</string>
|
||||||
|
<string name="tethering_start_failed_code">Tethering request failed (error %1$d): %2$s</string>
|
||||||
|
<string name="tethering_permission_denied">Android denied permission to control Ethernet Tethering.</string>
|
||||||
|
<string name="tethering_type_not_supported">This device does not support the requested Ethernet Tethering type.</string>
|
||||||
|
<string name="tethering_start_exception">Unable to start Ethernet Tethering: %1$s</string>
|
||||||
|
<string name="tethering_stop_confirmed">Android reported that Ethernet Tethering is no longer active.</string>
|
||||||
|
<string name="tethering_stop_unverified">The stop request was submitted, but Android did not confirm that Ethernet Tethering stopped.</string>
|
||||||
|
<string name="tethering_no_owned_session">This app has no confirmed tethering session to stop.</string>
|
||||||
|
<string name="tethering_stop_exception">Unable to stop Ethernet Tethering: %1$s</string>
|
||||||
|
<string name="tethering_error_unknown_interface">The tethering service could not identify a suitable interface.</string>
|
||||||
|
<string name="tethering_error_service_unavailable">Android tethering service is unavailable.</string>
|
||||||
|
<string name="tethering_error_unsupported">Ethernet Tethering is not supported by this device implementation.</string>
|
||||||
|
<string name="tethering_error_interface_unavailable">The Ethernet interface is unavailable or not connected.</string>
|
||||||
|
<string name="tethering_error_provisioning">The system tethering provisioning check failed.</string>
|
||||||
|
<string name="tethering_error_dhcp">The system could not start its DHCP service.</string>
|
||||||
|
<string name="tethering_error_entitlement">The system tethering entitlement check failed.</string>
|
||||||
|
<string name="tethering_error_permission">Android denied the required tethering permission.</string>
|
||||||
|
<string name="tethering_error_generic">Android reported a tethering error.</string>
|
||||||
|
<string name="tethering_checking_device">Checking device and Ethernet interface…</string>
|
||||||
|
<string name="tethering_no_ethernet_interface">No usable Ethernet interface was detected. Connect a supported Ethernet adapter and cable, then retry.</string>
|
||||||
|
<string name="tethering_checking_access">Checking whether Android permits direct Ethernet Tethering control…</string>
|
||||||
|
<string name="tethering_starting">Requesting Ethernet Tethering from Android…</string>
|
||||||
|
<string name="tethering_result_unknown">Android did not provide a conclusive tethering status.</string>
|
||||||
|
<string name="tethering_start_failed_generic">Ethernet Tethering could not be started.</string>
|
||||||
|
<string name="tethering_started_link_up">Tethering request started and an Ethernet link is detected.</string>
|
||||||
|
<string name="tethering_started_waiting_for_link">Android accepted the tethering request, but no active Ethernet link is detected yet.</string>
|
||||||
|
<string name="tethering_stopping">Requesting Ethernet Tethering to stop…</string>
|
||||||
|
<string name="tethering_support">Tethering Support</string>
|
||||||
|
<string name="self_assigned_ip_title">Ethernet connection needs attention</string>
|
||||||
|
<string name="self_assigned_ip_message">A client has a self-assigned IP address (169.254.x.x). Check the adapter, cable, IP configuration, and whether the operating system has enabled tethering.</string>
|
||||||
|
<string name="unknown">Unknown</string>
|
||||||
|
<string name="tethering_unavailable">Unavailable</string>
|
||||||
|
<string name="connection_failed">Failed</string>
|
||||||
|
<string name="tethering_active">Tethering Active</string>
|
||||||
|
<string name="status_ready">Ready</string>
|
||||||
|
</resources>
|
||||||
4
app/src/main/res/values/themes.xml
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
<resources>
|
||||||
|
|
||||||
|
<style name="Theme.NetShareEcohub" parent="Theme.MaterialComponents.Light" />
|
||||||
|
</resources>
|
||||||
13
app/src/main/res/xml/backup_rules.xml
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?><!--
|
||||||
|
Sample backup rules file; uncomment and customize as necessary.
|
||||||
|
See https://developer.android.com/guide/topics/data/autobackup
|
||||||
|
for details.
|
||||||
|
Note: This file is ignored for devices older than API 31
|
||||||
|
See https://developer.android.com/about/versions/12/backup-restore
|
||||||
|
-->
|
||||||
|
<full-backup-content>
|
||||||
|
<!--
|
||||||
|
<include domain="sharedpref" path="."/>
|
||||||
|
<exclude domain="sharedpref" path="device.xml"/>
|
||||||
|
-->
|
||||||
|
</full-backup-content>
|
||||||
19
app/src/main/res/xml/data_extraction_rules.xml
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?><!--
|
||||||
|
Sample data extraction rules file; uncomment and customize as necessary.
|
||||||
|
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
|
||||||
|
for details.
|
||||||
|
-->
|
||||||
|
<data-extraction-rules>
|
||||||
|
<cloud-backup>
|
||||||
|
<!-- TODO: Use <include> and <exclude> to control what is backed up.
|
||||||
|
<include .../>
|
||||||
|
<exclude .../>
|
||||||
|
-->
|
||||||
|
</cloud-backup>
|
||||||
|
<!--
|
||||||
|
<device-transfer>
|
||||||
|
<include .../>
|
||||||
|
<exclude .../>
|
||||||
|
</device-transfer>
|
||||||
|
-->
|
||||||
|
</data-extraction-rules>
|
||||||
6
app/src/main/res/xml/network_security_config.xml
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<network-security-config>
|
||||||
|
<domain-config cleartextTrafficPermitted="true">
|
||||||
|
<domain includeSubdomains="true">unlock.ecohub.cc</domain>
|
||||||
|
</domain-config>
|
||||||
|
</network-security-config>
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package com.example.netshareecohub
|
||||||
|
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
import org.junit.Assert.*
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example local unit test, which will execute on the development machine (host).
|
||||||
|
*
|
||||||
|
* See [testing documentation](http://d.android.com/tools/testing).
|
||||||
|
*/
|
||||||
|
class ExampleUnitTest {
|
||||||
|
@Test
|
||||||
|
fun addition_isCorrect() {
|
||||||
|
assertEquals(4, 2 + 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
package com.example.netshareecohub.dhcp
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class DhcpLeaseRepositoryTest {
|
||||||
|
|
||||||
|
private lateinit var repository: DhcpLeaseRepository
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
val defaultConfig = DhcpServerConfig(
|
||||||
|
serverIp = "192.168.50.1",
|
||||||
|
subnetMask = "255.255.255.0",
|
||||||
|
poolStartIp = "192.168.50.100",
|
||||||
|
poolEndIp = "192.168.50.105", // Small pool of 6 IPs for testing
|
||||||
|
routerIp = "192.168.50.1",
|
||||||
|
dnsServers = listOf("192.168.50.1"),
|
||||||
|
defaultLeaseTimeSeconds = 60L
|
||||||
|
)
|
||||||
|
repository = DhcpLeaseRepository(defaultConfig)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testAllocateOfferAndConfirmLease() {
|
||||||
|
val mac = "00:11:22:33:44:55"
|
||||||
|
val hostName = "TestLaptop"
|
||||||
|
|
||||||
|
// 1. Allocate offer for DISCOVER
|
||||||
|
val offeredIp = repository.allocateOrFindOffer(
|
||||||
|
macAddress = mac,
|
||||||
|
requestedIp = null,
|
||||||
|
hostName = hostName
|
||||||
|
)
|
||||||
|
|
||||||
|
assertNotNull(offeredIp)
|
||||||
|
assertEquals("192.168.50.100", offeredIp)
|
||||||
|
|
||||||
|
// Verify lease status is OFFERED
|
||||||
|
val leasesAfterOffer = repository.leases.value
|
||||||
|
assertEquals(1, leasesAfterOffer.size)
|
||||||
|
assertEquals(LeaseStatus.OFFERED, leasesAfterOffer[0].status)
|
||||||
|
assertEquals(mac.uppercase(), leasesAfterOffer[0].macAddress)
|
||||||
|
|
||||||
|
// 2. Confirm lease for REQUEST
|
||||||
|
val confirmedLease = repository.confirmLease(
|
||||||
|
macAddress = mac,
|
||||||
|
requestedIp = offeredIp!!,
|
||||||
|
hostName = hostName
|
||||||
|
)
|
||||||
|
|
||||||
|
assertNotNull(confirmedLease)
|
||||||
|
assertEquals(LeaseStatus.ONLINE, confirmedLease!!.status)
|
||||||
|
assertEquals("192.168.50.100", confirmedLease.ipAddress)
|
||||||
|
|
||||||
|
val leasesAfterConfirm = repository.leases.value
|
||||||
|
assertEquals(1, leasesAfterConfirm.size)
|
||||||
|
assertEquals(LeaseStatus.ONLINE, leasesAfterConfirm[0].status)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testSequentialIpAllocationInPool() {
|
||||||
|
val mac1 = "00:11:22:33:44:01"
|
||||||
|
val mac2 = "00:11:22:33:44:02"
|
||||||
|
|
||||||
|
val ip1 = repository.allocateOrFindOffer(mac1, null, "Device1")
|
||||||
|
val ip2 = repository.allocateOrFindOffer(mac2, null, "Device2")
|
||||||
|
|
||||||
|
assertEquals("192.168.50.100", ip1)
|
||||||
|
assertEquals("192.168.50.101", ip2)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testReleaseAndReallocation() {
|
||||||
|
val mac = "00:11:22:33:44:01"
|
||||||
|
val ip = repository.allocateOrFindOffer(mac, null, "Device1")
|
||||||
|
repository.confirmLease(mac, ip!!, "Device1")
|
||||||
|
|
||||||
|
// Release lease
|
||||||
|
val released = repository.releaseLease(mac)
|
||||||
|
assertTrue(released)
|
||||||
|
|
||||||
|
val leases = repository.leases.value
|
||||||
|
assertEquals(LeaseStatus.RELEASED, leases[0].status)
|
||||||
|
|
||||||
|
// Another client should be able to get the released IP if pool demands it
|
||||||
|
val mac2 = "00:11:22:33:44:02"
|
||||||
|
val ip2 = repository.allocateOrFindOffer(mac2, ip, "Device2")
|
||||||
|
assertEquals(ip, ip2)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testPoolExhaustion() {
|
||||||
|
// Pool is 100 to 105 (6 IPs)
|
||||||
|
for (i in 0..5) {
|
||||||
|
val mac = "00:11:22:33:44:0$i"
|
||||||
|
val ip = repository.allocateOrFindOffer(mac, null, "Device$i")
|
||||||
|
assertNotNull(ip)
|
||||||
|
repository.confirmLease(mac, ip!!, "Device$i")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 7th device should fail to get an IP
|
||||||
|
val macExtra = "00:11:22:33:44:99"
|
||||||
|
val ipExtra = repository.allocateOrFindOffer(macExtra, null, "DeviceExtra")
|
||||||
|
assertNull(ipExtra)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testDynamicPoolConfigUpdateAtRuntime() {
|
||||||
|
val mac = "00:11:22:33:44:01"
|
||||||
|
repository.allocateOrFindOffer(mac, null, "Device1")
|
||||||
|
repository.confirmLease(mac, "192.168.50.100", "Device1")
|
||||||
|
|
||||||
|
// Update pool config to start at 192.168.50.150
|
||||||
|
val newConfig = DhcpServerConfig(
|
||||||
|
serverIp = "192.168.50.1",
|
||||||
|
subnetMask = "255.255.255.0",
|
||||||
|
poolStartIp = "192.168.50.150",
|
||||||
|
poolEndIp = "192.168.50.200",
|
||||||
|
routerIp = "192.168.50.1",
|
||||||
|
dnsServers = listOf("192.168.50.1", "8.8.8.8"),
|
||||||
|
defaultLeaseTimeSeconds = 3600L
|
||||||
|
)
|
||||||
|
|
||||||
|
repository.updateConfig(newConfig)
|
||||||
|
|
||||||
|
assertEquals("192.168.50.150", repository.getConfig().poolStartIp)
|
||||||
|
|
||||||
|
// Previous lease at 100 is now outside pool and should be marked EXPIRED
|
||||||
|
val leases = repository.leases.value
|
||||||
|
assertEquals(LeaseStatus.EXPIRED, leases[0].status)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testSweepExpiredLeases() {
|
||||||
|
val mac = "00:11:22:33:44:01"
|
||||||
|
repository.allocateOrFindOffer(mac, null, "Device1")
|
||||||
|
repository.confirmLease(mac, "192.168.50.100", "Device1")
|
||||||
|
|
||||||
|
// Sweep with future time (2 minutes later)
|
||||||
|
val futureTime = System.currentTimeMillis() + 120_000L
|
||||||
|
repository.sweepExpiredLeases(currentTimeMs = futureTime)
|
||||||
|
|
||||||
|
val leases = repository.leases.value
|
||||||
|
assertEquals(LeaseStatus.EXPIRED, leases[0].status)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
package com.example.netshareecohub.dhcp
|
||||||
|
|
||||||
|
import org.junit.Assert.assertArrayEquals
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class DhcpPacketTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testDhcpPacketEncodingAndDecodingRoundTrip() {
|
||||||
|
val originalMac = "00:11:22:33:44:55"
|
||||||
|
val macBytes = DhcpPacket.macToBytes(originalMac)
|
||||||
|
|
||||||
|
val options = listOf(
|
||||||
|
DhcpOption(DhcpOptionCode.MESSAGE_TYPE, 1, byteArrayOf(DhcpMessageType.DISCOVER.code)),
|
||||||
|
DhcpOption(DhcpOptionCode.REQUESTED_IP, 4, DhcpPacket.ipToBytes("192.168.50.150")),
|
||||||
|
DhcpOption(DhcpOptionCode.HOST_NAME, "TestDevice".length, "TestDevice".toByteArray(Charsets.UTF_8))
|
||||||
|
)
|
||||||
|
|
||||||
|
val packet = DhcpPacket(
|
||||||
|
op = 1,
|
||||||
|
htype = 1,
|
||||||
|
hlen = 6,
|
||||||
|
xid = 0x12345678,
|
||||||
|
flags = 0x8000.toShort(), // Broadcast
|
||||||
|
chaddr = macBytes,
|
||||||
|
options = options
|
||||||
|
)
|
||||||
|
|
||||||
|
val encoded = packet.encode()
|
||||||
|
assertNotNull(encoded)
|
||||||
|
|
||||||
|
val decoded = DhcpPacket.decode(encoded, encoded.size)
|
||||||
|
assertNotNull(decoded)
|
||||||
|
|
||||||
|
assertEquals(1.toByte(), decoded!!.op)
|
||||||
|
assertEquals(1.toByte(), decoded.htype)
|
||||||
|
assertEquals(6.toByte(), decoded.hlen)
|
||||||
|
assertEquals(0x12345678, decoded.xid)
|
||||||
|
assertEquals(0x8000.toShort(), decoded.flags)
|
||||||
|
|
||||||
|
assertEquals(DhcpMessageType.DISCOVER, decoded.getMessageType())
|
||||||
|
assertEquals("192.168.50.150", decoded.getRequestedIp())
|
||||||
|
assertEquals("TestDevice", decoded.getHostName())
|
||||||
|
assertEquals("00:11:22:33:44:55", decoded.getClientMac())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testOfferPacketOptionsAndEncoding() {
|
||||||
|
val serverIp = "192.168.50.1"
|
||||||
|
val offeredIp = "192.168.50.100"
|
||||||
|
val subnetMask = "255.255.255.0"
|
||||||
|
val routerIp = "192.168.50.1"
|
||||||
|
val dns1 = "192.168.50.1"
|
||||||
|
val dns2 = "8.8.8.8"
|
||||||
|
val leaseTimeSeconds = 86400
|
||||||
|
|
||||||
|
val dnsBytes = ByteArray(8)
|
||||||
|
System.arraycopy(DhcpPacket.ipToBytes(dns1), 0, dnsBytes, 0, 4)
|
||||||
|
System.arraycopy(DhcpPacket.ipToBytes(dns2), 0, dnsBytes, 4, 4)
|
||||||
|
|
||||||
|
val options = listOf(
|
||||||
|
DhcpOption(DhcpOptionCode.MESSAGE_TYPE, 1, byteArrayOf(DhcpMessageType.OFFER.code)),
|
||||||
|
DhcpOption(DhcpOptionCode.SERVER_ID, 4, DhcpPacket.ipToBytes(serverIp)),
|
||||||
|
DhcpOption(DhcpOptionCode.LEASE_TIME, 4, DhcpPacket.intToBytes(leaseTimeSeconds)),
|
||||||
|
DhcpOption(DhcpOptionCode.SUBNET_MASK, 4, DhcpPacket.ipToBytes(subnetMask)),
|
||||||
|
DhcpOption(DhcpOptionCode.ROUTER, 4, DhcpPacket.ipToBytes(routerIp)),
|
||||||
|
DhcpOption(DhcpOptionCode.DNS_SERVER, 8, dnsBytes)
|
||||||
|
)
|
||||||
|
|
||||||
|
val packet = DhcpPacket(
|
||||||
|
op = 2,
|
||||||
|
xid = 0x87654321.toInt(),
|
||||||
|
yiaddr = offeredIp,
|
||||||
|
siaddr = serverIp,
|
||||||
|
chaddr = DhcpPacket.macToBytes("AA:BB:CC:DD:EE:FF"),
|
||||||
|
options = options
|
||||||
|
)
|
||||||
|
|
||||||
|
val encoded = packet.encode()
|
||||||
|
val decoded = DhcpPacket.decode(encoded, encoded.size)
|
||||||
|
|
||||||
|
assertNotNull(decoded)
|
||||||
|
assertEquals(DhcpMessageType.OFFER, decoded!!.getMessageType())
|
||||||
|
assertEquals(offeredIp, decoded.yiaddr)
|
||||||
|
assertEquals(serverIp, decoded.getServerId())
|
||||||
|
assertEquals("AA:BB:CC:DD:EE:FF", decoded.getClientMac())
|
||||||
|
|
||||||
|
val subnetOpt = decoded.getOption(DhcpOptionCode.SUBNET_MASK)
|
||||||
|
assertNotNull(subnetOpt)
|
||||||
|
assertEquals(subnetMask, DhcpPacket.bytesToIp(subnetOpt!!.value, 0))
|
||||||
|
|
||||||
|
val routerOpt = decoded.getOption(DhcpOptionCode.ROUTER)
|
||||||
|
assertNotNull(routerOpt)
|
||||||
|
assertEquals(routerIp, DhcpPacket.bytesToIp(routerOpt!!.value, 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testMacAddressAndIpConversionHelpers() {
|
||||||
|
val macStr = "12:34:56:78:9A:BC"
|
||||||
|
val bytes = DhcpPacket.macToBytes(macStr)
|
||||||
|
val formatted = DhcpPacket.macToString(bytes, bytes.size)
|
||||||
|
assertEquals(macStr, formatted)
|
||||||
|
|
||||||
|
val ipStr = "192.168.1.50"
|
||||||
|
val ipBytes = DhcpPacket.ipToBytes(ipStr)
|
||||||
|
val recoveredIp = DhcpPacket.bytesToIp(ipBytes, 0)
|
||||||
|
assertEquals(ipStr, recoveredIp)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package com.example.netshareecohub.diagnostics
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.ContextWrapper
|
||||||
|
import com.example.netshareecohub.dhcp.DhcpLeaseRepository
|
||||||
|
import com.example.netshareecohub.dhcp.DhcpServer
|
||||||
|
import com.example.netshareecohub.ethernet.EthernetMonitor
|
||||||
|
import com.example.netshareecohub.routing.RoutingManager
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class FakeContext : ContextWrapper(null)
|
||||||
|
|
||||||
|
class NetworkDiagnosticsTest {
|
||||||
|
|
||||||
|
private lateinit var mockEthernetMonitor: EthernetMonitor
|
||||||
|
private lateinit var mockDhcpServer: DhcpServer
|
||||||
|
private lateinit var mockLeaseRepository: DhcpLeaseRepository
|
||||||
|
private lateinit var mockRoutingManager: RoutingManager
|
||||||
|
private lateinit var diagnostics: NetworkDiagnostics
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
val context: Context = FakeContext()
|
||||||
|
mockEthernetMonitor = EthernetMonitor(context)
|
||||||
|
mockDhcpServer = DhcpServer()
|
||||||
|
mockLeaseRepository = mockDhcpServer.leaseRepository
|
||||||
|
mockRoutingManager = RoutingManager()
|
||||||
|
|
||||||
|
diagnostics = NetworkDiagnostics(
|
||||||
|
ethernetMonitor = mockEthernetMonitor,
|
||||||
|
dhcpServer = mockDhcpServer,
|
||||||
|
dhcpLeaseRepository = mockLeaseRepository,
|
||||||
|
routingManager = mockRoutingManager
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testInitialDiagnosticItemsCount() {
|
||||||
|
val items = diagnostics.items.value
|
||||||
|
assertEquals(8, items.size)
|
||||||
|
assertEquals("Ethernet Interface Test", items[0].name)
|
||||||
|
assertEquals("NAT Forwarding Test", items[7].name)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testRunFullDiagnosticsUpdatesItems() = runTest {
|
||||||
|
val result = diagnostics.runFullDiagnostics()
|
||||||
|
assertEquals(8, result.size)
|
||||||
|
assertTrue(diagnostics.outputLog.value.contains("COMPLETED FULL DIAGNOSTICS"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testAppendAndClearLog() {
|
||||||
|
diagnostics.appendLog("Test Message 123")
|
||||||
|
assertTrue(diagnostics.outputLog.value.contains("Test Message 123"))
|
||||||
|
|
||||||
|
diagnostics.clearLog()
|
||||||
|
assertTrue(diagnostics.outputLog.value.contains("cleared"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package com.example.netshareecohub.ethernet
|
||||||
|
|
||||||
|
import com.example.netshareecohub.routing.CommandResult
|
||||||
|
import com.example.netshareecohub.routing.ShellExecutor
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class MockShellExecutor(
|
||||||
|
private val rootAvailable: Boolean,
|
||||||
|
private val ethtoolAvailable: Boolean = false
|
||||||
|
) : ShellExecutor {
|
||||||
|
val executedCommands = mutableListOf<String>()
|
||||||
|
|
||||||
|
override fun isRootAvailable(): Boolean = rootAvailable
|
||||||
|
|
||||||
|
override fun executeSu(command: String): CommandResult {
|
||||||
|
return executeSu(listOf(command))
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun executeSu(commands: List<String>): CommandResult {
|
||||||
|
executedCommands.addAll(commands)
|
||||||
|
if (!rootAvailable) {
|
||||||
|
return CommandResult(1, "", "Permission denied")
|
||||||
|
}
|
||||||
|
val first = commands.firstOrNull() ?: ""
|
||||||
|
if (first.contains("which ethtool")) {
|
||||||
|
return if (ethtoolAvailable) CommandResult(0, "/system/bin/ethtool", "")
|
||||||
|
else CommandResult(1, "", "ethtool not found")
|
||||||
|
}
|
||||||
|
return CommandResult(0, "Success", "")
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun executeSh(command: String): CommandResult {
|
||||||
|
return CommandResult(0, "", "")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class EtToolSpeedManagerTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testNonRootReturnsUnsupportedMessage() {
|
||||||
|
val mockShell = MockShellExecutor(rootAvailable = false, ethtoolAvailable = false)
|
||||||
|
val speedManager = EtToolSpeedManager(mockShell)
|
||||||
|
|
||||||
|
assertFalse(speedManager.isSpeedConfigSupported())
|
||||||
|
assertEquals(
|
||||||
|
"Manual Ethernet speed configuration is not supported on this device.",
|
||||||
|
speedManager.getStatusMessage()
|
||||||
|
)
|
||||||
|
|
||||||
|
val (success, message) = speedManager.configureSpeed("eth0", SpeedMode.SPEED_100_FULL)
|
||||||
|
assertFalse(success)
|
||||||
|
assertEquals("Manual Ethernet speed configuration is not supported on this device.", message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testRootWithEthtoolSuccess() {
|
||||||
|
val mockShell = MockShellExecutor(rootAvailable = true, ethtoolAvailable = true)
|
||||||
|
val speedManager = EtToolSpeedManager(mockShell)
|
||||||
|
|
||||||
|
assertTrue(speedManager.isSpeedConfigSupported())
|
||||||
|
val (success, message) = speedManager.configureSpeed("eth0", SpeedMode.SPEED_100_FULL)
|
||||||
|
assertTrue(success)
|
||||||
|
assertTrue(message.contains("100 Mbps"))
|
||||||
|
assertTrue(mockShell.executedCommands.any { it.contains("ethtool -s eth0 speed 100 duplex full") })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package com.example.netshareecohub.ethernet
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class EthernetManagerTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testPrefixLengthToSubnetMask() {
|
||||||
|
assertEquals("255.255.255.0", EthernetManager.prefixLengthToSubnetMask(24))
|
||||||
|
assertEquals("255.255.0.0", EthernetManager.prefixLengthToSubnetMask(16))
|
||||||
|
assertEquals("255.0.0.0", EthernetManager.prefixLengthToSubnetMask(8))
|
||||||
|
assertEquals("255.255.255.255", EthernetManager.prefixLengthToSubnetMask(32))
|
||||||
|
assertEquals("255.255.255.240", EthernetManager.prefixLengthToSubnetMask(28))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testSubnetMaskToPrefixLength() {
|
||||||
|
assertEquals(24, EthernetManager.subnetMaskToPrefixLength("255.255.255.0"))
|
||||||
|
assertEquals(16, EthernetManager.subnetMaskToPrefixLength("255.255.0.0"))
|
||||||
|
assertEquals(8, EthernetManager.subnetMaskToPrefixLength("255.0.0.0"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testFormatMacAddress() {
|
||||||
|
val macBytes = byteArrayOf(0x00, 0x11, 0x22, 0x33, 0x44, 0x55)
|
||||||
|
val formatted = EthernetManager.formatMacAddress(macBytes)
|
||||||
|
assertEquals("00:11:22:33:44:55", formatted)
|
||||||
|
|
||||||
|
val emptyMac = EthernetManager.formatMacAddress(null)
|
||||||
|
assertEquals("00:00:00:00:00:00", emptyMac)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package com.example.netshareecohub.ethernet
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class SysfsReaderTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testReadOperstateFallback() {
|
||||||
|
val state = SysfsReader.readOperstate("non_existent_iface_99")
|
||||||
|
assertEquals("unknown", state)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testReadSpeedFallback() {
|
||||||
|
val speed = SysfsReader.readSpeed("non_existent_iface_99")
|
||||||
|
assertEquals(-1, speed)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testReadDuplexFallback() {
|
||||||
|
val duplex = SysfsReader.readDuplex("non_existent_iface_99")
|
||||||
|
assertEquals("unknown", duplex)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testReadStatsFallback() {
|
||||||
|
val stats = SysfsReader.readStats("non_existent_iface_99")
|
||||||
|
assertNotNull(stats)
|
||||||
|
assertEquals(0L, stats.rxBytes)
|
||||||
|
assertEquals(0L, stats.txBytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
package com.example.netshareecohub.routing
|
||||||
|
|
||||||
|
import org.junit.Assert.assertArrayEquals
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class IpPacketTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testIPv4HeaderBuildAndParse() {
|
||||||
|
val srcIp = "192.168.1.100"
|
||||||
|
val dstIp = "8.8.8.8"
|
||||||
|
val protocol = 17 // UDP
|
||||||
|
val payloadLen = 32
|
||||||
|
|
||||||
|
val headerBytes = PacketBuilder.buildIPv4Header(
|
||||||
|
srcIp = srcIp,
|
||||||
|
dstIp = dstIp,
|
||||||
|
protocol = protocol,
|
||||||
|
payloadLength = payloadLen,
|
||||||
|
id = 12345,
|
||||||
|
ttl = 64
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(20, headerBytes.size)
|
||||||
|
|
||||||
|
val parsed = PacketParser.parseIPv4(headerBytes, 20)
|
||||||
|
assertNotNull(parsed)
|
||||||
|
assertEquals(4, parsed!!.version)
|
||||||
|
assertEquals(20, parsed.ihl)
|
||||||
|
assertEquals(52, parsed.totalLength) // 20 + 32
|
||||||
|
assertEquals(12345, parsed.id)
|
||||||
|
assertEquals(64, parsed.ttl)
|
||||||
|
assertEquals(17, parsed.protocol)
|
||||||
|
assertEquals(srcIp, parsed.srcIp)
|
||||||
|
assertEquals(dstIp, parsed.dstIp)
|
||||||
|
|
||||||
|
// Checksum verification
|
||||||
|
assertTrue(ChecksumUtil.verifyIPv4Checksum(headerBytes, 20))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testUdpPacketBuildAndParse() {
|
||||||
|
val srcIp = "10.0.0.2"
|
||||||
|
val dstIp = "1.1.1.1"
|
||||||
|
val srcPort = 54321
|
||||||
|
val dstPort = 53
|
||||||
|
val payload = "Hello DNS".toByteArray(Charsets.UTF_8)
|
||||||
|
|
||||||
|
val fullPacket = PacketBuilder.buildUdpPacket(
|
||||||
|
srcIp = srcIp,
|
||||||
|
dstIp = dstIp,
|
||||||
|
srcPort = srcPort,
|
||||||
|
dstPort = dstPort,
|
||||||
|
payload = payload
|
||||||
|
)
|
||||||
|
|
||||||
|
val parsedIp = PacketParser.parseIPv4(fullPacket, fullPacket.size)
|
||||||
|
assertNotNull(parsedIp)
|
||||||
|
assertEquals(srcIp, parsedIp!!.srcIp)
|
||||||
|
assertEquals(dstIp, parsedIp.dstIp)
|
||||||
|
assertEquals(17, parsedIp.protocol)
|
||||||
|
|
||||||
|
val parsedUdp = PacketParser.parseUdp(fullPacket, parsedIp.ihl, fullPacket.size)
|
||||||
|
assertNotNull(parsedUdp)
|
||||||
|
assertEquals(srcPort, parsedUdp!!.srcPort)
|
||||||
|
assertEquals(dstPort, parsedUdp.dstPort)
|
||||||
|
assertEquals(8 + payload.size, parsedUdp.length)
|
||||||
|
|
||||||
|
val extractedPayload = fullPacket.copyOfRange(parsedIp.ihl + 8, fullPacket.size)
|
||||||
|
assertArrayEquals(payload, extractedPayload)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testTcpPacketBuildAndParse() {
|
||||||
|
val srcIp = "10.0.0.5"
|
||||||
|
val dstIp = "142.250.190.46"
|
||||||
|
val srcPort = 45678
|
||||||
|
val dstPort = 80
|
||||||
|
val seq = 1000L
|
||||||
|
val ack = 2000L
|
||||||
|
val flags = 0x18 // PSH + ACK
|
||||||
|
val payload = "GET / HTTP/1.1\r\n\r\n".toByteArray(Charsets.UTF_8)
|
||||||
|
|
||||||
|
val fullPacket = PacketBuilder.buildTcpPacket(
|
||||||
|
srcIp = srcIp,
|
||||||
|
dstIp = dstIp,
|
||||||
|
srcPort = srcPort,
|
||||||
|
dstPort = dstPort,
|
||||||
|
seqNumber = seq,
|
||||||
|
ackNumber = ack,
|
||||||
|
flags = flags,
|
||||||
|
payload = payload
|
||||||
|
)
|
||||||
|
|
||||||
|
val parsedIp = PacketParser.parseIPv4(fullPacket, fullPacket.size)
|
||||||
|
assertNotNull(parsedIp)
|
||||||
|
|
||||||
|
val parsedTcp = PacketParser.parseTcp(fullPacket, parsedIp!!.ihl, fullPacket.size)
|
||||||
|
assertNotNull(parsedTcp)
|
||||||
|
assertEquals(srcPort, parsedTcp!!.srcPort)
|
||||||
|
assertEquals(dstPort, parsedTcp.dstPort)
|
||||||
|
assertEquals(seq, parsedTcp.sequenceNumber)
|
||||||
|
assertEquals(ack, parsedTcp.ackNumber)
|
||||||
|
assertEquals(flags, parsedTcp.flags)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testIcmpEchoReplyBuildAndParse() {
|
||||||
|
val srcIp = "8.8.8.8"
|
||||||
|
val dstIp = "10.0.0.2"
|
||||||
|
val identifier = 0x1234
|
||||||
|
val sequence = 0x0001
|
||||||
|
val payload = "PingData12345".toByteArray(Charsets.UTF_8)
|
||||||
|
|
||||||
|
val fullPacket = PacketBuilder.buildIcmpEchoReply(
|
||||||
|
srcIp = srcIp,
|
||||||
|
dstIp = dstIp,
|
||||||
|
identifier = identifier,
|
||||||
|
sequence = sequence,
|
||||||
|
payload = payload
|
||||||
|
)
|
||||||
|
|
||||||
|
val parsedIp = PacketParser.parseIPv4(fullPacket, fullPacket.size)
|
||||||
|
assertNotNull(parsedIp)
|
||||||
|
assertEquals(1, parsedIp!!.protocol)
|
||||||
|
|
||||||
|
val parsedIcmp = PacketParser.parseIcmp(fullPacket, parsedIp.ihl, fullPacket.size)
|
||||||
|
assertNotNull(parsedIcmp)
|
||||||
|
assertEquals(0, parsedIcmp!!.type) // Echo Reply
|
||||||
|
assertEquals(0, parsedIcmp.code)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testInvalidPacketDataReturnsNull() {
|
||||||
|
val invalidBuffer = ByteArray(10) { 0 }
|
||||||
|
assertNull(PacketParser.parseIPv4(invalidBuffer, 10))
|
||||||
|
|
||||||
|
val corruptVersionBuffer = ByteArray(20)
|
||||||
|
corruptVersionBuffer[0] = 0x55.toByte() // Version 5
|
||||||
|
assertNull(PacketParser.parseIPv4(corruptVersionBuffer, 20))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testIpStringConversion() {
|
||||||
|
val ipStr = "172.16.0.1"
|
||||||
|
val bytes = PacketParser.ipStringToBytes(ipStr)
|
||||||
|
assertEquals(4, bytes.size)
|
||||||
|
assertEquals(172.toByte(), bytes[0])
|
||||||
|
assertEquals(16.toByte(), bytes[1])
|
||||||
|
assertEquals(0.toByte(), bytes[2])
|
||||||
|
assertEquals(1.toByte(), bytes[3])
|
||||||
|
|
||||||
|
val convertedStr = PacketParser.bytesToIpString(bytes)
|
||||||
|
assertEquals(ipStr, convertedStr)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package com.example.netshareecohub.routing
|
||||||
|
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class FakeShellExecutor(
|
||||||
|
var rootAvailable: Boolean = true,
|
||||||
|
var shouldFailCommands: Boolean = false
|
||||||
|
) : ShellExecutor {
|
||||||
|
val executedCommands = mutableListOf<String>()
|
||||||
|
|
||||||
|
override fun isRootAvailable(): Boolean = rootAvailable
|
||||||
|
|
||||||
|
override fun executeSu(command: String): CommandResult {
|
||||||
|
return executeSu(listOf(command))
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun executeSu(commands: List<String>): CommandResult {
|
||||||
|
executedCommands.addAll(commands)
|
||||||
|
return if (shouldFailCommands) {
|
||||||
|
CommandResult(1, "", "Permission denied or command failed")
|
||||||
|
} else {
|
||||||
|
CommandResult(0, "uid=0(root)", "")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun executeSh(command: String): CommandResult {
|
||||||
|
executedCommands.add(command)
|
||||||
|
return CommandResult(0, "sh success", "")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class RootRoutingManagerTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testStartRoutingSuccess() {
|
||||||
|
val fakeShell = FakeShellExecutor(rootAvailable = true)
|
||||||
|
val rootManager = RootRoutingManager(fakeShell)
|
||||||
|
|
||||||
|
val success = rootManager.startRouting(
|
||||||
|
lanInterface = "eth0",
|
||||||
|
upstreamInterface = "wlan0",
|
||||||
|
dnsServer = "1.1.1.1"
|
||||||
|
)
|
||||||
|
|
||||||
|
assertTrue(success)
|
||||||
|
assertTrue(rootManager.isRoutingActive())
|
||||||
|
|
||||||
|
val commands = fakeShell.executedCommands
|
||||||
|
assertTrue(commands.any { it.contains("sysctl") || it.contains("ip_forward") })
|
||||||
|
assertTrue(commands.any { it.contains("POSTROUTING -o wlan0 -j MASQUERADE") })
|
||||||
|
assertTrue(commands.any { it.contains("FORWARD -i eth0 -o wlan0 -j ACCEPT") })
|
||||||
|
assertTrue(commands.any { it.contains("FORWARD -i wlan0 -o eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT") })
|
||||||
|
assertTrue(commands.any { it.contains("PREROUTING -i eth0 -p udp --dport 53 -j DNAT --to-destination 1.1.1.1:53") })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testStartRoutingFailsWithoutRoot() {
|
||||||
|
val fakeShell = FakeShellExecutor(rootAvailable = false)
|
||||||
|
val rootManager = RootRoutingManager(fakeShell)
|
||||||
|
|
||||||
|
val success = rootManager.startRouting("eth0", "wlan0")
|
||||||
|
|
||||||
|
assertFalse(success)
|
||||||
|
assertFalse(rootManager.isRoutingActive())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testStopRoutingCleansUpRules() {
|
||||||
|
val fakeShell = FakeShellExecutor(rootAvailable = true)
|
||||||
|
val rootManager = RootRoutingManager(fakeShell)
|
||||||
|
|
||||||
|
rootManager.startRouting("eth0", "wlan0", "8.8.8.8")
|
||||||
|
fakeShell.executedCommands.clear()
|
||||||
|
|
||||||
|
val stopped = rootManager.stopRouting("eth0", "wlan0", "8.8.8.8")
|
||||||
|
|
||||||
|
assertTrue(stopped)
|
||||||
|
assertFalse(rootManager.isRoutingActive())
|
||||||
|
|
||||||
|
val commands = fakeShell.executedCommands
|
||||||
|
assertTrue(commands.any { it.contains("POSTROUTING -o wlan0 -j MASQUERADE") && it.contains("-D") })
|
||||||
|
assertTrue(commands.any { it.contains("FORWARD -i eth0 -o wlan0 -j ACCEPT") && it.contains("-D") })
|
||||||
|
assertTrue(commands.any { it.contains("PREROUTING -i eth0 -p udp --dport 53 -j DNAT --to-destination 8.8.8.8:53") && it.contains("-D") })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
package com.example.netshareecohub.routing
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.ContextWrapper
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class FakeContext : ContextWrapper(null)
|
||||||
|
|
||||||
|
class RoutingManagerTest {
|
||||||
|
|
||||||
|
private fun createDummyContext(): Context = FakeContext()
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testInitialStatusIsStopped() {
|
||||||
|
val manager = RoutingManager(
|
||||||
|
rootRoutingManager = RootRoutingManager(FakeShellExecutor(false))
|
||||||
|
)
|
||||||
|
|
||||||
|
val status = manager.status.value
|
||||||
|
assertEquals(RoutingMode.NON_ROOT_VPN, status.mode)
|
||||||
|
assertEquals(RoutingState.STOPPED, status.state)
|
||||||
|
assertNull(status.errorMessage)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testUpdateMetrics() {
|
||||||
|
val manager = RoutingManager(
|
||||||
|
rootRoutingManager = RootRoutingManager(FakeShellExecutor(false))
|
||||||
|
)
|
||||||
|
|
||||||
|
manager.updateMetrics(rxBytes = 1024, txBytes = 2048, rxPackets = 10, txPackets = 20)
|
||||||
|
|
||||||
|
val status = manager.status.value
|
||||||
|
assertEquals(1024L, status.rxBytes)
|
||||||
|
assertEquals(2048L, status.txBytes)
|
||||||
|
assertEquals(10L, status.rxPackets)
|
||||||
|
assertEquals(20L, status.txPackets)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testUpdateUpstreamInterface() {
|
||||||
|
val manager = RoutingManager(
|
||||||
|
rootRoutingManager = RootRoutingManager(FakeShellExecutor(false))
|
||||||
|
)
|
||||||
|
|
||||||
|
manager.updateUpstreamInterface("wlan0")
|
||||||
|
assertEquals("wlan0", manager.status.value.upstreamInterface)
|
||||||
|
|
||||||
|
manager.updateUpstreamInterface("eth1")
|
||||||
|
assertEquals("eth1", manager.status.value.upstreamInterface)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testRootModeRoutingSuccess() {
|
||||||
|
val fakeShell = FakeShellExecutor(rootAvailable = true)
|
||||||
|
val rootManager = RootRoutingManager(fakeShell)
|
||||||
|
val manager = RoutingManager(rootRoutingManager = rootManager)
|
||||||
|
|
||||||
|
val dummyContext = createDummyContext()
|
||||||
|
|
||||||
|
manager.startRouting(
|
||||||
|
context = dummyContext,
|
||||||
|
mode = RoutingMode.ROOT_IPTABLES,
|
||||||
|
lanInterface = "eth0",
|
||||||
|
upstreamInterface = "wlan0",
|
||||||
|
dnsServer = "8.8.8.8"
|
||||||
|
)
|
||||||
|
|
||||||
|
val status = manager.status.value
|
||||||
|
assertEquals(RoutingMode.ROOT_IPTABLES, status.mode)
|
||||||
|
assertEquals(RoutingState.ACTIVE, status.state)
|
||||||
|
assertEquals("eth0", status.lanInterface)
|
||||||
|
assertEquals("wlan0", status.upstreamInterface)
|
||||||
|
|
||||||
|
manager.stopRouting(dummyContext)
|
||||||
|
assertEquals(RoutingState.STOPPED, manager.status.value.state)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testRootModeRoutingFailureWithoutRoot() {
|
||||||
|
val fakeShell = FakeShellExecutor(rootAvailable = false)
|
||||||
|
val rootManager = RootRoutingManager(fakeShell)
|
||||||
|
val manager = RoutingManager(rootRoutingManager = rootManager)
|
||||||
|
|
||||||
|
val dummyContext = createDummyContext()
|
||||||
|
|
||||||
|
manager.startRouting(
|
||||||
|
context = dummyContext,
|
||||||
|
mode = RoutingMode.ROOT_IPTABLES,
|
||||||
|
lanInterface = "eth0",
|
||||||
|
upstreamInterface = "wlan0"
|
||||||
|
)
|
||||||
|
|
||||||
|
val status = manager.status.value
|
||||||
|
assertEquals(RoutingState.ERROR, status.state)
|
||||||
|
assertEquals("Failed to start Root IP Tables routing", status.errorMessage)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package com.example.netshareecohub.routing
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import java.io.ByteArrayInputStream
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.io.FileDescriptor
|
||||||
|
|
||||||
|
class TunNatEngineTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testIcmpEchoRequestTriggersEchoReply() {
|
||||||
|
val dummyFd = FileDescriptor()
|
||||||
|
val inStream = ByteArrayInputStream(ByteArray(0))
|
||||||
|
val outStream = ByteArrayOutputStream()
|
||||||
|
|
||||||
|
val engine = TunNatEngine(
|
||||||
|
fileDescriptor = dummyFd,
|
||||||
|
dnsServer = "8.8.8.8",
|
||||||
|
inputStreamOverride = inStream,
|
||||||
|
outputStreamOverride = outStream
|
||||||
|
)
|
||||||
|
|
||||||
|
// Build an ICMP Echo Request packet from 10.0.0.2 to 8.8.8.8
|
||||||
|
val icmpPayload = "TestPingPayload".toByteArray(Charsets.UTF_8)
|
||||||
|
val icmpLen = 8 + icmpPayload.size
|
||||||
|
val icmpReq = ByteArray(icmpLen)
|
||||||
|
icmpReq[0] = 8 // Echo Request
|
||||||
|
icmpReq[1] = 0 // Code 0
|
||||||
|
icmpReq[2] = 0
|
||||||
|
icmpReq[3] = 0
|
||||||
|
icmpReq[4] = 0x12
|
||||||
|
icmpReq[5] = 0x34
|
||||||
|
icmpReq[6] = 0x00
|
||||||
|
icmpReq[7] = 0x01
|
||||||
|
System.arraycopy(icmpPayload, 0, icmpReq, 8, icmpPayload.size)
|
||||||
|
|
||||||
|
val checksum = ChecksumUtil.computeChecksum(icmpReq, 0, icmpLen)
|
||||||
|
icmpReq[2] = ((checksum ushr 8) and 0xFF).toByte()
|
||||||
|
icmpReq[3] = (checksum and 0xFF).toByte()
|
||||||
|
|
||||||
|
val ipHeader = PacketBuilder.buildIPv4Header(
|
||||||
|
srcIp = "10.0.0.2",
|
||||||
|
dstIp = "8.8.8.8",
|
||||||
|
protocol = 1, // ICMP
|
||||||
|
payloadLength = icmpLen
|
||||||
|
)
|
||||||
|
|
||||||
|
val fullPacket = ByteArray(20 + icmpLen)
|
||||||
|
System.arraycopy(ipHeader, 0, fullPacket, 0, 20)
|
||||||
|
System.arraycopy(icmpReq, 0, fullPacket, 20, icmpLen)
|
||||||
|
|
||||||
|
// Process packet directly
|
||||||
|
engine.processPacket(fullPacket, fullPacket.size, outStream)
|
||||||
|
|
||||||
|
val writtenBytes = outStream.toByteArray()
|
||||||
|
assertTrue(writtenBytes.size >= 28) // IPv4 (20) + ICMP (8)
|
||||||
|
|
||||||
|
val replyIp = PacketParser.parseIPv4(writtenBytes, writtenBytes.size)
|
||||||
|
assertNotNull(replyIp)
|
||||||
|
assertEquals("8.8.8.8", replyIp!!.srcIp)
|
||||||
|
assertEquals("10.0.0.2", replyIp.dstIp)
|
||||||
|
assertEquals(1, replyIp.protocol)
|
||||||
|
|
||||||
|
val replyIcmp = PacketParser.parseIcmp(writtenBytes, replyIp.ihl, writtenBytes.size)
|
||||||
|
assertNotNull(replyIcmp)
|
||||||
|
assertEquals(0, replyIcmp!!.type) // Echo Reply
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testStatsTracker() {
|
||||||
|
val stats = NatStats(rxBytes = 500, txBytes = 300, rxPackets = 5, txPackets = 3)
|
||||||
|
assertEquals(500L, stats.rxBytes)
|
||||||
|
assertEquals(300L, stats.txBytes)
|
||||||
|
assertEquals(5L, stats.rxPackets)
|
||||||
|
assertEquals(3L, stats.txPackets)
|
||||||
|
}
|
||||||
|
}
|
||||||