Compare commits

..

45 Commits

Author SHA1 Message Date
Jason A. Donenfeld 0f128f99a1 Version bump
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-12 05:46:02 +02:00
Jason A. Donenfeld 61e3441bfb Application: require rootshell to use wgquick backend
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-12 05:42:24 +02:00
Jason A. Donenfeld 15e10d8fde ToolsInstaller: safer state machine
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-10 05:17:09 +02:00
Jason A. Donenfeld ea72e8b656 Version bump
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-07 04:59:47 +02:00
Jason A. Donenfeld 2ca27c2783 BaseActivity: style
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-07 04:49:15 +02:00
Jason A. Donenfeld f190db0754 BootShutdownReceiver: style
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-07 04:37:28 +02:00
Jason A. Donenfeld 8d27570eea Backend: abstract version information
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-07 04:35:07 +02:00
Jason A. Donenfeld 24605c9c01 Give Samuel heart attack by removing Dagger
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-07 04:12:42 +02:00
Jason A. Donenfeld 7b59353910 VersionPreference: account for checking state and move away from tools installer
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-07 03:27:06 +02:00
Jason A. Donenfeld ca7f4e5be9 FloatingActionMenu: 5.1 requires explicit text color
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-06 03:12:29 +02:00
Harsh Shandilya ab95ac83c9 MainActivity: Fix style
Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-06 02:07:26 +02:00
Jason A. Donenfeld 51fb57433b ToolsInstallerPreference: do not check for magisk on main thread
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-06 00:29:44 +02:00
Harsh Shandilya 0496b94aa8 build: Allow building release artifacts in-tree
This change avoids all need for changing any file under
VCS to insert signing keys and configs for release builds.

Example contents of keystore.properties

```
// Location of keystore, relative to module build.gradle,
// in this case, of the app module
storeFile=../wireguard.jks
storePassword=b3ty0uc4nth4xxth1s
keyAlias=wireguard
keyPassword=4ndr01dsux
```

Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-05 19:58:34 +05:30
Harsh Shandilya d8d6e99df1 MainActivity: Silence useless warning
Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-05 19:52:08 +05:30
Jason A. Donenfeld 377ba1c9d1 Version bump
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-05 16:07:56 +02:00
Jason A. Donenfeld 8ebeeb6d90 FloatingActionMenu: use appcompat theme
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-05 16:01:38 +02:00
Harsh Shandilya 3c3de065c6 MainActivity: collapse action menu on toolbar touch
Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-05 15:22:40 +02:00
Jason A. Donenfeld a17ec6b1f7 ToolsInstaller: allow installing as Magisk module
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-05 06:17:00 +02:00
Jason A. Donenfeld cbf8ac6538 libwg-go: better error when using unpatched Go
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-05 03:28:16 +02:00
Jason A. Donenfeld d4b1295e94 ActionBar: show single menu item as toolicon
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-05 03:09:51 +02:00
Jason A. Donenfeld db53e17e58 TunnelListFragment: hide menu when going to settings
Really the menu should be hidden when clicking on the action bar, too.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-05 03:05:58 +02:00
Jason A. Donenfeld f0a3e63743 MainActivity: style
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-05 02:47:59 +02:00
Jason A. Donenfeld d636e13717 fab: properly get theme color
Harsh changed this before, but my original way is what the support
library does internally.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-05 02:44:32 +02:00
Jason A. Donenfeld dea60e13c0 libwg-go: more efficient and safer string passing
It was unclear when the Go string was actually freed.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-05 02:18:12 +02:00
Harsh Shandilya 40a30d997d fab: Remove useless override
Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-05 02:05:35 +02:00
Harsh Shandilya dba8d0305e fab: Use themed context to set style
Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-05 02:05:23 +02:00
Jason A. Donenfeld 27072972ab DarkMode: move to shared preferences listener
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-05 02:02:09 +02:00
Jason A. Donenfeld d56e95c576 MainActivity: style
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-04 19:55:27 +02:00
Jason A. Donenfeld d0ef2c43d9 FloatingActionsMenu: remove unused imports
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-04 19:12:12 +02:00
Jason A. Donenfeld 0c0c1acc3b BaseActivity: support android 5 and 6 when clearing drawable cache
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-04 18:35:18 +02:00
Jason A. Donenfeld 48f796c463 LogExporterPreference: get all past processes
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-04 17:57:02 +02:00
Jason A. Donenfeld 8aab35a70d BaseActivity: invalidate icon cache on Android P
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-04 17:57:02 +02:00
Jason A. Donenfeld e5f6c24174 Bump version
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-04 07:16:10 +02:00
Jason A. Donenfeld 4cad06b7ce app: disable proguard
It's mostly a hindrance to debugging.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-04 07:16:10 +02:00
Jason A. Donenfeld c4e32328fc TunnelManager: disable dangerous intents for now
We need to think about how to allow this securely. It's not okay for all
apps to be allowed to twiddle with VPN settings.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-04 07:06:28 +02:00
Jason A. Donenfeld a2ccbf003c TunnelManager: new intents
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-04 07:06:28 +02:00
Jason A. Donenfeld 10ca2c8681 Preferences: don't use round icon
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-03 16:15:30 +02:00
Harsh Shandilya fd63e496e5 Preferences: Move version pref to top and add icon
Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-02 19:35:11 +02:00
Jason A. Donenfeld 567503abc7 Backends: print versions somewhere in log
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-02 19:26:33 +02:00
Harsh Shandilya 4671f59c67 android: Cleanup classes
- Use final modifer wherever possible
- Use try-with-resources for input/output streams

Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-02 19:14:56 +02:00
Harsh Shandilya 4986d92f3d crypto: KeyEncoding: Fix style
- Replace python style variable names with camel case
- Don't declare multiple variables in the same line

Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-02 19:12:30 +02:00
Jason A. Donenfeld 0b1c7cc35f Topic: John does things differently
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-02 18:44:35 +02:00
Jason A. Donenfeld 9e278c88e6 ExporterPreferences: disable control immediately
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-02 18:38:56 +02:00
Jason A. Donenfeld c3246060f5 Preferences: add log exporter
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-02 18:35:09 +02:00
Jason A. Donenfeld b7e025e381 libwg-go: fix style
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-01 18:27:30 +02:00
40 changed files with 662 additions and 622 deletions
+2
View File
@@ -13,3 +13,5 @@ build/
*.class
*.dex
*.iml
*.jks
keystore.properties
+28 -11
View File
@@ -1,13 +1,11 @@
apply plugin: 'com.android.application'
// Create a variable called keystorePropertiesFile, and initialize it to your
// keystore.properties file, in the rootProject folder.
final def keystorePropertiesFile = rootProject.file("keystore.properties")
android {
buildToolsVersion '27.0.3'
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
@@ -20,8 +18,30 @@ android {
applicationId 'com.wireguard.android'
minSdkVersion 21
targetSdkVersion 27
versionCode 420
versionName '0.0.20180601'
versionCode 424
versionName '0.0.20180612'
}
// If the keystore file exists
if (keystorePropertiesFile.exists()) {
// Initialize a new Properties() object called keystoreProperties.
final def keystoreProperties = new Properties()
// Load your keystore.properties file into the keystoreProperties object.
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
signingConfigs {
release {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile file(keystoreProperties['storeFile'])
storePassword keystoreProperties['storePassword']
}
}
}
buildTypes {
release {
if (keystorePropertiesFile.exists()) signingConfig signingConfigs.release
}
}
externalNativeBuild {
cmake {
@@ -32,19 +52,16 @@ android {
ext {
databindingVersion = '3.1.2'
supportLibsVersion = '27.1.1'
daggerVersion = '2.14.1'
streamsupportVersion = '1.6.0'
}
dependencies {
annotationProcessor "com.google.dagger:dagger-compiler:$daggerVersion"
implementation "com.android.databinding:library:$databindingVersion"
implementation "com.android.support:appcompat-v7:$supportLibsVersion"
implementation "com.android.support:cardview-v7:$supportLibsVersion"
implementation "com.android.support:design:$supportLibsVersion"
implementation "com.android.support:preference-v14:$supportLibsVersion"
implementation "com.android.support:support-annotations:$supportLibsVersion"
implementation "com.google.dagger:dagger:$daggerVersion"
implementation "net.sourceforge.streamsupport:android-retrofuture:$streamsupportVersion"
implementation "net.sourceforge.streamsupport:android-retrostreams:$streamsupportVersion"
}
-26
View File
@@ -1,26 +0,0 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /opt/android-sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# 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 *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
-dontwarn sun.misc.Unsafe
+13 -2
View File
@@ -8,6 +8,13 @@
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<permission
android:name="com.wireguard.android.permission.CONTROL_TUNNELS"
android:protectionLevel="dangerous"
android:icon="@mipmap/ic_launcher"
android:label="@string/permission_label"
android:description="@string/permission_description" />
<application
android:name=".Application"
android:allowBackup="false"
@@ -50,9 +57,13 @@
</intent-filter>
</receiver>
<receiver android:name=".backend.WgQuickBackend$WgQuickChangeReceiver">
<receiver
android:name=".model.TunnelManager$IntentReceiver"
android:permission="com.wireguard.android.permission.CONTROL_TUNNELS">
<intent-filter>
<action android:name="com.wireguard.android.WGQUICK_CHANGE" />
<action android:name="com.wireguard.android.action.REFRESH_TUNNEL_STATES" />
<action android:name="com.wireguard.android.action.SET_TUNNEL_UP" />
<action android:name="com.wireguard.android.action.SET_TUNNEL_DOWN" />
</intent-filter>
</receiver>
@@ -1,12 +1,10 @@
/*
* Copyright © 2018 Samuel Holland <samuel@sholland.org>
* Copyright © 2018 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
* SPDX-License-Identifier: GPL-2.0-or-later
*/
package com.wireguard.android;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Handler;
@@ -23,133 +21,82 @@ import com.wireguard.android.model.TunnelManager;
import com.wireguard.android.util.AsyncWorker;
import com.wireguard.android.util.RootShell;
import com.wireguard.android.util.ToolsInstaller;
import com.wireguard.android.util.Topic;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.concurrent.Executor;
import javax.inject.Qualifier;
import javax.inject.Scope;
import dagger.Component;
import dagger.Module;
import dagger.Provides;
/**
* Base context for the WireGuard Android application. This class (instantiated once during the
* application lifecycle) maintains and mediates access to the global state of the application.
*/
public class Application extends android.app.Application {
private static ApplicationComponent component;
private static WeakReference<Application> weakSelf;
private AsyncWorker asyncWorker;
private Backend backend;
private RootShell rootShell;
private SharedPreferences sharedPreferences;
private ToolsInstaller toolsInstaller;
private TunnelManager tunnelManager;
public Application() {
weakSelf = new WeakReference<>(this);
}
public static ApplicationComponent getComponent() {
if (component == null)
throw new IllegalStateException("Application instance not yet created");
return component;
public static Application get() {
return weakSelf.get();
}
public static AsyncWorker getAsyncWorker() {
return get().asyncWorker;
}
public static Backend getBackend() {
return get().backend;
}
public static Class getBackendType() {
return get().backend.getClass();
}
public static RootShell getRootShell() {
return get().rootShell;
}
public static SharedPreferences getSharedPreferences() {
return get().sharedPreferences;
}
public static ToolsInstaller getToolsInstaller() {
return get().toolsInstaller;
}
public static TunnelManager getTunnelManager() {
return get().tunnelManager;
}
@Override
public void onCreate() {
super.onCreate();
component = DaggerApplication_ApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
.build();
component.getTunnelManager().onCreate();
}
@ApplicationScope
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
AsyncWorker getAsyncWorker();
final Executor executor = AsyncTask.SERIAL_EXECUTOR;
final Handler handler = new Handler(Looper.getMainLooper());
final ConfigStore configStore = new FileConfigStore(getApplicationContext());
Class getBackendType();
asyncWorker = new AsyncWorker(executor, handler);
rootShell = new RootShell(getApplicationContext());
toolsInstaller = new ToolsInstaller(getApplicationContext());
ToolsInstaller getToolsInstaller();
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
AppCompatDelegate.setDefaultNightMode(
sharedPreferences.getBoolean("dark_theme", false) ?
AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO);
TunnelManager getTunnelManager();
Topic getThemeChangeTopic();
}
@Qualifier
public @interface ApplicationContext {
}
@Qualifier
public @interface ApplicationHandler {
}
@Scope
public @interface ApplicationScope {
}
@Module
public static final class ApplicationModule {
private final Context context;
private ApplicationModule(final Application application) {
context = application.getApplicationContext();
AppCompatDelegate.setDefaultNightMode(
getPreferences(context).getBoolean("dark_theme", false) ?
AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO);
if (new File("/sys/module/wireguard").exists()) {
try {
rootShell.start();
backend = new WgQuickBackend(getApplicationContext());
} catch (final Exception ignored) { }
}
if (backend == null)
backend = new GoBackend(getApplicationContext());
@ApplicationScope
@Provides
public static Backend getBackend(@ApplicationContext final Context context,
final RootShell rootShell,
final ToolsInstaller toolsInstaller) {
if (new File("/sys/module/wireguard").exists())
return new WgQuickBackend(context, rootShell, toolsInstaller);
else
return new GoBackend(context);
}
@ApplicationScope
@Provides
public static Class getBackendType(final Backend backend) {
return backend.getClass();
}
@ApplicationScope
@Provides
public static ConfigStore getConfigStore(@ApplicationContext final Context context) {
return new FileConfigStore(context);
}
@ApplicationScope
@Provides
public static Topic getThemeChangeTopic() {
return new Topic();
}
@ApplicationScope
@Provides
public static Executor getExecutor() {
return AsyncTask.SERIAL_EXECUTOR;
}
@ApplicationHandler
@ApplicationScope
@Provides
public static Handler getHandler() {
return new Handler(Looper.getMainLooper());
}
@ApplicationScope
@Provides
public static SharedPreferences getPreferences(@ApplicationContext final Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
@ApplicationContext
@ApplicationScope
@Provides
public Context getContext() {
return context;
}
tunnelManager = new TunnelManager(backend, configStore);
tunnelManager.onCreate();
}
}
@@ -20,13 +20,12 @@ public class BootShutdownReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
if (Application.getComponent().getBackendType() != WgQuickBackend.class) {
if (Application.getBackendType() != WgQuickBackend.class)
return;
}
final String action = intent.getAction();
if (action == null)
return;
final TunnelManager tunnelManager = Application.getComponent().getTunnelManager();
final TunnelManager tunnelManager = Application.getTunnelManager();
if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
Log.i(TAG, "Broadcast receiver restoring state (boot)");
tunnelManager.restoreState(false).whenComplete(ExceptionLoggers.D);
@@ -38,7 +38,6 @@ public class QuickTileService extends TileService {
private final OnStateChangedCallback onStateChangedCallback = new OnStateChangedCallback();
private final OnTunnelChangedCallback onTunnelChangedCallback = new OnTunnelChangedCallback();
private Tunnel tunnel;
private TunnelManager tunnelManager;
@Override
public void onClick() {
@@ -54,12 +53,11 @@ public class QuickTileService extends TileService {
@Override
public void onCreate() {
super.onCreate();
tunnelManager = Application.getComponent().getTunnelManager();
}
@Override
public void onStartListening() {
tunnelManager.addOnPropertyChangedCallback(onTunnelChangedCallback);
Application.getTunnelManager().addOnPropertyChangedCallback(onTunnelChangedCallback);
if (tunnel != null)
tunnel.addOnPropertyChangedCallback(onStateChangedCallback);
updateTile();
@@ -69,7 +67,7 @@ public class QuickTileService extends TileService {
public void onStopListening() {
if (tunnel != null)
tunnel.removeOnPropertyChangedCallback(onStateChangedCallback);
tunnelManager.removeOnPropertyChangedCallback(onTunnelChangedCallback);
Application.getTunnelManager().removeOnPropertyChangedCallback(onTunnelChangedCallback);
}
private void onToggleFinished(@SuppressWarnings("unused") final State state,
@@ -84,7 +82,7 @@ public class QuickTileService extends TileService {
private void updateTile() {
// Update the tunnel.
final Tunnel newTunnel = tunnelManager.getLastUsedTunnel();
final Tunnel newTunnel = Application.getTunnelManager().getLastUsedTunnel();
if (newTunnel != tunnel) {
if (tunnel != null)
tunnel.removeOnPropertyChangedCallback(onStateChangedCallback);
@@ -11,24 +11,19 @@ import android.databinding.CallbackRegistry;
import android.databinding.CallbackRegistry.NotifierCallback;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.wireguard.android.Application;
import com.wireguard.android.backend.GoBackend;
import com.wireguard.android.model.Tunnel;
import com.wireguard.android.model.TunnelManager;
import com.wireguard.android.util.Topic;
import java.lang.reflect.Field;
import java.util.Objects;
/**
* Base class for activities that need to remember the currently-selected tunnel.
*/
public abstract class BaseActivity extends AppCompatActivity implements Topic.Subscriber {
private static final String TAG = "WireGuard/" + BaseActivity.class.getSimpleName();
public abstract class BaseActivity extends ThemeChangeAwareActivity {
private static final String KEY_SELECTED_TUNNEL = "selected_tunnel";
private final SelectionChangeRegistry selectionChangeRegistry = new SelectionChangeRegistry();
@@ -45,8 +40,6 @@ public abstract class BaseActivity extends AppCompatActivity implements Topic.Su
@Override
protected void onCreate(final Bundle savedInstanceState) {
subscribeTopics();
// Restore the saved tunnel if there is one; otherwise grab it from the arguments.
String savedTunnelName = null;
if (savedInstanceState != null)
@@ -54,27 +47,20 @@ public abstract class BaseActivity extends AppCompatActivity implements Topic.Su
else if (getIntent() != null)
savedTunnelName = getIntent().getStringExtra(KEY_SELECTED_TUNNEL);
if (savedTunnelName != null) {
final TunnelManager tunnelManager = Application.getComponent().getTunnelManager();
final TunnelManager tunnelManager = Application.getTunnelManager();
selectedTunnel = tunnelManager.getTunnels().get(savedTunnelName);
}
// The selected tunnel must be set before the superclass method recreates fragments.
super.onCreate(savedInstanceState);
if (Application.getComponent().getBackendType() == GoBackend.class) {
if (Application.getBackendType() == GoBackend.class) {
final Intent intent = GoBackend.VpnService.prepare(this);
if (intent != null) {
if (intent != null)
startActivityForResult(intent, 0);
}
}
}
@Override
protected void onDestroy() {
unsubscribeTopics();
super.onDestroy();
}
@Override
protected void onSaveInstanceState(final Bundle outState) {
if (selectedTunnel != null)
@@ -118,28 +104,4 @@ public abstract class BaseActivity extends AppCompatActivity implements Topic.Su
super(new SelectionChangeNotifier());
}
}
@Override
public void onTopicPublished(Topic topic) {
try {
Field f = getResources().getClass().getDeclaredField("mResourcesImpl");
f.setAccessible(true);
Object o = f.get(getResources());
f = o.getClass().getDeclaredField("mDrawableCache");
f.setAccessible(true);
o = f.get(o);
f = o.getClass().getSuperclass().getDeclaredField("mThemedEntries");
f.setAccessible(true);
o = f.get(o);
o.getClass().getMethod("clear").invoke(o);
} catch (Exception e) {
Log.e(TAG, "Failed to flush icon cache", e);
}
recreate();
}
@Override
public Topic[] getSubscription() {
return new Topic[] { Application.getComponent().getThemeChangeTopic() };
}
}
@@ -6,6 +6,7 @@
package com.wireguard.android.activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
@@ -71,17 +72,17 @@ public class MainActivity extends BaseActivity {
public void onBackPressed() {
TunnelListFragment fragment = null;
try {
fragment =
((TunnelListFragment)
getSupportFragmentManager().getFragments().get(0));
} catch (final ClassCastException ignored) {
}
if (fragment == null || !(fragment.collapseActionMenu())) {
fragment = ((TunnelListFragment) getSupportFragmentManager().getFragments().get(0));
} catch (final ClassCastException ignored) { }
if (fragment == null || !fragment.collapseActionMenu()) {
if (!moveToState(State.ofLayer(state.layer - 1)))
super.onBackPressed();
}
}
// We use onTouchListener here to avoid the UI click sound, hence
// calling View#performClick defeats the purpose of it.
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -95,6 +96,15 @@ public class MainActivity extends BaseActivity {
moveToState(initialState);
}
updateActionBar();
final int actionBarId = getResources().getIdentifier("action_bar", "id", getPackageName());
if (actionBarId != 0 && findViewById(actionBarId) != null) {
findViewById(actionBarId).setOnTouchListener((v, e) -> {
try {
((TunnelListFragment) getSupportFragmentManager().getFragments().get(0)).collapseActionMenu();
} catch (final ClassCastException ignored) { }
return false;
});
}
}
@Override
@@ -131,7 +141,6 @@ public class MainActivity extends BaseActivity {
super.onSaveInstanceState(outState);
}
@Override
protected void onSelectedTunnelChanged(final Tunnel oldTunnel, final Tunnel newTunnel) {
moveToState(newTunnel != null ? State.DETAIL : State.LIST);
@@ -21,7 +21,6 @@ import android.view.MenuItem;
import com.wireguard.android.Application;
import com.wireguard.android.R;
import com.wireguard.android.backend.WgQuickBackend;
import com.wireguard.android.util.Topic;
import java.util.ArrayList;
import java.util.Arrays;
@@ -33,7 +32,7 @@ import java.util.Map;
* Interface for changing application-global persistent settings.
*/
public class SettingsActivity extends AppCompatActivity implements Topic.Subscriber {
public class SettingsActivity extends ThemeChangeAwareActivity {
private final Map<Integer, PermissionRequestCallback> permissionRequestCallbacks = new HashMap<>();
private int permissionRequestCounter;
@@ -59,7 +58,6 @@ public class SettingsActivity extends AppCompatActivity implements Topic.Subscri
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
subscribeTopics();
if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, new SettingsFragment())
@@ -67,12 +65,6 @@ public class SettingsActivity extends AppCompatActivity implements Topic.Subscri
}
}
@Override
protected void onDestroy() {
unsubscribeTopics();
super.onDestroy();
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
@@ -99,47 +91,16 @@ public class SettingsActivity extends AppCompatActivity implements Topic.Subscri
void done(String[] permissions, int[] grantResults);
}
@Override
public void onTopicPublished(Topic topic) {
recreate();
}
@Override
public Topic[] getSubscription() {
return new Topic[] { Application.getComponent().getThemeChangeTopic() };
}
public static class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {
public static class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(final Bundle savedInstanceState, final String key) {
addPreferencesFromResource(R.xml.preferences);
if (Application.getComponent().getBackendType() != WgQuickBackend.class) {
if (Application.getBackendType() != WgQuickBackend.class) {
Preference pref = getPreferenceManager().findPreference("tools_installer");
getPreferenceScreen().removePreference(pref);
pref = getPreferenceManager().findPreference("restore_on_boot");
getPreferenceScreen().removePreference(pref);
}
}
@Override
public void onResume() {
super.onResume();
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onPause() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if ("dark_theme".equals(key)) {
AppCompatDelegate.setDefaultNightMode(
sharedPreferences.getBoolean(key, false) ? AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO);
Application.getComponent().getThemeChangeTopic().publish(false);
}
}
}
}
@@ -0,0 +1,77 @@
/*
* Copyright © 2018 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
* SPDX-License-Identifier: GPL-2.0-or-later
*/
package com.wireguard.android.activity;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.util.Log;
import com.wireguard.android.Application;
import java.lang.reflect.Field;
public abstract class ThemeChangeAwareActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = "WireGuard/" + ThemeChangeAwareActivity.class.getSimpleName();
private static Resources lastResources;
private static boolean lastDarkMode;
private static synchronized void invalidateDrawableCache(final Resources resources, final boolean darkMode) {
if (resources == lastResources && darkMode == lastDarkMode)
return;
try {
Field f;
Object o = resources;
try {
f = o.getClass().getDeclaredField("mResourcesImpl");
f.setAccessible(true);
o = f.get(o);
} catch (final Exception ignored) { }
f = o.getClass().getDeclaredField("mDrawableCache");
f.setAccessible(true);
o = f.get(o);
try {
o.getClass().getMethod("onConfigurationChange", int.class).invoke(o, -1);
} catch (final Exception ignored) {
o.getClass().getMethod("clear").invoke(o);
}
} catch (final Exception e) {
Log.e(TAG, "Failed to flush drawable cache", e);
}
lastResources = resources;
lastDarkMode = darkMode;
}
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Application.getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onDestroy() {
Application.getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
super.onDestroy();
}
@Override
public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String key) {
if ("dark_theme".equals(key)) {
final boolean darkMode = sharedPreferences.getBoolean(key, false);
AppCompatDelegate.setDefaultNightMode(
sharedPreferences.getBoolean(key, false) ?
AppCompatDelegate.MODE_NIGHT_YES :
AppCompatDelegate.MODE_NIGHT_NO);
invalidateDrawableCache(getResources(), darkMode);
recreate();
}
}
}
@@ -62,4 +62,19 @@ public interface Backend {
* @return The updated state of the tunnel.
*/
State setState(Tunnel tunnel, State state) throws Exception;
/**
* Determine version of underlying backend.
*
* @return The version of the backend.
* @throws Exception
*/
String getVersion() throws Exception;
/**
* Determine type name of underlying backend.
*
* @return Type name
*/
String getTypeName();
}
@@ -58,7 +58,11 @@ public final class GoBackend implements Backend {
private static native String wgVersion();
public static String getVersion() { return wgVersion(); }
@Override
public String getVersion() { return wgVersion(); }
@Override
public String getTypeName() { return "Go userspace"; }
@Override
public Config applyConfig(final Tunnel tunnel, final Config config) throws Exception {
@@ -137,7 +141,7 @@ public final class GoBackend implements Backend {
// Build config
final Interface iface = config.getInterface();
final String goConfig;
try (Formatter fmt = new Formatter(new StringBuilder())) {
try (final Formatter fmt = new Formatter(new StringBuilder())) {
fmt.format("replace_peers=true\n");
if (iface.getPrivateKey() != null)
fmt.format("private_key=%s\n", KeyEncoding.keyToHex(KeyEncoding.keyFromBase64(iface.getPrivateKey())));
@@ -184,11 +188,12 @@ public final class GoBackend implements Backend {
builder.setMtu(mtu);
builder.setBlocking(true);
final ParcelFileDescriptor tun = builder.establish();
if (tun == null)
throw new Exception("Unable to create tun device");
currentTunnelHandle = wgTurnOn(tunnel.getName(), tun.detachFd(), goConfig);
try (final ParcelFileDescriptor tun = builder.establish()) {
if (tun == null)
throw new Exception("Unable to create tun device");
Log.d(TAG, "Go backend v" + wgVersion());
currentTunnelHandle = wgTurnOn(tunnel.getName(), tun.detachFd(), goConfig);
}
if (currentTunnelHandle < 0)
throw new Exception("Unable to turn tunnel on (wgTurnOn return " + currentTunnelHandle + ')');
@@ -228,7 +233,7 @@ public final class GoBackend implements Backend {
@Override
public void onDestroy() {
for (final Tunnel tunnel : Application.getComponent().getTunnelManager().getTunnels()) {
for (final Tunnel tunnel : Application.getTunnelManager().getTunnels()) {
if (tunnel != null && tunnel.getState() != State.DOWN)
tunnel.setState(State.DOWN);
}
@@ -237,11 +242,11 @@ public final class GoBackend implements Backend {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
public int onStartCommand(final Intent intent, final int flags, final int startId) {
vpnService.complete(this);
if (intent == null || intent.getComponent() == null || !intent.getComponent().getPackageName().equals(getPackageName())) {
Log.d(TAG, "Service started by Always-on VPN feature");
Application.getComponent().getTunnelManager().restoreState(true).whenComplete(ExceptionLoggers.D);
Application.getTunnelManager().restoreState(true).whenComplete(ExceptionLoggers.D);
}
return super.onStartCommand(intent, flags, startId);
}
@@ -6,17 +6,13 @@
package com.wireguard.android.backend;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.wireguard.android.Application;
import com.wireguard.android.model.Tunnel;
import com.wireguard.android.model.Tunnel.State;
import com.wireguard.android.model.Tunnel.Statistics;
import com.wireguard.android.util.RootShell;
import com.wireguard.android.util.ToolsInstaller;
import com.wireguard.config.Config;
import java.io.File;
@@ -38,16 +34,23 @@ public final class WgQuickBackend implements Backend {
private static final String TAG = "WireGuard/" + WgQuickBackend.class.getSimpleName();
private final File localTemporaryDir;
private final RootShell rootShell;
private final ToolsInstaller toolsInstaller;
public WgQuickBackend(final Context context, final RootShell rootShell,
final ToolsInstaller toolsInstaller) {
public WgQuickBackend(final Context context) {
localTemporaryDir = new File(context.getCacheDir(), "tmp");
this.rootShell = rootShell;
this.toolsInstaller = toolsInstaller;
}
@Override
public String getVersion() throws Exception {
final List<String> output = new ArrayList<>();
if (Application.getRootShell()
.run(output, "cat /sys/module/wireguard/version") != 0 || output.isEmpty())
throw new Exception("Unable to determine kernel module version");
return output.get(0);
}
@Override
public String getTypeName() { return "Kernel module"; }
@Override
public Config applyConfig(final Tunnel tunnel, final Config config) throws Exception {
if (tunnel.getState() == State.UP) {
@@ -69,8 +72,8 @@ public final class WgQuickBackend implements Backend {
final List<String> output = new ArrayList<>();
// Don't throw an exception here or nothing will show up in the UI.
try {
toolsInstaller.ensureToolsAvailable();
if (rootShell.run(output, "wg show interfaces") != 0 || output.isEmpty())
Application.getToolsInstaller().ensureToolsAvailable();
if (Application.getRootShell().run(output, "wg show interfaces") != 0 || output.isEmpty())
return Collections.emptySet();
} catch (final Exception e) {
Log.w(TAG, "Unable to enumerate running tunnels", e);
@@ -98,7 +101,7 @@ public final class WgQuickBackend implements Backend {
if (state == originalState)
return originalState;
Log.d(TAG, "Changing tunnel " + tunnel.getName() + " to state " + state);
toolsInstaller.ensureToolsAvailable();
Application.getToolsInstaller().ensureToolsAvailable();
setStateInternal(tunnel, tunnel.getConfig(), state);
return getState(tunnel);
}
@@ -106,23 +109,17 @@ public final class WgQuickBackend implements Backend {
private void setStateInternal(final Tunnel tunnel, final Config config, final State state)
throws Exception {
final File tempFile = new File(localTemporaryDir, tunnel.getName() + ".conf");
try (FileOutputStream stream = new FileOutputStream(tempFile, false)) {
try (final FileOutputStream stream = new FileOutputStream(tempFile, false)) {
stream.write(config.toString().getBytes(StandardCharsets.UTF_8));
}
final String command = String.format("wg-quick %s '%s'",
String command = String.format("wg-quick %s '%s'",
state.toString().toLowerCase(), tempFile.getAbsolutePath());
final int result = rootShell.run(null, command);
if (state == State.UP)
command = "cat /sys/module/wireguard/version && " + command;
final int result = Application.getRootShell().run(null, command);
// noinspection ResultOfMethodCallIgnored
tempFile.delete();
if (result != 0)
throw new Exception("Unable to configure tunnel (wg-quick returned " + result + ')');
}
public static final class WgQuickChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
Log.d(TAG, "Refreshing tunnel states");
Application.getComponent().getTunnelManager().refreshTunnelStates();
}
}
}
@@ -9,7 +9,6 @@ package com.wireguard.android.configStore;
import android.content.Context;
import android.util.Log;
import com.wireguard.android.Application.ApplicationContext;
import com.wireguard.config.Config;
import java.io.File;
@@ -32,7 +31,7 @@ public final class FileConfigStore implements ConfigStore {
private final Context context;
public FileConfigStore(@ApplicationContext final Context context) {
public FileConfigStore(final Context context) {
this.context = context;
}
@@ -42,7 +41,7 @@ public final class FileConfigStore implements ConfigStore {
final File file = fileFor(name);
if (!file.createNewFile())
throw new IOException("Configuration file " + file.getName() + " already exists");
try (FileOutputStream stream = new FileOutputStream(file, false)) {
try (final FileOutputStream stream = new FileOutputStream(file, false)) {
stream.write(config.toString().getBytes(StandardCharsets.UTF_8));
}
return config;
@@ -70,7 +69,7 @@ public final class FileConfigStore implements ConfigStore {
@Override
public Config load(final String name) throws IOException {
try (FileInputStream stream = new FileInputStream(fileFor(name))) {
try (final FileInputStream stream = new FileInputStream(fileFor(name))) {
return Config.from(stream);
}
}
@@ -95,7 +94,7 @@ public final class FileConfigStore implements ConfigStore {
final File file = fileFor(name);
if (!file.isFile())
throw new FileNotFoundException("Configuration file " + file.getName() + " not found");
try (FileOutputStream stream = new FileOutputStream(file, false)) {
try (final FileOutputStream stream = new FileOutputStream(file, false)) {
stream.write(config.toString().getBytes(StandardCharsets.UTF_8));
}
return config;
@@ -128,7 +128,7 @@ public class TunnelEditorFragment extends BaseFragment {
}
if (tunnel == null) {
Log.d(TAG, "Attempting to create new tunnel " + binding.getConfig().getName());
final TunnelManager manager = Application.getComponent().getTunnelManager();
final TunnelManager manager = Application.getTunnelManager();
manager.create(binding.getConfig().getName(), newConfig)
.whenComplete(this::onTunnelCreated);
} else if (!tunnel.getName().equals(binding.getConfig().getName())) {
@@ -34,7 +34,6 @@ import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import com.wireguard.android.Application;
import com.wireguard.android.Application.ApplicationComponent;
import com.wireguard.android.R;
import com.wireguard.android.activity.TunnelCreatorActivity;
import com.wireguard.android.databinding.TunnelListFragmentBinding;
@@ -70,9 +69,7 @@ public class TunnelListFragment extends BaseFragment {
private final MultiChoiceModeListener actionModeListener = new ActionModeListener();
private final ListViewCallbacks listViewCallbacks = new ListViewCallbacks();
private ActionMode actionMode;
private AsyncWorker asyncWorker;
private TunnelListFragmentBinding binding;
private TunnelManager tunnelManager;
public boolean collapseActionMenu() {
if (binding.createMenu.isExpanded()) {
@@ -90,7 +87,7 @@ public class TunnelListFragment extends BaseFragment {
final Collection<CompletableFuture<Tunnel>> futureTunnels = new ArrayList<>();
final List<Throwable> throwables = new ArrayList<>();
asyncWorker.supplyAsync(() -> {
Application.getAsyncWorker().supplyAsync(() -> {
final String[] columns = {OpenableColumns.DISPLAY_NAME};
String name = null;
try (Cursor cursor = contentResolver.query(uri, columns,
@@ -137,11 +134,11 @@ public class TunnelListFragment extends BaseFragment {
throwables.add(e);
}
if (config != null)
futureTunnels.add(tunnelManager.create(name, config).toCompletableFuture());
futureTunnels.add(Application.getTunnelManager().create(name, config).toCompletableFuture());
}
}
} else {
futureTunnels.add(tunnelManager.create(name,
futureTunnels.add(Application.getTunnelManager().create(name,
Config.from(contentResolver.openInputStream(uri))).toCompletableFuture());
}
@@ -190,9 +187,6 @@ public class TunnelListFragment extends BaseFragment {
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ApplicationComponent applicationComponent = Application.getComponent();
asyncWorker = applicationComponent.getAsyncWorker();
tunnelManager = applicationComponent.getTunnelManager();
}
@Override
@@ -229,6 +223,12 @@ public class TunnelListFragment extends BaseFragment {
binding.createMenu.collapse();
}
@Override
public void onPause() {
binding.createMenu.collapse();
super.onPause();
}
@Override
public void onSelectedTunnelChanged(final Tunnel oldTunnel, final Tunnel newTunnel) {
// Do nothing.
@@ -269,16 +269,15 @@ public class TunnelListFragment extends BaseFragment {
tunnels.size() + throwables.size(),
tunnels.size(), tunnels.size() + throwables.size());
if (binding != null) {
if (binding != null)
Snackbar.make(binding.mainContainer, message, Snackbar.LENGTH_LONG).show();
}
}
@Override
public void onViewStateRestored(final Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
binding.setFragment(this);
binding.setTunnels(tunnelManager.getTunnels());
binding.setTunnels(Application.getTunnelManager().getTunnels());
}
private final class ActionModeListener implements MultiChoiceModeListener {
@@ -6,18 +6,19 @@
package com.wireguard.android.model;
import android.content.SharedPreferences;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.databinding.BaseObservable;
import android.databinding.Bindable;
import android.support.annotation.NonNull;
import com.wireguard.android.Application.ApplicationScope;
import com.wireguard.android.Application;
import com.wireguard.android.BR;
import com.wireguard.android.backend.Backend;
import com.wireguard.android.configStore.ConfigStore;
import com.wireguard.android.model.Tunnel.State;
import com.wireguard.android.model.Tunnel.Statistics;
import com.wireguard.android.util.AsyncWorker;
import com.wireguard.android.util.ExceptionLoggers;
import com.wireguard.android.util.ObservableKeyedList;
import com.wireguard.android.util.ObservableSortedKeyedArrayList;
@@ -29,8 +30,6 @@ import java.util.Collection;
import java.util.Comparator;
import java.util.Set;
import javax.inject.Inject;
import java9.util.Comparators;
import java9.util.concurrent.CompletableFuture;
import java9.util.concurrent.CompletionStage;
@@ -41,7 +40,6 @@ import java9.util.stream.StreamSupport;
* Maintains and mediates changes to the set of available WireGuard tunnels,
*/
@ApplicationScope
public final class TunnelManager extends BaseObservable {
private static final Comparator<String> COMPARATOR = Comparators.<String>thenComparing(
String.CASE_INSENSITIVE_ORDER, Comparators.naturalOrder());
@@ -49,23 +47,17 @@ public final class TunnelManager extends BaseObservable {
private static final String KEY_RESTORE_ON_BOOT = "restore_on_boot";
private static final String KEY_RUNNING_TUNNELS = "enabled_configs";
private final AsyncWorker asyncWorker;
private final Backend backend;
private final ConfigStore configStore;
private final SharedPreferences preferences;
private final ObservableSortedKeyedList<String, Tunnel> tunnels =
new ObservableSortedKeyedArrayList<>(COMPARATOR);
private Tunnel lastUsedTunnel;
private boolean haveLoaded;
private ArrayList<CompletableFuture<Void>> delayedLoadRestoreTunnels = new ArrayList<>();
private final ArrayList<CompletableFuture<Void>> delayedLoadRestoreTunnels = new ArrayList<>();
@Inject
public TunnelManager(final AsyncWorker asyncWorker, final Backend backend,
final ConfigStore configStore, final SharedPreferences preferences) {
this.asyncWorker = asyncWorker;
public TunnelManager(final Backend backend, final ConfigStore configStore) {
this.backend = backend;
this.configStore = configStore;
this.preferences = preferences;
}
private Tunnel addToList(final String name, final Config config, final State state) {
@@ -81,7 +73,7 @@ public final class TunnelManager extends BaseObservable {
final String message = "Tunnel " + name + " already exists";
return CompletableFuture.failedFuture(new IllegalArgumentException(message));
}
return asyncWorker.supplyAsync(() -> configStore.create(name, config))
return Application.getAsyncWorker().supplyAsync(() -> configStore.create(name, config))
.thenApply(savedConfig -> addToList(name, savedConfig, State.DOWN));
}
@@ -92,7 +84,7 @@ public final class TunnelManager extends BaseObservable {
if (wasLastUsed)
setLastUsedTunnel(null);
tunnels.remove(tunnel);
return asyncWorker.runAsync(() -> {
return Application.getAsyncWorker().runAsync(() -> {
if (originalState == State.UP)
backend.setState(tunnel, State.DOWN);
try {
@@ -119,17 +111,17 @@ public final class TunnelManager extends BaseObservable {
}
CompletionStage<Config> getTunnelConfig(final Tunnel tunnel) {
return asyncWorker.supplyAsync(() -> configStore.load(tunnel.getName()))
return Application.getAsyncWorker().supplyAsync(() -> configStore.load(tunnel.getName()))
.thenApply(tunnel::onConfigChanged);
}
CompletionStage<State> getTunnelState(final Tunnel tunnel) {
return asyncWorker.supplyAsync(() -> backend.getState(tunnel))
return Application.getAsyncWorker().supplyAsync(() -> backend.getState(tunnel))
.thenApply(tunnel::onStateChanged);
}
CompletionStage<Statistics> getTunnelStatistics(final Tunnel tunnel) {
return asyncWorker.supplyAsync(() -> backend.getStatistics(tunnel))
return Application.getAsyncWorker().supplyAsync(() -> backend.getStatistics(tunnel))
.thenApply(tunnel::onStatisticsChanged);
}
@@ -138,8 +130,8 @@ public final class TunnelManager extends BaseObservable {
}
public void onCreate() {
asyncWorker.supplyAsync(configStore::enumerate)
.thenAcceptBoth(asyncWorker.supplyAsync(backend::enumerate), this::onTunnelsLoaded)
Application.getAsyncWorker().supplyAsync(configStore::enumerate)
.thenAcceptBoth(Application.getAsyncWorker().supplyAsync(backend::enumerate), this::onTunnelsLoaded)
.whenComplete(ExceptionLoggers.E);
}
@@ -147,10 +139,10 @@ public final class TunnelManager extends BaseObservable {
private void onTunnelsLoaded(final Iterable<String> present, final Collection<String> running) {
for (final String name : present)
addToList(name, null, running.contains(name) ? State.UP : State.DOWN);
final String lastUsedName = preferences.getString(KEY_LAST_USED_TUNNEL, null);
final String lastUsedName = Application.getSharedPreferences().getString(KEY_LAST_USED_TUNNEL, null);
if (lastUsedName != null)
setLastUsedTunnel(tunnels.get(lastUsedName));
CompletableFuture<Void> toComplete[];
final CompletableFuture<Void>[] toComplete;
synchronized (delayedLoadRestoreTunnels) {
haveLoaded = true;
toComplete = delayedLoadRestoreTunnels.toArray(new CompletableFuture[delayedLoadRestoreTunnels.size()]);
@@ -167,7 +159,7 @@ public final class TunnelManager extends BaseObservable {
}
public void refreshTunnelStates() {
asyncWorker.supplyAsync(backend::enumerate)
Application.getAsyncWorker().supplyAsync(backend::enumerate)
.thenAccept(running -> {
for (final Tunnel tunnel : tunnels)
tunnel.onStateChanged(running.contains(tunnel.getName()) ? State.UP : State.DOWN);
@@ -175,17 +167,17 @@ public final class TunnelManager extends BaseObservable {
.whenComplete(ExceptionLoggers.E);
}
public CompletionStage<Void> restoreState(boolean force) {
if (!force && !preferences.getBoolean(KEY_RESTORE_ON_BOOT, false))
public CompletionStage<Void> restoreState(final boolean force) {
if (!force && !Application.getSharedPreferences().getBoolean(KEY_RESTORE_ON_BOOT, false))
return CompletableFuture.completedFuture(null);
synchronized (delayedLoadRestoreTunnels) {
if (!haveLoaded) {
CompletableFuture<Void> f = new CompletableFuture<>();
final CompletableFuture<Void> f = new CompletableFuture<>();
delayedLoadRestoreTunnels.add(f);
return f;
}
}
final Set<String> previouslyRunning = preferences.getStringSet(KEY_RUNNING_TUNNELS, null);
final Set<String> previouslyRunning = Application.getSharedPreferences().getStringSet(KEY_RUNNING_TUNNELS, null);
if (previouslyRunning == null)
return CompletableFuture.completedFuture(null);
return CompletableFuture.allOf(StreamSupport.stream(tunnels)
@@ -199,7 +191,7 @@ public final class TunnelManager extends BaseObservable {
.filter(tunnel -> tunnel.getState() == State.UP)
.map(Tunnel::getName)
.collect(Collectors.toUnmodifiableSet());
preferences.edit().putStringSet(KEY_RUNNING_TUNNELS, runningTunnels).apply();
Application.getSharedPreferences().edit().putStringSet(KEY_RUNNING_TUNNELS, runningTunnels).apply();
}
private void setLastUsedTunnel(final Tunnel tunnel) {
@@ -208,13 +200,13 @@ public final class TunnelManager extends BaseObservable {
lastUsedTunnel = tunnel;
notifyPropertyChanged(BR.lastUsedTunnel);
if (tunnel != null)
preferences.edit().putString(KEY_LAST_USED_TUNNEL, tunnel.getName()).apply();
Application.getSharedPreferences().edit().putString(KEY_LAST_USED_TUNNEL, tunnel.getName()).apply();
else
preferences.edit().remove(KEY_LAST_USED_TUNNEL).apply();
Application.getSharedPreferences().edit().remove(KEY_LAST_USED_TUNNEL).apply();
}
CompletionStage<Config> setTunnelConfig(final Tunnel tunnel, final Config config) {
return asyncWorker.supplyAsync(() -> {
return Application.getAsyncWorker().supplyAsync(() -> {
final Config appliedConfig = backend.applyConfig(tunnel, config);
return configStore.save(tunnel.getName(), appliedConfig);
}).thenApply(tunnel::onConfigChanged);
@@ -233,7 +225,7 @@ public final class TunnelManager extends BaseObservable {
if (wasLastUsed)
setLastUsedTunnel(null);
tunnels.remove(tunnel);
return asyncWorker.supplyAsync(() -> {
return Application.getAsyncWorker().supplyAsync(() -> {
if (originalState == State.UP)
backend.setState(tunnel, State.DOWN);
configStore.rename(tunnel.getName(), name);
@@ -255,7 +247,7 @@ public final class TunnelManager extends BaseObservable {
CompletionStage<State> setTunnelState(final Tunnel tunnel, final State state) {
// Ensure the configuration is loaded before trying to use it.
return tunnel.getConfigAsync().thenCompose(x ->
asyncWorker.supplyAsync(() -> backend.setState(tunnel, state))
Application.getAsyncWorker().supplyAsync(() -> backend.setState(tunnel, state))
).whenComplete((newState, e) -> {
// Ensure onStateChanged is always called (failure or not), and with the correct state.
tunnel.onStateChanged(e == null ? newState : tunnel.getState());
@@ -264,4 +256,43 @@ public final class TunnelManager extends BaseObservable {
saveState();
});
}
public static final class IntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
final TunnelManager manager = Application.getTunnelManager();
if (intent == null)
return;
final String action = intent.getAction();
if (action == null)
return;
if ("com.wireguard.android.action.REFRESH_TUNNEL_STATES".equals(action)) {
manager.refreshTunnelStates();
return;
}
/* We disable the below, for now, as the security model of allowing this
* might take a bit more consideration.
*/
if (true)
return;
final State state;
if ("com.wireguard.android.action.SET_TUNNEL_UP".equals(action))
state = State.UP;
else if ("com.wireguard.android.action.SET_TUNNEL_DOWN".equals(action))
state = State.DOWN;
else
return;
final String tunnelName = intent.getStringExtra("tunnel");
if (tunnelName == null)
return;
final Tunnel tunnel = manager.getTunnels().get(tunnelName);
if (tunnel == null)
return;
manager.setTunnelState(tunnel, state);
}
}
}
@@ -0,0 +1,126 @@
/*
* Copyright © 2018 Samuel Holland <samuel@sholland.org>
* Copyright © 2018 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
* SPDX-License-Identifier: GPL-2.0-or-later
*/
package com.wireguard.android.preference;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.design.widget.Snackbar;
import android.support.v7.preference.Preference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ContextThemeWrapper;
import com.wireguard.android.Application;
import com.wireguard.android.R;
import com.wireguard.android.activity.SettingsActivity;
import com.wireguard.android.util.ExceptionLoggers;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Preference implementing a button that asynchronously exports logs.
*/
public class LogExporterPreference extends Preference {
private static final String TAG = "WireGuard/" + LogExporterPreference.class.getSimpleName();
private String exportedFilePath;
public LogExporterPreference(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
private static SettingsActivity getPrefActivity(final Preference preference) {
final Context context = preference.getContext();
if (context instanceof ContextThemeWrapper) {
if (((ContextThemeWrapper) context).getBaseContext() instanceof SettingsActivity) {
return ((SettingsActivity) ((ContextThemeWrapper) context).getBaseContext());
}
}
return null;
}
private void exportLog() {
Application.getAsyncWorker().supplyAsync(() -> {
final File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
final File file = new File(path, "wireguard-log.txt");
if (!path.isDirectory() && !path.mkdirs())
throw new IOException("Cannot create output directory");
/* We would like to simply run `builder.redirectOutput(file);`, but this is API 26.
* Instead we have to do this dance, since logcat appends.
*/
new FileOutputStream(file).close();
try {
final Process process = Runtime.getRuntime().exec(new String[]{
"logcat", "-b", "all", "-d", "-v", "threadtime", "-f", file.getAbsolutePath(), "*:V"});
if (process.waitFor() != 0) {
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
final StringBuilder errors = new StringBuilder();
errors.append("Unable to run logcat: ");
String line;
while ((line = reader.readLine()) != null)
errors.append(line);
throw new Exception(errors.toString());
}
}
} catch (final Exception e) {
// noinspection ResultOfMethodCallIgnored
file.delete();
throw e;
}
return file.getAbsolutePath();
}).whenComplete(this::exportLogComplete);
}
private void exportLogComplete(final String filePath, final Throwable throwable) {
if (throwable != null) {
final String error = ExceptionLoggers.unwrapMessage(throwable);
final String message = getContext().getString(R.string.log_export_error, error);
Log.e(TAG, message, throwable);
Snackbar.make(
getPrefActivity(this).findViewById(android.R.id.content),
message, Snackbar.LENGTH_LONG).show();
setEnabled(true);
} else {
exportedFilePath = filePath;
notifyChanged();
}
}
@Override
public CharSequence getSummary() {
return exportedFilePath == null ?
getContext().getString(R.string.log_export_summary) :
getContext().getString(R.string.log_export_success, exportedFilePath);
}
@Override
public CharSequence getTitle() {
return getContext().getString(R.string.log_exporter_title);
}
@Override
protected void onClick() {
getPrefActivity(this).ensurePermissions(
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
(permissions, granted) -> {
if (granted.length > 0 && granted[0] == PackageManager.PERMISSION_GRANTED) {
setEnabled(false);
exportLog();
}
});
}
}
@@ -11,11 +11,10 @@ import android.support.annotation.NonNull;
import android.support.v7.preference.Preference;
import android.system.OsConstants;
import android.util.AttributeSet;
import android.util.Log;
import com.wireguard.android.Application;
import com.wireguard.android.Application.ApplicationComponent;
import com.wireguard.android.R;
import com.wireguard.android.util.AsyncWorker;
import com.wireguard.android.util.ToolsInstaller;
/**
@@ -24,16 +23,10 @@ import com.wireguard.android.util.ToolsInstaller;
*/
public class ToolsInstallerPreference extends Preference {
private final AsyncWorker asyncWorker;
private final ToolsInstaller toolsInstaller;
private State state = State.INITIAL;
@SuppressWarnings({"SameParameterValue", "WeakerAccess"})
public ToolsInstallerPreference(final Context context, final AttributeSet attrs) {
super(context, attrs);
final ApplicationComponent applicationComponent = Application.getComponent();
asyncWorker = applicationComponent.getAsyncWorker();
toolsInstaller = applicationComponent.getToolsInstaller();
}
@Override
@@ -49,31 +42,37 @@ public class ToolsInstallerPreference extends Preference {
@Override
public void onAttached() {
super.onAttached();
asyncWorker.supplyAsync(toolsInstaller::areInstalled).whenComplete(this::onCheckResult);
Application.getAsyncWorker().supplyAsync(Application.getToolsInstaller()::areInstalled).whenComplete(this::onCheckResult);
}
private void onCheckResult(final Integer result, final Throwable throwable) {
setState(throwable == null && result == OsConstants.EALREADY ?
State.ALREADY : State.INITIAL);
private void onCheckResult(final int state, final Throwable throwable) {
if (throwable != null || state == ToolsInstaller.ERROR)
setState(State.INITIAL);
else if ((state & ToolsInstaller.YES) == ToolsInstaller.YES)
setState(State.ALREADY);
else if ((state & (ToolsInstaller.MAGISK | ToolsInstaller.NO)) == (ToolsInstaller.MAGISK | ToolsInstaller.NO))
setState(State.INITIAL_MAGISK);
else if ((state & (ToolsInstaller.SYSTEM | ToolsInstaller.NO)) == (ToolsInstaller.SYSTEM | ToolsInstaller.NO))
setState(State.INITIAL_SYSTEM);
else
setState(State.INITIAL);
}
@Override
protected void onClick() {
setState(State.WORKING);
asyncWorker.supplyAsync(toolsInstaller::install).whenComplete(this::onInstallResult);
Application.getAsyncWorker().supplyAsync(Application.getToolsInstaller()::install).whenComplete(this::onInstallResult);
}
private void onInstallResult(final Integer result, final Throwable throwable) {
final State nextState;
if (throwable != null)
nextState = State.FAILURE;
else if (result == OsConstants.EXIT_SUCCESS)
nextState = State.SUCCESS;
else if (result == OsConstants.EALREADY)
nextState = State.ALREADY;
setState(State.FAILURE);
else if ((result & (ToolsInstaller.YES | ToolsInstaller.MAGISK)) == (ToolsInstaller.YES | ToolsInstaller.MAGISK))
setState(State.SUCCESS_MAGISK);
else if ((result & (ToolsInstaller.YES | ToolsInstaller.SYSTEM)) == (ToolsInstaller.YES | ToolsInstaller.SYSTEM))
setState(State.SUCCESS_SYSTEM);
else
nextState = State.FAILURE;
setState(nextState);
setState(State.FAILURE);
}
private void setState(@NonNull final State state) {
@@ -86,11 +85,14 @@ public class ToolsInstallerPreference extends Preference {
}
private enum State {
INITIAL(R.string.tools_installer_initial, true),
ALREADY(R.string.tools_installer_already, false),
FAILURE(R.string.tools_installer_failure, true),
INITIAL(R.string.tools_installer_initial, true),
SUCCESS(R.string.tools_installer_success, false),
WORKING(R.string.tools_installer_working, false);
WORKING(R.string.tools_installer_working, false),
INITIAL_SYSTEM(R.string.tools_installer_initial_system, true),
SUCCESS_SYSTEM(R.string.tools_installer_success_system, false),
INITIAL_MAGISK(R.string.tools_installer_initial_magisk, true),
SUCCESS_MAGISK(R.string.tools_installer_success_magisk, false);
private final int messageResourceId;
private final boolean shouldEnableView;
@@ -14,26 +14,27 @@ import android.util.AttributeSet;
import com.wireguard.android.Application;
import com.wireguard.android.BuildConfig;
import com.wireguard.android.R;
import com.wireguard.android.backend.Backend;
import com.wireguard.android.backend.GoBackend;
import com.wireguard.android.backend.WgQuickBackend;
import java.util.ArrayList;
import java.util.List;
public class VersionPreference extends Preference {
private String versionSummary;
public VersionPreference(final Context context, final AttributeSet attrs) {
super(context, attrs);
if (Application.getComponent().getBackendType() == GoBackend.class) {
versionSummary = getContext().getString(R.string.version_userspace_summary, GoBackend.getVersion());
} else if (Application.getComponent().getBackendType() == WgQuickBackend.class) {
Application.getComponent().getToolsInstaller().getVersion().whenComplete((version, exception) -> {
if (exception == null)
versionSummary = getContext().getString(R.string.version_kernel_summary, version);
else
versionSummary = getContext().getString(R.string.version_kernel_unknown_summary);
notifyChanged();
});
}
final Backend backend = Application.getBackend();
versionSummary = getContext().getString(R.string.version_summary_checking, backend.getTypeName().toLowerCase());
Application.getAsyncWorker().supplyAsync(backend::getVersion).whenComplete((version, exception) -> {
versionSummary = exception == null
? getContext().getString(R.string.version_summary, backend.getTypeName(), version)
: getContext().getString(R.string.version_summary_unknown, backend.getTypeName().toLowerCase());
notifyChanged();
});
}
@Override
@@ -17,12 +17,9 @@ import android.util.Log;
import android.view.ContextThemeWrapper;
import com.wireguard.android.Application;
import com.wireguard.android.Application.ApplicationComponent;
import com.wireguard.android.R;
import com.wireguard.android.activity.SettingsActivity;
import com.wireguard.android.model.Tunnel;
import com.wireguard.android.model.TunnelManager;
import com.wireguard.android.util.AsyncWorker;
import com.wireguard.android.util.ExceptionLoggers;
import com.wireguard.config.Config;
@@ -44,16 +41,10 @@ import java9.util.concurrent.CompletableFuture;
public class ZipExporterPreference extends Preference {
private static final String TAG = "WireGuard/" + ZipExporterPreference.class.getSimpleName();
private final AsyncWorker asyncWorker;
private final TunnelManager tunnelManager;
private String exportedFilePath;
@SuppressWarnings({"SameParameterValue", "WeakerAccess"})
public ZipExporterPreference(final Context context, final AttributeSet attrs) {
super(context, attrs);
final ApplicationComponent applicationComponent = Application.getComponent();
asyncWorker = applicationComponent.getAsyncWorker();
tunnelManager = applicationComponent.getTunnelManager();
}
private static SettingsActivity getPrefActivity(final Preference preference) {
@@ -67,7 +58,7 @@ public class ZipExporterPreference extends Preference {
}
private void exportZip() {
final List<Tunnel> tunnels = new ArrayList<>(tunnelManager.getTunnels());
final List<Tunnel> tunnels = new ArrayList<>(Application.getTunnelManager().getTunnels());
final List<CompletableFuture<Config>> futureConfigs = new ArrayList<>(tunnels.size());
for (final Tunnel tunnel : tunnels)
futureConfigs.add(tunnel.getConfigAsync().toCompletableFuture());
@@ -76,7 +67,7 @@ public class ZipExporterPreference extends Preference {
return;
}
CompletableFuture.allOf(futureConfigs.toArray(new CompletableFuture[futureConfigs.size()]))
.whenComplete((ignored1, exception) -> asyncWorker.supplyAsync(() -> {
.whenComplete((ignored1, exception) -> Application.getAsyncWorker().supplyAsync(() -> {
if (exception != null)
throw exception;
final File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
@@ -90,8 +81,7 @@ public class ZipExporterPreference extends Preference {
toString().getBytes(StandardCharsets.UTF_8));
}
zip.closeEntry();
zip.close();
} catch (Exception e) {
} catch (final Exception e) {
// noinspection ResultOfMethodCallIgnored
file.delete();
throw e;
@@ -103,14 +93,14 @@ public class ZipExporterPreference extends Preference {
private void exportZipComplete(final String filePath, final Throwable throwable) {
if (throwable != null) {
final String error = ExceptionLoggers.unwrapMessage(throwable);
final String message = getContext().getString(R.string.export_error, error);
final String message = getContext().getString(R.string.zip_export_error, error);
Log.e(TAG, message, throwable);
Snackbar.make(
getPrefActivity(this).findViewById(android.R.id.content),
message, Snackbar.LENGTH_LONG).show();
setEnabled(true);
} else {
exportedFilePath = filePath;
setEnabled(false);
notifyChanged();
}
}
@@ -118,8 +108,8 @@ public class ZipExporterPreference extends Preference {
@Override
public CharSequence getSummary() {
return exportedFilePath == null ?
getContext().getString(R.string.export_summary) :
getContext().getString(R.string.export_success, exportedFilePath);
getContext().getString(R.string.zip_export_summary) :
getContext().getString(R.string.zip_export_success, exportedFilePath);
}
@Override
@@ -132,8 +122,10 @@ public class ZipExporterPreference extends Preference {
getPrefActivity(this).ensurePermissions(
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
(permissions, granted) -> {
if (granted.length > 0 && granted[0] == PackageManager.PERMISSION_GRANTED)
if (granted.length > 0 && granted[0] == PackageManager.PERMISSION_GRANTED) {
setEnabled(false);
exportZip();
}
});
}
@@ -8,13 +8,8 @@ package com.wireguard.android.util;
import android.os.Handler;
import com.wireguard.android.Application.ApplicationHandler;
import com.wireguard.android.Application.ApplicationScope;
import java.util.concurrent.Executor;
import javax.inject.Inject;
import java9.util.concurrent.CompletableFuture;
import java9.util.concurrent.CompletionStage;
@@ -22,13 +17,11 @@ import java9.util.concurrent.CompletionStage;
* Helper class for running asynchronous tasks and ensuring they are completed on the main thread.
*/
@ApplicationScope
public class AsyncWorker {
private final Executor executor;
private final Handler handler;
@Inject
AsyncWorker(final Executor executor, @ApplicationHandler final Handler handler) {
public AsyncWorker(final Executor executor, final Handler handler) {
this.executor = executor;
this.handler = handler;
}
@@ -9,8 +9,6 @@ package com.wireguard.android.util;
import android.content.Context;
import android.util.Log;
import com.wireguard.android.Application.ApplicationContext;
import com.wireguard.android.Application.ApplicationScope;
import com.wireguard.android.R;
import java.io.BufferedReader;
@@ -23,13 +21,10 @@ import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.UUID;
import javax.inject.Inject;
/**
* Helper class for running commands as root.
*/
@ApplicationScope
public class RootShell {
private static final String SU = "su";
private static final String TAG = "WireGuard/" + RootShell.class.getSimpleName();
@@ -44,8 +39,7 @@ public class RootShell {
private OutputStreamWriter stdin;
private BufferedReader stdout;
@Inject
public RootShell(@ApplicationContext final Context context) {
public RootShell(final Context context) {
deviceNotRootedMessage = context.getString(R.string.error_root);
final File cacheDir = context.getCacheDir();
localBinaryDir = new File(cacheDir, "bin");
@@ -22,7 +22,7 @@ public final class SharedLibraryLoader {
private SharedLibraryLoader() {
}
public static final void loadSharedLibrary(final Context context, final String libName) {
public static void loadSharedLibrary(final Context context, final String libName) {
Throwable noAbiException;
try {
System.loadLibrary(libName);
@@ -35,12 +35,12 @@ public final class SharedLibraryLoader {
final ZipFile zipFile;
try {
zipFile = new ZipFile(new File(context.getApplicationInfo().sourceDir), ZipFile.OPEN_READ);
} catch (IOException e) {
} catch (final IOException e) {
throw new RuntimeException(e);
}
final String mappedLibName = System.mapLibraryName(libName);
byte buffer[] = new byte[1024 * 32];
final byte[] buffer = new byte[1024 * 32];
for (final String abi : Build.SUPPORTED_ABIS) {
final String libZipPath = "lib" + File.separatorChar + abi + File.separatorChar + mappedLibName;
final ZipEntry zipEntry = zipFile.getEntry(libZipPath);
@@ -50,13 +50,13 @@ public final class SharedLibraryLoader {
try {
f = File.createTempFile("lib", ".so", context.getCacheDir());
Log.d(TAG, "Extracting apk:/" + libZipPath + " to " + f.getAbsolutePath() + " and loading");
FileOutputStream out = new FileOutputStream(f);
InputStream in = zipFile.getInputStream(zipEntry);
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
try (final FileOutputStream out = new FileOutputStream(f);
final InputStream in = zipFile.getInputStream(zipEntry)) {
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
}
out.close();
System.load(f.getAbsolutePath());
return;
} catch (Exception e) {
@@ -64,6 +64,7 @@ public final class SharedLibraryLoader {
noAbiException = e;
} finally {
if (f != null)
// noinspection ResultOfMethodCallIgnored
f.delete();
}
}
@@ -11,27 +11,26 @@ import android.system.OsConstants;
import android.util.Log;
import com.wireguard.android.Application;
import com.wireguard.android.Application.ApplicationContext;
import com.wireguard.android.Application.ApplicationScope;
import com.wireguard.android.BuildConfig;
import com.wireguard.android.util.RootShell.NoRootException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import java9.util.concurrent.CompletionStage;
/**
* Helper to install WireGuard tools to the system partition.
*/
@ApplicationScope
public final class ToolsInstaller {
public static final int ERROR = 0x0;
public static final int YES = 0x1;
public static final int NO = 0x2;
public static final int MAGISK = 0x4;
public static final int SYSTEM = 0x8;
private static final String[][] EXECUTABLES = {
{"libwg.so", "wg"},
{"libwg-quick.so", "wg-quick"},
@@ -46,23 +45,12 @@ public final class ToolsInstaller {
private final File localBinaryDir;
private final Object lock = new Object();
private final File nativeLibraryDir;
private final RootShell rootShell;
private Boolean areToolsAvailable;
private Boolean installAsMagiskModule;
@Inject
public ToolsInstaller(@ApplicationContext final Context context, final RootShell rootShell) {
public ToolsInstaller(final Context context) {
localBinaryDir = new File(context.getCacheDir(), "bin");
nativeLibraryDir = new File(context.getApplicationInfo().nativeLibraryDir);
this.rootShell = rootShell;
}
public CompletionStage<String> getVersion() {
return Application.getComponent().getAsyncWorker().supplyAsync(() -> {
final ArrayList<String> output = new ArrayList<>();
if (rootShell.run(output, "cat /sys/module/wireguard/version") != 0 || output.isEmpty())
throw new RuntimeException("Unable to determine kernel module version");
return output.get(0);
});
}
private static File getInstallDir() {
@@ -79,7 +67,7 @@ public final class ToolsInstaller {
public int areInstalled() throws NoRootException {
if (INSTALL_DIR == null)
return OsConstants.ENOENT;
return ERROR;
final StringBuilder script = new StringBuilder();
for (final String[] names : EXECUTABLES) {
script.append(String.format("cmp -s '%s' '%s' && ",
@@ -88,9 +76,13 @@ public final class ToolsInstaller {
}
script.append("exit ").append(OsConstants.EALREADY).append(';');
try {
return rootShell.run(null, script.toString());
final int ret = Application.getRootShell().run(null, script.toString());
if (ret == OsConstants.EALREADY)
return willInstallAsMagiskModule() ? YES | MAGISK : YES | SYSTEM;
else
return willInstallAsMagiskModule() ? NO | MAGISK : NO | SYSTEM;
} catch (final IOException ignored) {
return OsConstants.EXIT_FAILURE;
return ERROR;
}
}
@@ -114,7 +106,20 @@ public final class ToolsInstaller {
}
}
public int install() throws NoRootException {
private boolean willInstallAsMagiskModule() {
synchronized (lock) {
if (installAsMagiskModule == null) {
try {
installAsMagiskModule = Application.getRootShell().run(null, "[ -d /sbin/.core/mirror -a -d /sbin/.core/img -a ! -f /cache/.disable_magisk ]") == OsConstants.EXIT_SUCCESS;
} catch (final Exception ignored) {
installAsMagiskModule = false;
}
}
return installAsMagiskModule;
}
}
private int installSystem() throws NoRootException {
if (INSTALL_DIR == null)
return OsConstants.ENOENT;
final StringBuilder script = new StringBuilder("set -ex; ");
@@ -125,12 +130,37 @@ public final class ToolsInstaller {
new File(nativeLibraryDir, names[0]), destination, destination, destination));
}
try {
return rootShell.run(null, script.toString());
return Application.getRootShell().run(null, script.toString()) == 0 ? YES | SYSTEM : ERROR;
} catch (final IOException ignored) {
return OsConstants.EXIT_FAILURE;
return ERROR;
}
}
private int installMagisk() throws NoRootException {
final StringBuilder script = new StringBuilder("set -ex; ");
script.append("trap 'rm -rf /sbin/.core/img/wireguard' INT TERM EXIT; ");
script.append(String.format("rm -rf /sbin/.core/img/wireguard/; mkdir -p /sbin/.core/img/wireguard%s; ", INSTALL_DIR));
script.append(String.format("printf 'name=WireGuard Command Line Tools\nversion=%s\nversionCode=%s\nauthor=zx2c4\ndescription=Command line tools for WireGuard\nminMagisk=1500\n' > /sbin/.core/img/wireguard/module.prop; ", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE));
script.append("touch /sbin/.core/img/wireguard/auto_mount; ");
for (final String[] names : EXECUTABLES) {
final File destination = new File("/sbin/.core/img/wireguard" + INSTALL_DIR, names[1]);
script.append(String.format("cp '%s' '%s'; chmod 755 '%s'; restorecon '%s' || true; ",
new File(nativeLibraryDir, names[0]), destination, destination, destination));
}
script.append("trap - INT TERM EXIT;");
try {
return Application.getRootShell().run(null, script.toString()) == 0 ? YES | MAGISK : ERROR;
} catch (final IOException ignored) {
return ERROR;
}
}
public int install() throws NoRootException {
return willInstallAsMagiskModule() ? installMagisk() : installSystem();
}
public int symlink() throws NoRootException {
final StringBuilder script = new StringBuilder("set -x; ");
for (final String[] names : EXECUTABLES) {
@@ -148,7 +178,7 @@ public final class ToolsInstaller {
script.append("exit ").append(OsConstants.EXIT_SUCCESS).append(';');
try {
return rootShell.run(null, script.toString());
return Application.getRootShell().run(null, script.toString());
} catch (final IOException ignored) {
return OsConstants.EXIT_FAILURE;
}
@@ -1,108 +0,0 @@
/*
* Copyright © 2017 John Wu <topjohnwu@gmail.com>
* SPDX-License-Identifier: GPL-2.0-or-later
*/
package com.wireguard.android.util;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class Topic {
private static final int NON_INIT = 0;
private static final int PENDING = 1;
private static final int PUBLISHED = 2;
private int state = NON_INIT;
private List<WeakReference<Subscriber>> subscribers;
private Object[] results;
public void subscribe(Subscriber sub) {
if (subscribers == null) {
subscribers = new LinkedList<>();
}
synchronized (subscribers) {
subscribers.add(new WeakReference<>(sub));
}
}
public void unsubscribe() {
subscribers = null;
}
public void unsubscribe(Subscriber sub) {
synchronized (subscribers) {
for (Iterator<WeakReference<Subscriber>> i = subscribers.iterator(); i.hasNext(); ) {
WeakReference<Subscriber> subscriber = i.next();
if (subscriber.get() == null || subscriber.get() == sub) {
i.remove();
}
}
}
}
public void reset() {
state = NON_INIT;
results = null;
}
public boolean isPublished() {
return state == PUBLISHED;
}
public void publish() {
publish(true);
}
public void publish(boolean record, Object... results) {
if (record)
state = PUBLISHED;
this.results = results;
if (subscribers != null) {
List<WeakReference<Subscriber>> subscribersCopy = new LinkedList<>();
synchronized (subscribers) {
subscribersCopy.addAll(subscribers);
}
for (WeakReference<Subscriber> subscriber : subscribersCopy) {
if (subscriber.get() != null)
subscriber.get().onTopicPublished(this);
}
}
}
public Object[] getResults() {
return results;
}
public boolean isPending() {
return state == PENDING;
}
public void setPending() {
state = PENDING;
}
public interface Subscriber {
default void subscribeTopics() {
for (Topic topic : getSubscription()) {
if (topic.isPublished()) {
onTopicPublished(topic);
}
topic.subscribe(this);
}
}
default void unsubscribeTopics() {
for (Topic event : getSubscription()) {
event.unsubscribe(this);
}
}
void onTopicPublished(Topic topic);
Topic[] getSubscription();
}
}
@@ -7,7 +7,6 @@
package com.wireguard.android.widget.fab;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.*;
import android.graphics.Paint.Style;
@@ -19,7 +18,6 @@ import android.support.annotation.*;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatImageButton;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
import com.wireguard.android.R;
@@ -60,12 +58,12 @@ public class FloatingActionButton extends AppCompatImageButton {
}
public static int getColorFromTheme(final Context context, final int themeResource, @ColorRes final int fallback) {
final TypedValue typedValue = new TypedValue();
final Resources.Theme theme = context.getTheme();
theme.resolveAttribute(themeResource, typedValue, true);
@ColorInt final int color = typedValue.data;
return color == 0 ? fallback : color;
final TypedArray a = context.obtainStyledAttributes(new int[]{themeResource});
try {
return a.getColor(0, ContextCompat.getColor(context, fallback));
} finally {
a.recycle();
}
}
void init(final Context context, final AttributeSet attributeSet) {
@@ -222,6 +220,7 @@ public class FloatingActionButton extends AppCompatImageButton {
final LayerDrawable layerDrawable = new LayerDrawable(
new Drawable[]{
//TODO(msf); replace these pngs with programatic elevation
getResources().getDrawable(mSize == SIZE_NORMAL ? R.drawable.fab_bg_normal : R.drawable.fab_bg_mini, null),
createFillDrawable(strokeWidth),
createOuterStrokeDrawable(strokeWidth),
@@ -14,16 +14,13 @@ import android.animation.TimeInterpolator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.ColorRes;
import android.support.annotation.Keep;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
import android.view.ContextThemeWrapper;
@@ -390,11 +387,6 @@ public class FloatingActionsMenu extends ViewGroup {
return new LayoutParams(super.generateLayoutParams(p));
}
@Override
protected boolean checkLayoutParams(final ViewGroup.LayoutParams p) {
return super.checkLayoutParams(p);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
@@ -418,7 +410,7 @@ public class FloatingActionsMenu extends ViewGroup {
button.getTag(R.id.fab_label) != null) continue;
final AppCompatTextView label = new AppCompatTextView(context);
label.setTextAppearance(getContext(), mLabelsStyle);
label.setTextAppearance(context, mLabelsStyle);
label.setText(button.getTitle());
addView(label);
@@ -25,10 +25,10 @@ public final class KeyEncoding {
// Prevent instantiation.
}
private static int decodeBase64(final char[] src, final int src_offset) {
private static int decodeBase64(final char[] src, final int srcOffset) {
int val = 0;
for (int i = 0; i < 4; ++i) {
final char c = src[i + src_offset];
final char c = src[i + srcOffset];
val |= (-1
+ ((((('A' - 1) - c) & (c - ('Z' + 1))) >>> 8) & (c - 64))
+ ((((('a' - 1) - c) & (c - ('z' + 1))) >>> 8) & (c - 70))
@@ -40,16 +40,16 @@ public final class KeyEncoding {
return val;
}
private static void encodeBase64(final byte[] src, final int src_offset,
final char[] dest, final int dest_offset) {
private static void encodeBase64(final byte[] src, final int srcOffset,
final char[] dest, final int destOffset) {
final byte[] input = {
(byte) ((src[src_offset] >>> 2) & 63),
(byte) ((src[src_offset] << 4 | ((src[1 + src_offset] & 0xff) >>> 4)) & 63),
(byte) ((src[1 + src_offset] << 2 | ((src[2 + src_offset] & 0xff) >>> 6)) & 63),
(byte) ((src[2 + src_offset]) & 63),
(byte) ((src[srcOffset] >>> 2) & 63),
(byte) ((src[srcOffset] << 4 | ((src[1 + srcOffset] & 0xff) >>> 4)) & 63),
(byte) ((src[1 + srcOffset] << 2 | ((src[2 + srcOffset] & 0xff) >>> 6)) & 63),
(byte) ((src[2 + srcOffset]) & 63),
};
for (int i = 0; i < 4; ++i) {
dest[i + dest_offset] = (char) (input[i] + 'A'
dest[i + destOffset] = (char) (input[i] + 'A'
+ (((25 - input[i]) >>> 8) & 6)
- (((51 - input[i]) >>> 8) & 75)
- (((61 - input[i]) >>> 8) & 15)
@@ -62,7 +62,8 @@ public final class KeyEncoding {
final byte[] key = new byte[KEY_LENGTH];
if (input.length != KEY_LENGTH_BASE64 || input[KEY_LENGTH_BASE64 - 1] != '=')
throw new IllegalArgumentException(KEY_LENGTH_BASE64_EXCEPTION_MESSAGE);
int i, ret = 0;
int i;
int ret = 0;
for (i = 0; i < KEY_LENGTH / 3; ++i) {
final int val = decodeBase64(input, i * 4);
ret |= val >>> 31;
@@ -94,25 +95,31 @@ public final class KeyEncoding {
int ret = 0;
for (int i = 0; i < KEY_LENGTH_HEX; i += 2) {
int c, c_num, c_num0, c_alpha, c_alpha0, c_val, c_acc;
int c;
int cNum;
int cNum0;
int cAlpha;
int cAlpha0;
int cVal;
final int cAcc;
c = input[i];
c_num = c ^ 48;
c_num0 = ((c_num - 10) >>> 8) & 0xff;
c_alpha = (c & ~32) - 55;
c_alpha0 = (((c_alpha - 10) ^ (c_alpha - 16)) >>> 8) & 0xff;
ret |= ((c_num0 | c_alpha0) - 1) >>> 8;
c_val = (c_num0 & c_num) | (c_alpha0 & c_alpha);
c_acc = c_val * 16;
cNum = c ^ 48;
cNum0 = ((cNum - 10) >>> 8) & 0xff;
cAlpha = (c & ~32) - 55;
cAlpha0 = (((cAlpha - 10) ^ (cAlpha - 16)) >>> 8) & 0xff;
ret |= ((cNum0 | cAlpha0) - 1) >>> 8;
cVal = (cNum0 & cNum) | (cAlpha0 & cAlpha);
cAcc = cVal * 16;
c = input[i + 1];
c_num = c ^ 48;
c_num0 = ((c_num - 10) >>> 8) & 0xff;
c_alpha = (c & ~32) - 55;
c_alpha0 = (((c_alpha - 10) ^ (c_alpha - 16)) >>> 8) & 0xff;
ret |= ((c_num0 | c_alpha0) - 1) >>> 8;
c_val = (c_num0 & c_num) | (c_alpha0 & c_alpha);
key[i / 2] = (byte) (c_acc | c_val);
cNum = c ^ 48;
cNum0 = ((cNum - 10) >>> 8) & 0xff;
cAlpha = (c & ~32) - 55;
cAlpha0 = (((cAlpha - 10) ^ (cAlpha - 16)) >>> 8) & 0xff;
ret |= ((cNum0 | cAlpha0) - 1) >>> 8;
cVal = (cNum0 & cNum) | (cAlpha0 & cAlpha);
key[i / 2] = (byte) (cAcc | cVal);
}
if (ret != 0)
throw new IllegalArgumentException(KEY_LENGTH_HEX_EXCEPTION_MESSAGE);
+1 -1
View File
@@ -5,5 +5,5 @@
android:viewportWidth="24">
<path
android:fillColor="?android:attr/colorForeground"
android:pathData="M19.43,12.98c0.04,-0.32 0.07,-0.64 0.07,-0.98s-0.03,-0.66 -0.07,-0.98l2.11,-1.65c0.19,-0.15 0.24,-0.42 0.12,-0.64l-2,-3.46c-0.12,-0.22 -0.39,-0.3 -0.61,-0.22l-2.49,1c-0.52,-0.4 -1.08,-0.73 -1.69,-0.98l-0.38,-2.65C14.46,2.18 14.25,2 14,2h-4c-0.25,0 -0.46,0.18 -0.49,0.42l-0.38,2.65c-0.61,0.25 -1.17,0.59 -1.69,0.98l-2.49,-1c-0.23,-0.09 -0.49,0 -0.61,0.22l-2,3.46c-0.13,0.22 -0.07,0.49 0.12,0.64l2.11,1.65c-0.04,0.32 -0.07,0.65 -0.07,0.98s0.03,0.66 0.07,0.98l-2.11,1.65c-0.19,0.15 -0.24,0.42 -0.12,0.64l2,3.46c0.12,0.22 0.39,0.3 0.61,0.22l2.49,-1c0.52,0.4 1.08,0.73 1.69,0.98l0.38,2.65c0.03,0.24 0.24,0.42 0.49,0.42h4c0.25,0 0.46,-0.18 0.49,-0.42l0.38,-2.65c0.61,-0.25 1.17,-0.59 1.69,-0.98l2.49,1c0.23,0.09 0.49,0 0.61,-0.22l2,-3.46c0.12,-0.22 0.07,-0.49 -0.12,-0.64l-2.11,-1.65zM12,15.5c-1.93,0 -3.5,-1.57 -3.5,-3.5s1.57,-3.5 3.5,-3.5 3.5,1.57 3.5,3.5 -1.57,3.5 -3.5,3.5z" />
android:pathData="M12,8c1.1,0 2,-0.9 2,-2s-0.9,-2 -2,-2 -2,0.9 -2,2 0.9,2 2,2zM12,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2zM12,16c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2z"/>
</vector>
+2 -1
View File
@@ -6,5 +6,6 @@
android:alphabeticShortcut="s"
android:icon="@drawable/ic_settings"
android:title="@string/settings"
app:showAsAction="never" />
app:showAsAction="always"
android:orderInCategory="1000" />
</menu>
+18 -9
View File
@@ -39,9 +39,6 @@
<string name="error_down">Error bringing down tunnel: %s</string>
<string name="error_root">Please obtain root access and try again</string>
<string name="error_up">Error bringing up tunnel: %s</string>
<string name="export_error">Unable to export tunnels: %s</string>
<string name="export_success">Saved to %s</string>
<string name="export_summary">Zip file will be saved to downloads folder</string>
<string name="generate">Generate</string>
<string name="hint_automatic">(auto)</string>
<string name="hint_generated">(generated)</string>
@@ -51,9 +48,15 @@
<string name="import_success">Imported “%s”</string>
<string name="interface_title">Interface</string>
<string name="listen_port">Listen port</string>
<string name="log_exporter_title">Export log file</string>
<string name="log_export_error">Unable to export log: %s</string>
<string name="log_export_success">Saved to %s</string>
<string name="log_export_summary">Log file will be saved to downloads folder</string>
<string name="mtu">MTU</string>
<string name="name">Name</string>
<string name="peer">Peer</string>
<string name="permission_label">control WireGuard tunnels</string>
<string name="permission_description">Allows an app to control WireGuard tunnels. Apps with this permission may enable and disable WireGuard tunnels at will, potentially misdirecting Internet traffic.</string>
<string name="persistent_keepalive">Persistent keepalive</string>
<string name="pre_shared_key">Pre-shared key</string>
<string name="private_key">Private key</string>
@@ -66,17 +69,23 @@
<string name="toggle_error">Error toggling WireGuard tunnel: %s</string>
<string name="tools_installer_already">wg and wg-quick are already installed</string>
<string name="tools_installer_failure">Unable to install command-line tools (no root?)</string>
<string name="tools_installer_initial">Install optional tools for scripting into the system partition</string>
<string name="tools_installer_success">wg and wg-quick installed into the system partition</string>
<string name="tools_installer_initial">Install optional tools for scripting</string>
<string name="tools_installer_working">Installing wg and wg-quick</string>
<string name="tools_installer_initial_system">Install optional tools for scripting into the system partition</string>
<string name="tools_installer_initial_magisk">Install optional tools for scripting as Magisk module</string>
<string name="tools_installer_success_system">wg and wg-quick installed into the system partition</string>
<string name="tools_installer_success_magisk">wg and wg-quick installed as a Magisk module (reboot required)</string>
<string name="tools_installer_title">Install command line tools</string>
<string name="tools_installer_working">Installing wg and wg-quick into the system partition</string>
<string name="tunnel_create_error">Unable to create tunnel: %s</string>
<string name="tunnel_create_success">Successfully created tunnel “%s”</string>
<string name="tunnel_rename_error">Unable to rename tunnel: %s</string>
<string name="tunnel_rename_success">Successfully renamed tunnel to “%s”</string>
<string name="version_title">WireGuard for Android v%s"</string>
<string name="version_kernel_summary">Using kernel module implementation v%s</string>
<string name="version_kernel_unknown_summary">Using unknown kernel module implementation</string>
<string name="version_userspace_summary">Using Go userspace implementation v%s</string>
<string name="version_summary">%s backend v%s</string>
<string name="version_summary_checking">Checking %s backend version</string>
<string name="version_summary_unknown">Unknown %s version</string>
<string name="zip_exporter_title">Export tunnels to zip file</string>
<string name="zip_export_error">Unable to export tunnels: %s</string>
<string name="zip_export_success">Saved to %s</string>
<string name="zip_export_summary">Zip file will be saved to downloads folder</string>
</resources>
+1 -1
View File
@@ -9,7 +9,7 @@
<item name="preferenceTheme">@style/PreferenceThemeOverlay.v14.Material</item>
</style>
<style name="fab_label" parent="android:TextAppearance.DeviceDefault.Inverse">
<style name="fab_label" parent="TextAppearance.AppCompat.Inverse">
<item name="android:background">@drawable/fab_label_background</item>
<item name="android:textColor">@color/fab_label_text_color</item>
</style>
+3 -2
View File
@@ -1,17 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<com.wireguard.android.preference.VersionPreference android:icon="@mipmap/ic_launcher" />
<CheckBoxPreference
android:defaultValue="false"
android:key="restore_on_boot"
android:summary="@string/restore_on_boot_summary"
android:title="@string/restore_on_boot_title" />
<com.wireguard.android.preference.ToolsInstallerPreference android:key="tools_installer" />
<com.wireguard.android.preference.ZipExporterPreference android:key="zip_exporter" />
<com.wireguard.android.preference.ZipExporterPreference />
<com.wireguard.android.preference.LogExporterPreference />
<CheckBoxPreference
android:defaultValue="false"
android:key="dark_theme"
android:summaryOn="@string/dark_theme_summary_on"
android:summaryOff="@string/dark_theme_summary_off"
android:title="@string/dark_theme_title" />
<com.wireguard.android.preference.VersionPreference />
</PreferenceScreen>
+3 -3
View File
@@ -29,7 +29,7 @@ GOBUILDVERSION_NEEDED := go version go$(GOBUILDVERSION) $(GOBUILDOS)/$(GOBUILDAR
GOBUILDVERSION_CURRENT := $(shell go version 2>/dev/null)
ifeq ($(GOBUILDVERSION_NEEDED),$(GOBUILDVERSION_CURRENT))
$(info Using system go)
$(info Using system Go)
else
export GOROOT := $(CURDIR)/goroot
export PATH := $(GOROOT)/bin:$(PATH)
@@ -41,18 +41,18 @@ $(GOROOT)/bin/go:
rm -rf "$(GOROOT)"
mkdir -p "$(GOROOT)"
curl "$(GOBUILDTARBALL)" | tar -C "$(GOROOT)" --strip-components=1 -xzf - || { rm -rf "$(GOROOT)"; exit 1; }
patch -p1 -f -N -r- -d"$(GOROOT)" < goruntime-boottime-over-monotonic.diff || { rm -rf "$(GOROOT)"; exit 1; }
patch -p1 -f -N -r- -d "$(GOROOT)" < goruntime-boottime-over-monotonic.diff || { rm -rf "$(GOROOT)"; exit 1; }
$(DESTDIR)/libwg-go.so: $(GOROOT)/bin/go
endif
$(shell test "$$(cat .gobuildversion 2>/dev/null)" = "$(GOBUILDVERSION_CURRENT)" || rm -f "$(DESTDIR)/libwg-go.so")
$(DESTDIR)/libwg-go.so: $(FILES) src/git.zx2c4.com/wireguard-go/api-android.go src/git.zx2c4.com/wireguard-go/tun/api-android.go src/git.zx2c4.com/wireguard-go/jni.c
@goroot="$$(go env GOROOT)" || exit 1; patch -p1 -f -R -s --dry-run -d "$$goroot" < goruntime-boottime-over-monotonic.diff >/dev/null 2>&1 || { echo "ERROR: Your system's Go is not patched to use the suspend-aware monotonic clock. Please try again after having run: \`patch -p1 -d \"$$goroot\" < \"$(CURDIR)/goruntime-boottime-over-monotonic.diff\"\`."; exit 1; }
find . -name '*.go' -type l -delete
find . -type d -empty -delete
mkdir -p $(subst ../wireguard-go/,./src/git.zx2c4.com/wireguard-go/,$(dir $(FILES)))
$(foreach FILE,$(FILES),ln -sfrt $(subst ../wireguard-go/,./src/git.zx2c4.com/wireguard-go/,$(dir $(FILE))) $(FILE);)
patch -p1 -f -R -s --dry-run -d"$$(go env GOROOT)" < goruntime-boottime-over-monotonic.diff
GOPATH=$(PWD) go get -v -d git.zx2c4.com/wireguard-go
GOPATH=$(PWD) go build -v -o $(DESTDIR)/libwg-go.so -buildmode c-shared git.zx2c4.com/wireguard-go
go version > .gobuildversion
@@ -161,8 +161,8 @@ func wgGetSocketV6(tunnelHandle int32) int32 {
}
//export wgVersion
func wgVersion() string {
return WireGuardGoVersion
func wgVersion() *C.char {
return C.CString(WireGuardGoVersion)
}
func main() {}
@@ -12,7 +12,7 @@ extern int wgTurnOn(struct go_string ifname, int tun_fd, struct go_string settin
extern void wgTurnOff(int handle);
extern int wgGetSocketV4(int handle);
extern int wgGetSocketV6(int handle);
extern struct go_string wgVersion();
extern char *wgVersion();
JNIEXPORT jint JNICALL Java_com_wireguard_android_backend_GoBackend_wgTurnOn(JNIEnv *env, jclass c, jstring ifname, jint tun_fd, jstring settings)
{
@@ -49,14 +49,11 @@ JNIEXPORT jint JNICALL Java_com_wireguard_android_backend_GoBackend_wgGetSocketV
JNIEXPORT jstring JNICALL Java_com_wireguard_android_backend_GoBackend_wgVersion(JNIEnv *env, jclass c)
{
struct go_string s = wgVersion();
char *cstr = malloc(s.n + 1);
if (!cstr)
return NULL;
jstring ret;
memcpy(cstr, s.str, s.n);
cstr[s.n] = '\0';
ret = (*env)->NewStringUTF(env, cstr);
free(cstr);
char *version = wgVersion();
if (!version)
return NULL;
ret = (*env)->NewStringUTF(env, version);
free(version);
return ret;
}