aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/fil/libre/repwifiapp
diff options
context:
space:
mode:
Diffstat (limited to 'app/src/fil/libre/repwifiapp')
-rw-r--r--app/src/fil/libre/repwifiapp/ActivityLauncher.java46
-rw-r--r--app/src/fil/libre/repwifiapp/Commons.java134
-rw-r--r--app/src/fil/libre/repwifiapp/RepWifiIntentReceiver.java3
-rw-r--r--app/src/fil/libre/repwifiapp/activities/InputPasswordActivity.java4
-rw-r--r--app/src/fil/libre/repwifiapp/activities/InputSsidActivity.java4
-rw-r--r--app/src/fil/libre/repwifiapp/activities/Ipv4SettingsActivity.java181
-rw-r--r--app/src/fil/libre/repwifiapp/activities/LongTaskActivity.java37
-rw-r--r--app/src/fil/libre/repwifiapp/activities/MainActivity.java67
-rw-r--r--app/src/fil/libre/repwifiapp/activities/MenuEnabledActivity.java88
-rw-r--r--app/src/fil/libre/repwifiapp/activities/NetworkDetailsActivity.java20
-rw-r--r--app/src/fil/libre/repwifiapp/activities/SelectNetworkActivity.java10
-rw-r--r--app/src/fil/libre/repwifiapp/activities/SettingsActivity.java43
-rw-r--r--app/src/fil/libre/repwifiapp/activities/ShowStatusActivity.java183
-rw-r--r--app/src/fil/libre/repwifiapp/activities/VpnSettingsActivity.java201
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/AccessPointInfo.java173
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/ConnectionStatus.java8
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/DhcpSettings.java205
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/Engine.java415
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/Engine6p0.java249
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/IEngine.java8
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/NetworkManager.java170
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/OpenVpnManager.java237
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/RootCommand.java68
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/ShellCommand.java23
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/Utils.java231
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/WpaCli.java263
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/WpaSupplicant.java65
27 files changed, 2291 insertions, 845 deletions
diff --git a/app/src/fil/libre/repwifiapp/ActivityLauncher.java b/app/src/fil/libre/repwifiapp/ActivityLauncher.java
index 00a8d50..5e9c31d 100644
--- a/app/src/fil/libre/repwifiapp/ActivityLauncher.java
+++ b/app/src/fil/libre/repwifiapp/ActivityLauncher.java
@@ -1,3 +1,23 @@
+//
+// Copyright 2017 Filippo "Fil" Bergamo <fil.bergamo@riseup.net>
+//
+// This file is part of RepWifiApp.
+//
+// RepWifiApp is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// RepWifiApp is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with RepWifiApp. If not, see <http://www.gnu.org/licenses/>.
+//
+// ********************************************************************
+
package fil.libre.repwifiapp;
import android.app.Activity;
@@ -5,10 +25,12 @@ import android.content.Intent;
import android.widget.Toast;
import fil.libre.repwifiapp.activities.InputPasswordActivity;
import fil.libre.repwifiapp.activities.InputSsidActivity;
+import fil.libre.repwifiapp.activities.Ipv4SettingsActivity;
import fil.libre.repwifiapp.activities.LongTaskActivity;
import fil.libre.repwifiapp.activities.NetworkDetailsActivity;
import fil.libre.repwifiapp.activities.SelectNetworkActivity;
import fil.libre.repwifiapp.activities.ShowStatusActivity;
+import fil.libre.repwifiapp.activities.VpnSettingsActivity;
import fil.libre.repwifiapp.helpers.AccessPointInfo;
import fil.libre.repwifiapp.helpers.ConnectionStatus;
import fil.libre.repwifiapp.helpers.NetworkManager;
@@ -39,6 +61,7 @@ public class ActivityLauncher {
public static final int CONNECT_HIDDEN = 10;
public static final int USB_ATTACHED = 11;
public static final int USB_DETACHED = 12;
+ public static final int VPN_PERMISSION = 13;
}
@@ -59,7 +82,7 @@ public class ActivityLauncher {
}
public void launchLongTaskActivityConnect(AccessPointInfo info) {
-
+
Intent intent = new Intent(currentContext, LongTaskActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.putExtra(ActivityLauncher.EXTRA_REQCODE, RequestCode.CONNECT);
@@ -102,7 +125,7 @@ public class ActivityLauncher {
nets = manager.getKnownNetworks();
if (nets == null || nets.length == 0) {
- Toast toast = Toast.makeText(currentContext, "No saved network", Toast.LENGTH_LONG);
+ Toast toast = Toast.makeText(currentContext, Commons.msgNoSavedNetwork, Toast.LENGTH_LONG);
toast.show();
return;
}
@@ -130,6 +153,24 @@ public class ActivityLauncher {
currentContext.startActivityForResult(intent, RequestCode.DETAILS_SHOW);
}
+
+ public void launchIpSettingsActivity(AccessPointInfo info) {
+
+ Intent intent = new Intent(currentContext, Ipv4SettingsActivity.class);
+ // intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
+ intent.putExtra(EXTRA_APINFO, info);
+ currentContext.startActivity(intent);
+
+ }
+
+ public void launchVpnSettingsActivity(AccessPointInfo info) {
+
+ Intent intent = new Intent(currentContext, VpnSettingsActivity.class);
+ // intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
+ intent.putExtra(EXTRA_APINFO, info);
+ currentContext.startActivity(intent);
+
+ }
public void launchInputSsidActivity() {
@@ -139,5 +180,6 @@ public class ActivityLauncher {
currentContext.startActivityForResult(intent, RequestCode.CONNECT_HIDDEN);
}
+
}
diff --git a/app/src/fil/libre/repwifiapp/Commons.java b/app/src/fil/libre/repwifiapp/Commons.java
index 200381f..1603a76 100644
--- a/app/src/fil/libre/repwifiapp/Commons.java
+++ b/app/src/fil/libre/repwifiapp/Commons.java
@@ -20,6 +20,12 @@
package fil.libre.repwifiapp;
+import java.io.File;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Locale;
+import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
@@ -30,39 +36,33 @@ import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
+import android.os.Environment;
import android.preference.PreferenceManager;
import fil.libre.repwifiapp.activities.MainActivity;
import fil.libre.repwifiapp.helpers.ConnectionStatus;
+import fil.libre.repwifiapp.helpers.Engine;
import fil.libre.repwifiapp.helpers.Engine6p0;
import fil.libre.repwifiapp.helpers.IEngine;
import fil.libre.repwifiapp.helpers.NetworkManager;
import fil.libre.repwifiapp.helpers.Utils;
+import fil.libre.repwifiapp.helpers.WpaCli;
+import fil.libre.repwifiapp.helpers.WpaSupplicant;
public abstract class Commons {
private static Context currentContext;
- public Context getContext() {
+ public static Context getContext() {
return currentContext;
}
- // ------------- Enviromnet Constants -----------------
+ // ------------- Environment Constants -----------------
public static final int EXCOD_ROOT_DISABLED = 255;
public static final int EXCOD_ROOT_DENIED = 1;
public static final int WAIT_ON_USB_ATTACHED = 1500;
+ public static final int WAIT_FOR_GATEWAY = 4000;
public static final String BSSID_NOT_AVAILABLE = "[BSSID-NOT-AVAILABLE]";
- public static final String v4p2 = "4.2";
public static final String v6p0 = "6.0";
- public static final String SCAN_FILE_HDR = "bssid / frequency / signal level / flags / ssid";
- public static final String INTERFACE_NAME = "wlan0";
- public static final String WORKDIR = "/data/misc/wifi";
- public static final String PID_FILE = WORKDIR + "/pidfile";
- public static final String SOCKET_DIR = WORKDIR + "/sockets/";
- public static final String SOFTAP_FILE = WORKDIR + "/softap.conf";
- public static final String P2P_CONF = WORKDIR + "/p2p_supplicant.conf";
- public static final String WPA_CONF = WORKDIR + "/wpa_supplicant.conf";
- public static final String ENTROPY_FILE = WORKDIR + "/entropy.bin";
- public static final String OVERLAY_FILE = "/system/etc/wifi/wpa_supplicant_overlay.conf";
// ---------------------------------------------
// ------------- Shared Engines -----------------------
@@ -76,12 +76,45 @@ public abstract class Commons {
public static int colorBlack;
public static String dns1Default = "";
public static String dns2Default = "";
+ private static String APP_DATA_FOLDER;
+ public static String msgNoSavedNetwork;
+
+ public static String getNetworkStorageFile() {
+ if (APP_DATA_FOLDER == null) {
+ return null;
+ } else {
+ return APP_DATA_FOLDER + "/repwifi_storage.conf";
+ }
+ }
+
+ @SuppressLint("SimpleDateFormat")
+ public static String getLogDumpFile() {
+
+ File f = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
+ if (f == null || !f.exists()) {
+ return null;
+ }
+
+ String basefolder;
+ try {
+ basefolder = f.getCanonicalPath();
+ } catch (Exception e) {
+ Utils.logError("Exception while resolving canonical path for log dump file.", e);
+ return null;
+ }
+
+ DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss", Locale.getDefault());
+ String ts = dateFormat.format(Calendar.getInstance().getTime());
+ return basefolder + "/repwifi_log_dump." + ts + ".log";
+ }
+
+ // --------------------------------------------------------
private static final int NOTIFICATION_ID = 1;
public static void updateNotification(Context context) {
- ConnectionStatus status = connectionEngine.getConnectionStatus();
+ ConnectionStatus status = WpaCli.getConnectionStatus();
Notification.Builder builder = new Notification.Builder(context);
@@ -104,7 +137,7 @@ public abstract class Commons {
builder.setSmallIcon(iconId);
builder.setContentTitle(msg);
- builder.setContentText("Touch to open.");
+ builder.setContentText(currentContext.getString(R.string.msg_touch_open));
Notification n = builder.build();
n.flags |= Notification.FLAG_NO_CLEAR;
@@ -124,12 +157,13 @@ public abstract class Commons {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(context,
R.style.Theme_RepWifiDialogTheme);
dlgAlert.setMessage(msg);
- dlgAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int whichButton) {
- return;
- }
- });
+ dlgAlert.setPositiveButton(currentContext.getString(android.R.string.ok),
+ new DialogInterface.OnClickListener() {
+ @Override
+ public void onClick(DialogInterface dialog, int whichButton) {
+ return;
+ }
+ });
dlgAlert.setCancelable(false);
AlertDialog diag = dlgAlert.create();
@@ -180,9 +214,8 @@ public abstract class Commons {
if (silent) {
- if (connectionEngine != null) {
- connectionEngine.killBackEndProcesses();
- }
+ Engine.killDhcpcd();
+ WpaSupplicant.kill();
} else {
@@ -252,55 +285,6 @@ public abstract class Commons {
// ----------------------------------------------------
- // ----------------- Application Files --------------------
- private static String APP_DATA_FOLDER;
-
- public static String getNetworkStorageFile() {
- if (APP_DATA_FOLDER == null) {
- return null;
- } else {
- return APP_DATA_FOLDER + "/repwifi_storage.conf";
- }
- }
-
- public static String getTempFile() {
- return APP_DATA_FOLDER + "/file.tmp";
- }
-
- public static String getScriptScan() {
- return APP_DATA_FOLDER + "/scan_app.sh";
- }
-
- public static String getScriptScanRes() {
- return APP_DATA_FOLDER + "/get_scan_results_app.sh";
- }
-
- public static String getScriptDhcpcd() {
- return APP_DATA_FOLDER + "/run_dhcpcd.sh";
- }
-
- public static String getOldSelectScript() {
- return WORKDIR + "/select_network.sh";
- }
-
- public static String getScanFile() {
- return APP_DATA_FOLDER + "/scanres.txt";
- }
-
- public static String getStatusFile() {
- return APP_DATA_FOLDER + "/tmpStatus";
- }
-
- public static String getGwFile() {
- return APP_DATA_FOLDER + "/gw.txt";
- }
-
- public static String getTempOutFile() {
- return APP_DATA_FOLDER + "/tmpout.txt";
- }
-
- // --------------------------------------------------------
-
// ----------- Initialization methods ---------------------------
public static boolean init(Context context) {
@@ -310,6 +294,8 @@ public abstract class Commons {
colorThemeDark = currentContext.getResources().getColor(R.color.ThemeDark);
colorThemeLight = currentContext.getResources().getColor(R.color.ThemeLight);
+ msgNoSavedNetwork = currentContext.getResources().getString(
+ R.string.msg_no_saved_network);
colorBlack = currentContext.getResources().getColor(R.color.black);
APP_DATA_FOLDER = currentContext.getExternalFilesDir(null).getAbsolutePath();
dns1Default = currentContext.getResources().getString(R.string.dns1_default);
@@ -333,7 +319,7 @@ public abstract class Commons {
String vers = android.os.Build.VERSION.RELEASE;
if (!vers.startsWith(Commons.v6p0)) {
- showMessage("UNSUPPORTED OS VERSION\nThe current version of Replicant is not supported by RepWifi.\nPlease upgrade to the latest version as soon as possible!");
+ showMessage(currentContext.getString(R.string.msg_os_unsupported));
}
}
diff --git a/app/src/fil/libre/repwifiapp/RepWifiIntentReceiver.java b/app/src/fil/libre/repwifiapp/RepWifiIntentReceiver.java
index 3f507ec..ba26bb3 100644
--- a/app/src/fil/libre/repwifiapp/RepWifiIntentReceiver.java
+++ b/app/src/fil/libre/repwifiapp/RepWifiIntentReceiver.java
@@ -7,7 +7,6 @@ import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
-import android.util.Log;
public class RepWifiIntentReceiver extends BroadcastReceiver {
@@ -16,11 +15,9 @@ public class RepWifiIntentReceiver extends BroadcastReceiver {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context
.getApplicationContext());
if (!prefs.getBoolean("enable_autostart", false)) {
- Log.d("RepWifi", "autostart is false");
return;
}
- Log.d("RepWifi", "Autostart is true");
String a = intent.getAction();
if (a.equals(Intent.ACTION_BOOT_COMPLETED) || a.equals(Intent.ACTION_REBOOT)) {
diff --git a/app/src/fil/libre/repwifiapp/activities/InputPasswordActivity.java b/app/src/fil/libre/repwifiapp/activities/InputPasswordActivity.java
index 6f04d1c..32922c6 100644
--- a/app/src/fil/libre/repwifiapp/activities/InputPasswordActivity.java
+++ b/app/src/fil/libre/repwifiapp/activities/InputPasswordActivity.java
@@ -49,7 +49,7 @@ public class InputPasswordActivity extends Activity implements OnCheckedChangeLi
CheckBox c = (CheckBox) findViewById(R.id.chk_show_pass);
c.setOnCheckedChangeListener(this);
- setTitle("Input password");
+ setTitle(getResources().getString(R.string.title_input_password));
TextView v = (TextView) findViewById(R.id.txt_insert_pass);
@@ -81,7 +81,7 @@ public class InputPasswordActivity extends Activity implements OnCheckedChangeLi
String pass = txpass.getText().toString();
if (pass.length() == 0) {
- Commons.showMessage("Password can't be empty!", this);
+ Commons.showMessage(getString(R.string.msg_password_empty), this);
}
this.apinfo.setPassword(pass);
diff --git a/app/src/fil/libre/repwifiapp/activities/InputSsidActivity.java b/app/src/fil/libre/repwifiapp/activities/InputSsidActivity.java
index 4f3f74c..8b7c60c 100644
--- a/app/src/fil/libre/repwifiapp/activities/InputSsidActivity.java
+++ b/app/src/fil/libre/repwifiapp/activities/InputSsidActivity.java
@@ -39,7 +39,7 @@ public class InputSsidActivity extends Activity {
super.onCreate(icicle);
setContentView(R.layout.activity_input_ssid);
- setTitle("Insert Network's parameters");
+ setTitle(getString(R.string.title_input_ssid));
}
@@ -85,7 +85,7 @@ public class InputSsidActivity extends Activity {
String ssid = txssid.getText().toString();
if (ssid.length() == 0) {
- Commons.showMessage("Network name can't be empty!", this);
+ Commons.showMessage(getString(R.string.msg_network_name_empty), this);
return;
}
diff --git a/app/src/fil/libre/repwifiapp/activities/Ipv4SettingsActivity.java b/app/src/fil/libre/repwifiapp/activities/Ipv4SettingsActivity.java
new file mode 100644
index 0000000..1f15252
--- /dev/null
+++ b/app/src/fil/libre/repwifiapp/activities/Ipv4SettingsActivity.java
@@ -0,0 +1,181 @@
+//
+// Copyright 2017 Filippo "Fil" Bergamo <fil.bergamo@riseup.net>
+//
+// This file is part of RepWifiApp.
+//
+// RepWifiApp is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// RepWifiApp is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with RepWifiApp. If not, see <http://www.gnu.org/licenses/>.
+//
+// ********************************************************************
+
+package fil.libre.repwifiapp.activities;
+
+import fil.libre.repwifiapp.ActivityLauncher;
+import fil.libre.repwifiapp.Commons;
+import fil.libre.repwifiapp.R;
+import fil.libre.repwifiapp.helpers.AccessPointInfo;
+import fil.libre.repwifiapp.helpers.DhcpSettings;
+import android.nfc.FormatException;
+import android.os.Bundle;
+import android.app.Activity;
+import android.content.Intent;
+import android.view.Menu;
+import android.view.View;
+import android.widget.CheckBox;
+import android.widget.CompoundButton;
+import android.widget.EditText;
+import android.widget.CompoundButton.OnCheckedChangeListener;
+
+public class Ipv4SettingsActivity extends Activity implements OnCheckedChangeListener {
+
+ private AccessPointInfo currentNetwork;
+ private DhcpSettings currentSettings;
+
+ private EditText txtIp;
+ private EditText txtGw;
+ private EditText txtMask;
+ private CheckBox chkDhcp;
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_ipv4_settings);
+
+ chkDhcp = (CheckBox) findViewById(R.id.chk_use_dhcp);
+ txtIp = (EditText) findViewById(R.id.txt_static_ip);
+ txtMask = (EditText) findViewById(R.id.txt_netmask);
+ txtGw = (EditText) findViewById(R.id.txt_gateway);
+
+ chkDhcp.setOnCheckedChangeListener(this);
+
+ Intent intent = getIntent();
+ if (!intent.hasExtra(ActivityLauncher.EXTRA_APINFO)) {
+ this.setResult(RESULT_CANCELED);
+ this.finish();
+ return;
+ }
+
+ this.currentNetwork = (AccessPointInfo) intent.getExtras().getSerializable(
+ ActivityLauncher.EXTRA_APINFO);
+ if (this.currentNetwork == null) {
+ this.setResult(RESULT_CANCELED);
+ this.finish();
+ return;
+ }
+
+ this.currentNetwork = Commons.storage.getSavedNetwork(currentNetwork);
+
+ loadNetwork();
+
+ }
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ // Inflate the menu; this adds items to the action bar if it is present.
+ // getMenuInflater().inflate(R.menu.activity_manage_networks, menu);
+ return true;
+ }
+
+ private void loadNetwork() {
+
+ setTitle(this.currentNetwork.getSsid());
+ currentSettings = this.currentNetwork.getDhcpConfiguration();
+ loadSettings();
+
+ }
+
+ private void loadSettings() {
+
+ if (currentSettings.useDhcp) {
+
+ chkDhcp.setChecked(true);
+
+ txtIp.setText("");
+ txtIp.setEnabled(false);
+
+ txtMask.setText("");
+ txtMask.setEnabled(false);
+
+ txtGw.setText("");
+ txtGw.setEnabled(false);
+
+ } else {
+ chkDhcp.setChecked(false);
+
+ txtIp.setText(currentSettings.getStaticIP());
+ txtIp.setEnabled(true);
+
+ txtMask.setText(currentSettings.getSubnetMaskString());
+ txtMask.setEnabled(true);
+
+ txtGw.setText(currentSettings.getDefaultGateway());
+ txtGw.setEnabled(true);
+ }
+
+ }
+
+ @Override
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+
+ if (buttonView == findViewById(R.id.chk_use_dhcp)) {
+ currentSettings.useDhcp = isChecked;
+ loadSettings();
+
+ }
+
+ }
+
+ public void btnSaveClick(View v) throws FormatException {
+
+ if (chkDhcp.isChecked()) {
+ currentSettings.useDhcp = true;
+
+ } else {
+
+ String ip = txtIp.getText().toString();
+ String mask = txtMask.getText().toString();
+ String gw = txtGw.getText().toString();
+
+ if (!DhcpSettings.isValidAddress(ip)) {
+ Commons.showMessage(getString(R.string.msg_invalid_ip),this);
+ return;
+ }
+
+ if (!DhcpSettings.isValidMaks(mask)) {
+ Commons.showMessage(getString(R.string.msg_invalid_netmask),this);
+ return;
+ }
+
+ if (!DhcpSettings.isValidAddress(gw)) {
+ Commons.showMessage(getString(R.string.msg_invalid_gateway),this);
+ return;
+ }
+
+ currentSettings = new DhcpSettings(chkDhcp.isChecked(), ip, mask, gw);
+
+ }
+
+ currentNetwork.setDhcpConfiguration(currentSettings);
+ if (Commons.storage.save(currentNetwork)) {
+ Commons.showMessage(getString(R.string.msg_network_saved),this);
+ } else {
+ Commons.showMessage(getString(R.string.msg_network_save_fail),this);
+ }
+
+ }
+
+ public void btnBackClick(View v) {
+ finish();
+ }
+
+}
diff --git a/app/src/fil/libre/repwifiapp/activities/LongTaskActivity.java b/app/src/fil/libre/repwifiapp/activities/LongTaskActivity.java
index e0b4184..a5292d2 100644
--- a/app/src/fil/libre/repwifiapp/activities/LongTaskActivity.java
+++ b/app/src/fil/libre/repwifiapp/activities/LongTaskActivity.java
@@ -1,3 +1,24 @@
+//
+// Copyright 2017 Filippo "Fil" Bergamo <fil.bergamo@riseup.net>
+//
+// This file is part of RepWifiApp.
+//
+// RepWifiApp is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// RepWifiApp is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with RepWifiApp. If not, see <http://www.gnu.org/licenses/>.
+//
+// ********************************************************************
+
+
package fil.libre.repwifiapp.activities;
import fil.libre.repwifiapp.ActivityLauncher;
@@ -99,21 +120,21 @@ public class LongTaskActivity extends Activity {
// Extract AccessPointInfo
input = intent.getExtras().getSerializable(ActivityLauncher.EXTRA_APINFO);
currentNetwork = (AccessPointInfo) input;
- setTitle("Connecting to " + currentNetwork.getSsid() + "...");
- setMessage("Connecting to " + currentNetwork.getSsid() + "...");
+ setTitle(getString(R.string.msg_connecting_to) + " " + currentNetwork.getSsid() + "...");
+ setMessage(getString(R.string.msg_connecting_to) + " " + currentNetwork.getSsid() + "...");
break;
case ActivityLauncher.RequestCode.NETWORKS_GET:
- setTitle("Scanning...");
- setMessage("Scanning for Networks...");
+ setTitle(getString(R.string.title_scanning));
+ setMessage(getString(R.string.msg_scanning_for_nets));
case ActivityLauncher.RequestCode.STATUS_GET:
- setTitle("Checking status...");
- setMessage("Checking status...");
+ setTitle(getString(R.string.msg_checking_status));
+ setMessage(getString(R.string.msg_checking_status));
default:
- setTitle("Please wait...");
- setMessage("Please wait...");
+ setTitle(getString(R.string.msg_please_wait));
+ setMessage(getString(R.string.msg_please_wait));
break;
}
diff --git a/app/src/fil/libre/repwifiapp/activities/MainActivity.java b/app/src/fil/libre/repwifiapp/activities/MainActivity.java
index 6e667bf..7a22416 100644
--- a/app/src/fil/libre/repwifiapp/activities/MainActivity.java
+++ b/app/src/fil/libre/repwifiapp/activities/MainActivity.java
@@ -20,7 +20,6 @@
package fil.libre.repwifiapp.activities;
-import java.io.IOException;
import java.net.SocketException;
import fil.libre.repwifiapp.ActivityLauncher;
import fil.libre.repwifiapp.Commons;
@@ -29,8 +28,10 @@ import fil.libre.repwifiapp.ActivityLauncher.RequestCode;
import fil.libre.repwifiapp.helpers.AccessPointInfo;
import fil.libre.repwifiapp.helpers.ConnectionStatus;
import fil.libre.repwifiapp.helpers.NetworkManager;
+import fil.libre.repwifiapp.helpers.OpenVpnManager;
import fil.libre.repwifiapp.helpers.RootCommand;
import fil.libre.repwifiapp.helpers.Utils;
+import fil.libre.repwifiapp.helpers.WpaSupplicant;
import android.os.Bundle;
import android.content.BroadcastReceiver;
import android.content.Context;
@@ -59,8 +60,16 @@ public class MainActivity extends MenuEnabledActivity {
return;
}
+ if (! Commons.storage.updateStorageVersion()){
+ Utils.logError("Failed to convert storage file to new version!");
+ }
+
setImage();
setUsbDeviceMonitor();
+ setVersionOnTitle();
+
+ OpenVpnManager.initialize(this);
+
}
@Override
@@ -149,11 +158,6 @@ public class MainActivity extends MenuEnabledActivity {
handleFinishedConnecting(conres, i);
break;
- case RequestCode.STATUS_GET:
- ConnectionStatus status = (ConnectionStatus) intent.getExtras().getSerializable(
- ActivityLauncher.EXTRA_CONSTATUS);
- handleResultGetStatus(status);
- break;
case RequestCode.NETWORKS_GET:
AccessPointInfo[] nets = (AccessPointInfo[]) intent.getExtras().getSerializable(
@@ -182,6 +186,7 @@ public class MainActivity extends MenuEnabledActivity {
}
break;
+
default:
break;
@@ -190,6 +195,23 @@ public class MainActivity extends MenuEnabledActivity {
}
+ private void setVersionOnTitle() {
+
+ try {
+
+ String vers = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
+ if (vers == null) {
+ return;
+ }
+
+ setTitle(getTitle() + " - v." + vers);
+
+ } catch (Exception e) {
+ Utils.logError("Error while setting version on MainActivity's title.", e);
+ }
+
+ }
+
private void setImage() {
ImageView img = (ImageView) findViewById(R.id.img_logo);
@@ -197,7 +219,7 @@ public class MainActivity extends MenuEnabledActivity {
try {
Drawable d = Drawable.createFromStream(getAssets().open("repwifi-logo-0.png"), null);
img.setImageDrawable(d);
- } catch (IOException e) {
+ } catch (Exception e) {
Utils.logError("Error while loading logo image", e);
}
@@ -224,6 +246,7 @@ public class MainActivity extends MenuEnabledActivity {
}
private boolean checkConditions() {
+
return (checkRootEnabled() && checkInterface(true));
}
@@ -233,7 +256,7 @@ public class MainActivity extends MenuEnabledActivity {
String msg = "";
try {
- res = Commons.connectionEngine.isInterfaceAvailable(Commons.INTERFACE_NAME);
+ res = Commons.connectionEngine.isInterfaceAvailable(WpaSupplicant.INTERFACE_NAME);
} catch (SocketException e) {
Utils.logError("SocketException during isInterfaceAvailable()", e);
msg = "Error while retrieving interface list!";
@@ -258,7 +281,7 @@ public class MainActivity extends MenuEnabledActivity {
int excode = -1;
try {
- excode = su.execute();
+ excode = su.testRootAccess();
} catch (Exception e) {
Utils.logError("Error while trying to get first Super User access.", e);
excode = -1;
@@ -304,7 +327,7 @@ public class MainActivity extends MenuEnabledActivity {
if (i.needsPassword()) {
- // try to fetch network's password from storage
+ // try to fetch network's configuration from storage
AccessPointInfo fromStorage = Commons.storage.getSavedNetwork(i);
if (fromStorage == null) {
@@ -327,12 +350,6 @@ public class MainActivity extends MenuEnabledActivity {
launcher.launchLongTaskActivityConnect(i);
}
- private void handleResultGetStatus(ConnectionStatus status) {
- if (status != null && status.isConnected()) {
- launcher.launchStatusActivity(status);
- }
- }
-
private void handleFinishedConnecting(boolean connectionResult, AccessPointInfo info) {
if (connectionResult && info.needsPassword()) {
@@ -345,13 +362,13 @@ public class MainActivity extends MenuEnabledActivity {
// Save network
if (Commons.storage.save(info)) {
- Toast toast2 = Toast.makeText(getApplicationContext(), "Network Saved!",
- Toast.LENGTH_LONG);
+ Toast toast2 = Toast.makeText(getApplicationContext(),
+ getString(R.string.msg_network_saved), Toast.LENGTH_LONG);
toast2.show();
} else {
- Toast toast2 = Toast.makeText(getApplicationContext(), "FAILED to save network!",
- Toast.LENGTH_LONG);
+ Toast toast2 = Toast.makeText(getApplicationContext(),
+ getString(R.string.msg_network_save_fail), Toast.LENGTH_LONG);
toast2.show();
}
@@ -360,8 +377,8 @@ public class MainActivity extends MenuEnabledActivity {
} else {
// alert that connection failed
- Toast toast = Toast.makeText(getApplicationContext(), "FAILED to connect!",
- Toast.LENGTH_LONG);
+ Toast toast = Toast.makeText(getApplicationContext(),
+ getString(R.string.msg_connect_fail), Toast.LENGTH_LONG);
toast.show();
}
}
@@ -371,9 +388,9 @@ public class MainActivity extends MenuEnabledActivity {
NetworkManager manager = new NetworkManager(Commons.getNetworkStorageFile());
String msg = "";
if (manager.remove(info)) {
- msg = "Network info deleted!";
+ msg = getString(R.string.msg_netinfo_deleted);
} else {
- msg = "FAILED to delete network info!";
+ msg = getString(R.string.msg_netinfo_delete_fail);
}
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
@@ -437,7 +454,7 @@ public class MainActivity extends MenuEnabledActivity {
} catch (Exception e) {
Utils.logError("Error while autoconnecting", e);
- Commons.showMessage("An error occured while trying to auto-connect", this);
+ Commons.showMessage(getString(R.string.msg_autoconnect_error), this);
}
}
diff --git a/app/src/fil/libre/repwifiapp/activities/MenuEnabledActivity.java b/app/src/fil/libre/repwifiapp/activities/MenuEnabledActivity.java
index 0edfcf0..f5c8516 100644
--- a/app/src/fil/libre/repwifiapp/activities/MenuEnabledActivity.java
+++ b/app/src/fil/libre/repwifiapp/activities/MenuEnabledActivity.java
@@ -1,20 +1,60 @@
+//
+// Copyright 2017 Filippo "Fil" Bergamo <fil.bergamo@riseup.net>
+//
+// This file is part of RepWifiApp.
+//
+// RepWifiApp is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// RepWifiApp is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with RepWifiApp. If not, see <http://www.gnu.org/licenses/>.
+//
+// ********************************************************************
+
package fil.libre.repwifiapp.activities;
+import java.lang.reflect.Field;
+import fil.libre.repwifiapp.Commons;
import fil.libre.repwifiapp.R;
+import fil.libre.repwifiapp.helpers.RootCommand;
import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
+import android.view.ViewConfiguration;
public class MenuEnabledActivity extends Activity {
@Override
+ protected void onCreate(android.os.Bundle savedInstanceState) {
+ try {
+ ViewConfiguration config = ViewConfiguration.get(this);
+ Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
+ if (menuKeyField != null) {
+ menuKeyField.setAccessible(true);
+ menuKeyField.setBoolean(config, false);
+ }
+ } catch (Exception ignored) {
+ }
+ super.onCreate(savedInstanceState);
+ };
+
+ @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
-
+
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
@@ -27,6 +67,10 @@ public class MenuEnabledActivity extends Activity {
case R.id.menu_config:
launchSettingsActivity();
break;
+
+ case R.id.menu_btn_closeapp:
+ CloseApplication(false);
+ break;
default:
break;
@@ -46,4 +90,46 @@ public class MenuEnabledActivity extends Activity {
// intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
}
+
+ protected void CloseApplication(boolean silent) {
+
+ if (silent) {
+
+ Commons.connectionEngine.disconnect();
+ Commons.killBackEnd(this, true);
+ super.onDestroy();
+ RootCommand.executeRootCmd("am force-stop " + getPackageName());
+
+ } else {
+
+ String msg = getString(R.string.confirm_exit_app);
+ AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this,
+ R.style.Theme_RepWifiDialogTheme);
+ dlgAlert.setMessage(msg);
+ dlgAlert.setPositiveButton(this.getString(android.R.string.ok),
+ new DialogInterface.OnClickListener() {
+ @Override
+ public void onClick(DialogInterface dialog, int whichButton) {
+ CloseApplication(true);
+ return;
+ }
+ });
+ dlgAlert.setNegativeButton(getString(android.R.string.cancel),
+ new DialogInterface.OnClickListener() {
+ @Override
+ public void onClick(DialogInterface dialog, int whichButton) {
+ return;
+ }
+ });
+
+ dlgAlert.setCancelable(false);
+ AlertDialog diag = dlgAlert.create();
+
+ diag.show();
+ return;
+
+ }
+
+ }
+
}
diff --git a/app/src/fil/libre/repwifiapp/activities/NetworkDetailsActivity.java b/app/src/fil/libre/repwifiapp/activities/NetworkDetailsActivity.java
index 325d546..f2a8944 100644
--- a/app/src/fil/libre/repwifiapp/activities/NetworkDetailsActivity.java
+++ b/app/src/fil/libre/repwifiapp/activities/NetworkDetailsActivity.java
@@ -22,6 +22,7 @@ package fil.libre.repwifiapp.activities;
import java.util.Date;
import fil.libre.repwifiapp.ActivityLauncher;
+import fil.libre.repwifiapp.Commons;
import fil.libre.repwifiapp.R;
import fil.libre.repwifiapp.helpers.AccessPointInfo;
import android.os.Bundle;
@@ -69,6 +70,12 @@ public class NetworkDetailsActivity extends Activity implements OnCheckedChangeL
}
@Override
+ protected void onStart() {
+ super.onStart();
+ currentNetwork = Commons.storage.getSavedNetwork(currentNetwork);
+ };
+
+ @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.activity_manage_networks, menu);
@@ -88,17 +95,26 @@ public class NetworkDetailsActivity extends Activity implements OnCheckedChangeL
if (lastused > 0) {
Date ts = new Date(lastused);
String formstring = "dd-MMM-yyyy kk:mm:ss";
- v.append("\nLast Used: " + DateFormat.format(formstring, ts));
+ v.append("\n" + getString(R.string.text_netinfo_last_used) + ": "
+ + DateFormat.format(formstring, ts));
}
if (showPassword) {
- v.append("\n\nPassword:\n" + this.currentNetwork.getPassword());
+ v.append("\n\n" + getString(R.string.text_password) + ":\n" + this.currentNetwork.getPassword());
} else {
v.append("\n\n\n");
}
}
+ public void btnIpSettingsClick(View v){
+ new ActivityLauncher(this).launchIpSettingsActivity(currentNetwork);
+ }
+
+ public void btnVpnSettingsClick(View v){
+ new ActivityLauncher(this).launchVpnSettingsActivity(currentNetwork);
+ }
+
public void btnDeleteClick(View v) {
String msg = getResources().getString(R.string.msg_confirm_delete_network);
diff --git a/app/src/fil/libre/repwifiapp/activities/SelectNetworkActivity.java b/app/src/fil/libre/repwifiapp/activities/SelectNetworkActivity.java
index 341fb68..51baed8 100644
--- a/app/src/fil/libre/repwifiapp/activities/SelectNetworkActivity.java
+++ b/app/src/fil/libre/repwifiapp/activities/SelectNetworkActivity.java
@@ -48,7 +48,7 @@ public class SelectNetworkActivity extends Activity implements OnClickListener {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_network);
- setTitle("Select network");
+ setTitle(getString(R.string.title_activity_select_network));
getNetworks();
@@ -135,17 +135,17 @@ public class SelectNetworkActivity extends Activity implements OnClickListener {
if (info == null) {
Utils.logError("Unable to retrieve network list!");
- writeOut("Unable to retrieve network list!");
+ writeOut(getString(R.string.msg_network_list_fail));
return;
}
if (info.length == 0) {
- writeOut("No network found.");
+ writeOut(getString(R.string.msg_no_network));
toggleBtnRescan(true);
return;
}
- writeOut("Select the network you want to connect to:");
+ writeOut(getString(R.string.msg_select_network_connect));
toggleBtnRescan(false);
for (AccessPointInfo i : info) {
@@ -162,7 +162,7 @@ public class SelectNetworkActivity extends Activity implements OnClickListener {
return;
}
- writeOut("Select network info to manage:");
+ writeOut(getString(R.string.msg_select_network_manage));
toggleBtnRescan(false);
for (AccessPointInfo i : info) {
diff --git a/app/src/fil/libre/repwifiapp/activities/SettingsActivity.java b/app/src/fil/libre/repwifiapp/activities/SettingsActivity.java
index 6f14748..36e0e1f 100644
--- a/app/src/fil/libre/repwifiapp/activities/SettingsActivity.java
+++ b/app/src/fil/libre/repwifiapp/activities/SettingsActivity.java
@@ -1,9 +1,31 @@
+//
+// Copyright 2017 Filippo "Fil" Bergamo <fil.bergamo@riseup.net>
+//
+// This file is part of RepWifiApp.
+//
+// RepWifiApp is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// RepWifiApp is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with RepWifiApp. If not, see <http://www.gnu.org/licenses/>.
+//
+// ********************************************************************
+
+
package fil.libre.repwifiapp.activities;
import org.apache.http.conn.util.InetAddressUtils;
import java.util.List;
import fil.libre.repwifiapp.Commons;
import fil.libre.repwifiapp.R;
+import fil.libre.repwifiapp.helpers.Utils;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
@@ -31,6 +53,7 @@ public class SettingsActivity extends PreferenceActivity {
addPreferencesFromResource(R.xml.debug_settings);
setConfirmKillBackend();
+ setDumpFileClick();
}
@@ -48,6 +71,24 @@ public class SettingsActivity extends PreferenceActivity {
}
+ private void setDumpFileClick() {
+ Preference pref = getPreferenceScreen().findPreference("pref_dump_log");
+ pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
+
+ @Override
+ public boolean onPreferenceClick(Preference p) {
+ if (Utils.dumpLogcatToFile(Commons.getLogDumpFile())) {
+ Commons.showMessage(getString(R.string.msg_log_saved) + ": \n" + Commons.getLogDumpFile(),
+ getActivity());
+
+ } else {
+ Commons.showMessage(getString(R.string.msg_log_save_fail), getActivity());
+ }
+ return true;
+ }
+ });
+ }
+
}
public static class GeneralSettingFragment extends PreferenceFragment {
@@ -76,7 +117,7 @@ public class SettingsActivity extends PreferenceActivity {
|| InetAddressUtils.isIPv4Address((String) newValue)) {
return true;
} else {
- Commons.showMessage("ERROR:\nWrong IP format!", getActivity());
+ Commons.showMessage(getString(R.string.msg_error_ip_format), getActivity());
return false;
}
}
diff --git a/app/src/fil/libre/repwifiapp/activities/ShowStatusActivity.java b/app/src/fil/libre/repwifiapp/activities/ShowStatusActivity.java
index 0fb8992..21bfc4c 100644
--- a/app/src/fil/libre/repwifiapp/activities/ShowStatusActivity.java
+++ b/app/src/fil/libre/repwifiapp/activities/ShowStatusActivity.java
@@ -23,9 +23,14 @@ package fil.libre.repwifiapp.activities;
import fil.libre.repwifiapp.ActivityLauncher;
import fil.libre.repwifiapp.Commons;
import fil.libre.repwifiapp.R;
+import fil.libre.repwifiapp.ActivityLauncher.RequestCode;
+import fil.libre.repwifiapp.helpers.AccessPointInfo;
import fil.libre.repwifiapp.helpers.ConnectionStatus;
+import fil.libre.repwifiapp.helpers.OpenVpnManager;
import fil.libre.repwifiapp.helpers.Utils;
+import android.content.Intent;
import android.os.Bundle;
+import android.os.RemoteException;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
@@ -35,6 +40,8 @@ public class ShowStatusActivity extends MenuEnabledActivity {
private ConnectionStatus status;
+ // private AccessPointInfo info;
+
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -45,14 +52,45 @@ public class ShowStatusActivity extends MenuEnabledActivity {
ActivityLauncher.EXTRA_CONSTATUS);
}
- showStatus(false);
+ try {
+ showStatus(false);
+ } catch (Exception e) {
+ Utils.logError("Exception on showStatus", e);
+ }
}
@Override
public void onRestart() {
super.onRestart();
- showStatus(true);
+ try {
+ showStatus(true);
+ } catch (Exception e) {
+ Utils.logError("Exception on showStatus", e);
+ }
+ }
+
+ @Override
+ public void onActivityResult(int requestCode, int resultCode, Intent intent) {
+
+ switch (requestCode) {
+
+ case RequestCode.VPN_PERMISSION:
+
+ if (resultCode == RESULT_OK) {
+ endLaunchVpn(true);
+ } else {
+ endLaunchVpn(false);
+ }
+
+ break;
+
+ default:
+
+ break;
+
+ }
+
}
private void setMessage(String msg) {
@@ -60,7 +98,7 @@ public class ShowStatusActivity extends MenuEnabledActivity {
view.setText(msg);
}
- private void showStatus(boolean refresh) {
+ private void showStatus(boolean refresh) throws Exception {
if (refresh || status == null) {
this.status = Commons.connectionEngine.getConnectionStatus();
@@ -71,12 +109,14 @@ public class ShowStatusActivity extends MenuEnabledActivity {
} else if (this.status.isConnected()) {
Utils.logDebug("StatusActivity isConnected,showing buttons");
- setMessage("Connected to " + status.SSID + "\n\n" + "IP Address: " + status.IP + "\n");
+ setMessage(getString(R.string.msg_connected_to) + " " + status.SSID + "\n\n"
+ + getString(R.string.text_ip_address) + ": " + status.IP + "\n");
toggleBtnDisconnect(true);
-
+ beginLauncVpn();
+
} else {
Utils.logDebug("StatusActivity status Else");
- setMessage("Status:\n" + status.status);
+ setMessage(getString(R.string.text_status) + ":\n" + status.status);
toggleBtnDisconnect(false);
}
@@ -103,21 +143,144 @@ public class ShowStatusActivity extends MenuEnabledActivity {
public void onBtnDisconnectClick(View v) {
+ disconnectVpn();
+
boolean res = Commons.connectionEngine.disconnect();
String msg = "";
if (res) {
- msg = "Disconnected.";
+ msg = getString(R.string.msg_disconnected);
} else {
- msg = "FAILED to disconnect!";
+ msg = getString(R.string.msg_disconnect_fail);
}
Toast toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT);
toast.show();
- showStatus(true);
+ try {
+ showStatus(true);
+ } catch (Exception e) {
+ Utils.logError("Exception on showStatus", e);
+ }
+
+ }
+
+ private void disconnectVpn() {
+
+ if (! OpenVpnManager.isVpnConnected()){
+ return;
+ }
+
+ if (OpenVpnManager.disconnect()) {
+ Toast t = Toast.makeText(this, getString(R.string.msg_vpn_disconnect),
+ Toast.LENGTH_LONG);
+ t.show();
+
+ } else {
+ Commons.showMessage(getString(R.string.msg_vpn_disconnect_error), this);
+ }
+
+ }
+
+ private void beginLauncVpn() throws Exception {
+
+ if (OpenVpnManager.isVpnConnected()){
+ // already connected;
+ return;
+ }
+
+ if (!OpenVpnManager.isExternalAppInstalled(this)) {
+ Utils.logDebug("External VPN app not installed.");
+ return;
+ }
+
+ if (getVpnNameIfAny() == null){
+ Utils.logDebug("No vpn profile set. Exiting beginLaunchVpn()");
+ return;
+ }
+
+ // first, we make sure we have permission to use the vpn service.
+ Intent pi;
+
+ try {
+ pi = OpenVpnManager.askApiPermissionsGetIntent();
+ } catch (RemoteException e) {
+ Utils.logError("Exception while asking for VPN permission", e);
+ Toast t = Toast.makeText(getApplicationContext(), getString(R.string.msg_vpn_connect_error), Toast.LENGTH_LONG);
+ t.show();
+ return;
+
+ }
+
+ if (pi == null){
+ // no need to ask for permission
+ Utils.logDebug("No need for vpn permission: going to endLaunchVpn.");
+ endLaunchVpn(true);
+
+ } else{
+ // launch the intent to ask permission
+ Utils.logDebug("Need to ask for vpn permission. Starting intent..");
+ startActivityForResult(pi, ActivityLauncher.RequestCode.VPN_PERMISSION);
+ }
}
+ private void endLaunchVpn(boolean permissionGranted) {
+
+ try {
+
+ if (!permissionGranted) {
+ // warn user that permission must be granted
+ Utils.logDebug("User rejected vpn permission.");
+ String msg = getString(R.string.msg_vpn_no_permission).replace(
+ OpenVpnManager.PLACEHOLDER_APPNAME, OpenVpnManager.APP_COMMON_NAME);
+ Commons.showMessage(msg, this);
+ return;
+ }
+
+ String profname = getVpnNameIfAny();
+
+ // check if profile exists
+ String profUuid = OpenVpnManager.getUuidFromName(profname);
+ if (profUuid == null){
+ // warn user that selected profile doesn't exist
+ Commons.showMessage(getString(R.string.msg_vpn_wrong_profile), this);
+ return;
+ }
+
+ if (OpenVpnManager.startVpn(profUuid)){
+ Toast t = Toast.makeText(this, getString(R.string.msg_vpn_launched), Toast.LENGTH_LONG);
+ t.show();
+ } else {
+ Commons.showMessage(getString(R.string.msg_vpn_connect_error),this);
+ }
+
+ } catch (Exception e) {
+ Utils.logError("Exception while endLaunchVpn", e);
+
+ }
+
+ }
+
+ private String getVpnNameIfAny(){
+
+ if (status == null) {
+ return null;
+ }
+
+ AccessPointInfo i = status.getNetworkDetails();
+ if (i == null) {
+ return null;
+ }
+
+ String profname = i.getVpnProfileName();
+ if (profname == null || profname.isEmpty()) {
+ return null;
+ } else {
+ return profname;
+ }
+
+ }
+
public void onBtnMainClick(View v) {
finish();
}
@@ -126,5 +289,5 @@ public class ShowStatusActivity extends MenuEnabledActivity {
public void onBackPressed() {
moveTaskToBack(true);
}
-
+
}
diff --git a/app/src/fil/libre/repwifiapp/activities/VpnSettingsActivity.java b/app/src/fil/libre/repwifiapp/activities/VpnSettingsActivity.java
new file mode 100644
index 0000000..b9dab93
--- /dev/null
+++ b/app/src/fil/libre/repwifiapp/activities/VpnSettingsActivity.java
@@ -0,0 +1,201 @@
+//
+// Copyright 2017 Filippo "Fil" Bergamo <fil.bergamo@riseup.net>
+//
+// This file is part of RepWifiApp.
+//
+// RepWifiApp is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// RepWifiApp is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with RepWifiApp. If not, see <http://www.gnu.org/licenses/>.
+//
+// ********************************************************************
+
+package fil.libre.repwifiapp.activities;
+
+import java.util.List;
+import fil.libre.repwifiapp.ActivityLauncher;
+import fil.libre.repwifiapp.Commons;
+import fil.libre.repwifiapp.R;
+import fil.libre.repwifiapp.ActivityLauncher.RequestCode;
+import fil.libre.repwifiapp.helpers.AccessPointInfo;
+import fil.libre.repwifiapp.helpers.OpenVpnManager;
+import fil.libre.repwifiapp.helpers.Utils;
+import android.os.Bundle;
+import android.app.Activity;
+import android.content.Intent;
+import android.view.Menu;
+import android.view.View;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.Spinner;
+import android.widget.TextView;
+
+public class VpnSettingsActivity extends Activity {
+
+ private AccessPointInfo currentNetwork;
+ private Spinner spinProfile;
+ private TextView summaryView;
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_vpn_settings);
+
+ String title = getString(R.string.title_activity_vpn_settings);
+
+ Intent intent = getIntent();
+ if (!intent.hasExtra(ActivityLauncher.EXTRA_APINFO)) {
+ this.setResult(RESULT_CANCELED);
+ this.finish();
+ return;
+ }
+
+ this.currentNetwork = (AccessPointInfo) intent.getExtras().getSerializable(
+ ActivityLauncher.EXTRA_APINFO);
+ if (this.currentNetwork == null) {
+ this.setResult(RESULT_CANCELED);
+ this.finish();
+ return;
+ }
+
+ this.currentNetwork = Commons.storage.getSavedNetwork(currentNetwork);
+ this.spinProfile = (Spinner)findViewById(R.id.spin_vpn_profile);
+ this.summaryView = (TextView)findViewById(R.id.lbl_vpn_settings);
+ String summary = getString(R.string.summary_vpn_settings).replace(OpenVpnManager.PLACEHOLDER_APPNAME, OpenVpnManager.APP_COMMON_NAME);
+ summaryView.setText(summary);
+
+ title += " " + currentNetwork.getSsid();
+ this.setTitle(title);
+
+ if (!checkExternalApp()){
+ toggleSettingsEnabled(false);
+ } else {
+ initVpnManager();
+ }
+
+ }
+
+
+ @Override
+ public void onActivityResult(int requestCode, int resultCode, Intent intent) {
+
+ switch (requestCode) {
+
+ case RequestCode.VPN_PERMISSION:
+
+ if (resultCode != RESULT_OK) {
+ toggleSettingsEnabled(false);
+ Utils.logDebug("User rejected vpn permission.");
+ String msg = getString(R.string.msg_vpn_no_permission).replace(
+ OpenVpnManager.PLACEHOLDER_APPNAME, OpenVpnManager.APP_COMMON_NAME);
+ Commons.showMessage(msg, this);
+ return;
+ }
+
+ break;
+
+ default:
+
+ break;
+
+ }
+
+ }
+
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ return true;
+ }
+
+ private void initVpnManager(){
+
+ try {
+
+ Intent intentAllow = OpenVpnManager.askApiPermissionsGetIntent();
+ if (intentAllow != null){
+ startActivityForResult(intentAllow, ActivityLauncher.RequestCode.VPN_PERMISSION);
+ }
+
+ List<String> profiles = OpenVpnManager.getExistingProfiles();
+ if (profiles.size() == 0){
+ String msg = getString(R.string.msg_vpn_no_profile).replace(OpenVpnManager.PLACEHOLDER_APPNAME, OpenVpnManager.APP_COMMON_NAME);
+ Commons.showMessage(msg, this);
+ toggleSettingsEnabled(false);
+ return;
+ }
+ Spinner spin = (Spinner)findViewById(R.id.spin_vpn_profile);
+
+ ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,profiles);
+ adapter.insert("",0);
+ spin.setAdapter(adapter);
+ spin.setSelection(adapter.getPosition(currentNetwork.getVpnProfileName()));
+
+ } catch (Exception e) {
+ Utils.logError("Exception while creating openvpnmanager",e);
+ Commons.showMessage(getString(R.string.msg_vpn_connect_error));
+ toggleSettingsEnabled(false);
+ }
+
+ }
+
+ private boolean checkExternalApp(){
+
+ if (! OpenVpnManager.isExternalAppInstalled(this)){
+ String msg = getString(R.string.text_vpn_package_missing).replace(OpenVpnManager.PLACEHOLDER_APPNAME, OpenVpnManager.APP_COMMON_NAME);
+ Commons.showMessage(msg, this);
+ toggleSettingsEnabled(false);
+ return false;
+ } else {
+ return true;
+ }
+
+ }
+
+ private void toggleSettingsEnabled(boolean enabled){
+
+ spinProfile.setEnabled(enabled);
+
+ Button b = (Button)findViewById(R.id.btn_save_vpn_settings);
+ b.setEnabled(enabled);
+
+ }
+
+ public void btnSaveClick(View v){
+
+ String vpnProf = (String)spinProfile.getSelectedItem();
+
+ /*if (! vpnProf.isEmpty()){
+ // check if profile name exists
+ if( OpenVpnManager.getUuidFromName(vpnProf) == null){
+ Commons.showMessage(getString(R.string.msg_vpn_wrong_profile), this);
+ return;
+ }
+
+ }*/
+
+ // save profile
+ currentNetwork.setVpnProfileName(vpnProf);
+ Commons.storage.save(currentNetwork);
+
+ terminate();
+
+ }
+
+ public void btnBackClick(View v){
+ terminate();
+ }
+
+ private void terminate(){
+ finish();
+ }
+
+}
diff --git a/app/src/fil/libre/repwifiapp/helpers/AccessPointInfo.java b/app/src/fil/libre/repwifiapp/helpers/AccessPointInfo.java
index d6e2eb3..eee569d 100644
--- a/app/src/fil/libre/repwifiapp/helpers/AccessPointInfo.java
+++ b/app/src/fil/libre/repwifiapp/helpers/AccessPointInfo.java
@@ -20,25 +20,38 @@
package fil.libre.repwifiapp.helpers;
-import java.io.File;
+import org.json.JSONException;
+import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
import java.util.List;
-import fil.libre.repwifiapp.Commons;
public class AccessPointInfo implements Serializable {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 2L;
private static final int MAX_SSID_LENGTH = 32;
-
+ protected static final String SCAN_FILE_HDR = "bssid / frequency / signal level / flags / ssid";
+
+ private static final String JSONKEY_BSSID = "BSSID";
+ private static final String JSONKEY_SSID = "SSID";
+ private static final String JSONKEY_LASTUSED = "LastUsed";
+ private static final String JSONKEY_AUTH = "Auth";
+ private static final String JSONKEY_PSK = "PSK";
+ private static final String JSONKEY_VPN_PROFILE = "VpnProfile";
+ private static final String JSONKEY_DHCPSETS = "DhcpSettings";
+
private String _ssid;
private String _bssid;
private String _auth;
private String _level;
private String _freq;
private String _password;
+ private String _vpnProfileName = null;
private boolean _isHidden = false;
private long _lastTimeUsed;
+ private DhcpSettings _dhcpsets;
public AccessPointInfo(String ssid, String bssid, String authType, String level, String freq) {
@@ -50,6 +63,23 @@ public class AccessPointInfo implements Serializable {
}
+ private AccessPointInfo(){
+ // for inner use;
+ }
+
+ public void setDhcpConfiguration(DhcpSettings sets) {
+ this._dhcpsets = sets;
+ }
+
+ public DhcpSettings getDhcpConfiguration() {
+
+ if (this._dhcpsets == null) {
+ return DhcpSettings.getDefault();
+ } else {
+ return this._dhcpsets;
+ }
+ }
+
public String getSsid() {
return this._ssid;
}
@@ -78,12 +108,42 @@ public class AccessPointInfo implements Serializable {
this._bssid = bssid;
}
+ public String getVpnProfileName(){
+ if (_vpnProfileName == null){
+ return "";
+ } else {
+ return _vpnProfileName;
+ }
+ }
+
+ public void setVpnProfileName(String profileName){
+ _vpnProfileName = profileName;
+ }
+
public String getAuthType() {
+ if (_auth == null){
+ return "";
+ }
return this._auth;
}
- public String getSignlalStrength() {
- return this._level;
+ public int getSignlalStrength() {
+ // return this._level;
+
+ if (this._level == null || this._level.isEmpty()) {
+ return 0;
+ }
+
+ int retval = 0;
+
+ try {
+ retval = Integer.parseInt(this._level);
+ } catch (NumberFormatException e) {
+ retval = 0;
+ }
+
+ return retval;
+
}
public String getFrequency() {
@@ -116,6 +176,9 @@ public class AccessPointInfo implements Serializable {
}
public String getPassword() {
+ if (_password == null){
+ return "";
+ }
return this._password;
}
@@ -170,19 +233,18 @@ public class AccessPointInfo implements Serializable {
}
- public static AccessPointInfo[] parseScanResult(String scanResultFile) {
+ public static AccessPointInfo[] parseScanResult(String scanResultContent) {
try {
- Utils.logDebug("AccesPointInfo trying to parse file: " + scanResultFile);
-
- File f = new File(scanResultFile);
- if (!f.exists()) {
- Utils.logError("AccessPointInfo.parseScanResult(): The provided scan result file doesn't exist");
+ if (scanResultContent == null) {
return null;
}
- String[] lines = Utils.readFileLines(scanResultFile);
+ Utils.logDebug("AccesPointInfo trying to parse file scan content:\n"
+ + scanResultContent);
+
+ String[] lines = scanResultContent.split("\n");
List<AccessPointInfo> nets = new ArrayList<AccessPointInfo>();
if (lines == null) {
@@ -190,7 +252,7 @@ public class AccessPointInfo implements Serializable {
}
for (String l : lines) {
- if (l.startsWith(Commons.SCAN_FILE_HDR)) {
+ if (l.startsWith(SCAN_FILE_HDR)) {
// strip off the header
continue;
}
@@ -211,6 +273,8 @@ public class AccessPointInfo implements Serializable {
}
+ sortInfosBySignalStrength(nets);
+
AccessPointInfo[] a = new AccessPointInfo[nets.size()];
a = nets.toArray(a);
return a;
@@ -222,4 +286,85 @@ public class AccessPointInfo implements Serializable {
}
+ public JSONObject toJson(){
+
+ try {
+
+ JSONObject j = new JSONObject();
+
+ j.put(JSONKEY_BSSID, getBssid());
+ j.put(JSONKEY_SSID, getSsid());
+ j.put(JSONKEY_PSK, getPassword());
+ j.put(JSONKEY_AUTH, getAuthType());
+ j.put(JSONKEY_LASTUSED, getLastTimeUsed());
+ j.put(JSONKEY_VPN_PROFILE, getVpnProfileName());
+
+ DhcpSettings sets = getDhcpConfiguration();
+ if (sets != null){
+ JSONObject dhcpj = sets.toJson();
+ if (dhcpj != null){
+ j.put(JSONKEY_DHCPSETS, dhcpj);
+ }
+
+ }
+
+ return j;
+
+ } catch (JSONException e) {
+ Utils.logError("Exception while converting AccessPointInfo to JSON.", e);
+ return null;
+ }
+
+ }
+
+ public static AccessPointInfo fromJsonObject(JSONObject json){
+
+ if (json == null || json.isNull(JSONKEY_BSSID) || json.isNull(JSONKEY_SSID)){
+ return null;
+ }
+
+ AccessPointInfo info = new AccessPointInfo();
+
+ try {
+ info._bssid = json.getString(JSONKEY_BSSID);
+ info._ssid = json.getString(JSONKEY_SSID);
+ info._auth = json.getString(JSONKEY_AUTH);
+ info._lastTimeUsed = json.getLong(JSONKEY_LASTUSED);
+
+ if (json.has(JSONKEY_PSK) && ! json.isNull(JSONKEY_PSK)){
+ info._password = json.getString(JSONKEY_PSK);
+ }
+
+ if ( json.has(JSONKEY_VPN_PROFILE) && ! json.isNull(JSONKEY_VPN_PROFILE)){
+ info._vpnProfileName = json.getString(JSONKEY_VPN_PROFILE);
+ }
+
+ if (json.has(JSONKEY_DHCPSETS) && ! json.isNull(JSONKEY_DHCPSETS)){
+ info._dhcpsets = DhcpSettings.fromJsonObject(json.getJSONObject(JSONKEY_DHCPSETS));
+ }
+
+ return info;
+
+ } catch (JSONException e) {
+ Utils.logError("Exception while parsing json object to AccessPointInfo", e);
+ return null;
+ }
+
+
+
+
+ }
+
+ private static void sortInfosBySignalStrength(List<AccessPointInfo> toSort) {
+
+ Collections.sort(toSort, new Comparator<AccessPointInfo>() {
+ public int compare(AccessPointInfo o1, AccessPointInfo o2) {
+ if (o1.getSignlalStrength() == o2.getSignlalStrength())
+ return 0;
+ return o1.getSignlalStrength() < o2.getSignlalStrength() ? -1 : 1;
+ }
+ });
+
+ }
+
}
diff --git a/app/src/fil/libre/repwifiapp/helpers/ConnectionStatus.java b/app/src/fil/libre/repwifiapp/helpers/ConnectionStatus.java
index c26dae9..e271dbe 100644
--- a/app/src/fil/libre/repwifiapp/helpers/ConnectionStatus.java
+++ b/app/src/fil/libre/repwifiapp/helpers/ConnectionStatus.java
@@ -20,6 +20,7 @@
package fil.libre.repwifiapp.helpers;
+import fil.libre.repwifiapp.Commons;
import java.io.Serializable;
public class ConnectionStatus implements Serializable {
@@ -37,7 +38,7 @@ public class ConnectionStatus implements Serializable {
public String SSID;
public String BSSID;
public String IP;
-
+
private static final String F_SEP = "=";
private static final String KeyStatus = "wpa_state";
private static final String KeySSID = "ssid";
@@ -100,4 +101,9 @@ public class ConnectionStatus implements Serializable {
}
}
+ public AccessPointInfo getNetworkDetails(){
+ AccessPointInfo i = new AccessPointInfo(SSID, BSSID, "","", "");
+ return Commons.storage.getSavedNetwork(i);
+ }
+
}
diff --git a/app/src/fil/libre/repwifiapp/helpers/DhcpSettings.java b/app/src/fil/libre/repwifiapp/helpers/DhcpSettings.java
new file mode 100644
index 0000000..c0587a3
--- /dev/null
+++ b/app/src/fil/libre/repwifiapp/helpers/DhcpSettings.java
@@ -0,0 +1,205 @@
+//
+// Copyright 2017 Filippo "Fil" Bergamo <fil.bergamo@riseup.net>
+//
+// This file is part of RepWifiApp.
+//
+// RepWifiApp is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// RepWifiApp is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with RepWifiApp. If not, see <http://www.gnu.org/licenses/>.
+//
+// ********************************************************************
+
+package fil.libre.repwifiapp.helpers;
+
+import org.apache.http.conn.util.InetAddressUtils;
+import org.json.JSONException;
+import org.json.JSONObject;
+import java.io.Serializable;
+import android.nfc.FormatException;
+
+public class DhcpSettings implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+ public boolean useDhcp;
+ private String _staticIP;
+ private int _mask;
+ private String _defGw;
+
+ private static final String JSONKEY_DHCP = "DHCP";
+ private static final String JSONKEY_STATIC_IP = "StaticIP";
+ private static final String JSONKEY_GW = "Gateway";
+
+ public DhcpSettings(boolean useDhcp, String staticIP, String subnetMask, String defaultGateway)
+ throws FormatException {
+ this(useDhcp, staticIP, Utils.netmaskStringToInt(subnetMask), defaultGateway);
+ }
+
+ public DhcpSettings(boolean useDhcp, String staticIP, int subnetMask, String defaultGatweay)
+ throws FormatException {
+
+ this.useDhcp = useDhcp;
+
+ if (!useDhcp) {
+
+ if (!validateParams(staticIP, defaultGatweay, subnetMask)) {
+ throw new FormatException("Invalid dhcp parameters!");
+ }
+
+ this._staticIP = staticIP;
+ this._mask = subnetMask;
+ this._defGw = defaultGatweay;
+
+ }
+
+ }
+
+ private DhcpSettings(){
+ // inner use
+ }
+
+ public static DhcpSettings parseSavedSettings(String staticIPwithMask, String defaultGateway){
+
+ try {
+
+ String[] ipm = staticIPwithMask.split("/");
+ String ip = ipm[0];
+ int mask = Integer.parseInt(ipm[1]);
+
+ return new DhcpSettings(false, ip, mask, defaultGateway);
+
+
+ } catch (Exception e) {
+ Utils.logError("Exception while parsing DhcpSettings for saved network. Reverting to dhcp.", e);
+ return null;
+ }
+
+ }
+
+ public static DhcpSettings getDefault(){
+ try {
+ return new DhcpSettings(true, null, 24, null);
+ } catch (FormatException e) {
+ //no format exception can happen.
+ return null;
+ }
+ }
+
+ private boolean validateParams(String ip, String gateway, int mask) {
+
+ if (isValidAddress(ip) && isValidAddress(gateway) && isValidMask(mask)) {
+ return true;
+ } else {
+ return false;
+ }
+
+ }
+
+ public static boolean isValidAddress(String ipAddress){
+ return InetAddressUtils.isIPv4Address(ipAddress);
+ }
+
+ public static boolean isValidMaks(String mask){
+ int m = Utils.netmaskStringToInt(mask);
+ return isValidMask(m);
+ }
+
+ public static boolean isValidMask(int mask){
+ if (mask >= 8 && mask <= 32){
+ return true;
+ }else{
+ return false;
+ }
+ }
+
+ public String getStaticIP() {
+ if (_staticIP == null){
+ return "";
+ }
+ return _staticIP;
+ }
+
+ public String getStaticIPwithMask() {
+ return getStaticIP() + "/" + String.valueOf(getSubnetMaskInt());
+ }
+
+ public int getSubnetMaskInt() {
+ return _mask;
+ }
+
+ public String getSubnetMaskString(){
+ String v = Utils.netmaskIntToString(_mask);
+ if (v == null){
+ return "";
+ }
+ return v;
+ }
+
+ public String getDefaultGateway() {
+ if (_defGw == null){
+ return "";
+ }
+ return _defGw;
+ }
+
+ public JSONObject toJson(){
+
+ JSONObject j = new JSONObject();
+
+ try {
+ j.put(JSONKEY_DHCP, useDhcp);
+ j.put(JSONKEY_GW, getDefaultGateway());
+ j.put(JSONKEY_STATIC_IP, getStaticIPwithMask());
+
+ return j;
+
+ } catch (JSONException e) {
+ Utils.logError("Exception while converting DhcpSettings to JSON.", e);
+ return null;
+ }
+
+
+ }
+
+ public static DhcpSettings fromJsonObject(JSONObject json){
+
+ if (json == null){
+ return null;
+ }
+
+ DhcpSettings sets = new DhcpSettings();
+
+ try {
+
+ sets.useDhcp = json.getBoolean(JSONKEY_DHCP);
+
+ if (json.has(JSONKEY_GW) && ! json.isNull(JSONKEY_GW)){
+ sets._defGw = json.getString(JSONKEY_GW);
+ }
+
+ if (json.has(JSONKEY_STATIC_IP) && !json.isNull(JSONKEY_STATIC_IP)){
+
+ String[] splt = json.getString(JSONKEY_STATIC_IP).split("/");
+ sets._staticIP = splt[0];
+ sets._mask = Integer.parseInt(splt[1]);
+
+ }
+
+ return sets;
+
+ } catch (Exception e) {
+ Utils.logError("Exception while parsing json object to DhcpSettings", e);
+ return null;
+ }
+
+ }
+
+}
diff --git a/app/src/fil/libre/repwifiapp/helpers/Engine.java b/app/src/fil/libre/repwifiapp/helpers/Engine.java
index 68d8745..225d993 100644
--- a/app/src/fil/libre/repwifiapp/helpers/Engine.java
+++ b/app/src/fil/libre/repwifiapp/helpers/Engine.java
@@ -22,167 +22,33 @@ package fil.libre.repwifiapp.helpers;
import java.net.NetworkInterface;
import java.net.SocketException;
-import java.util.ArrayList;
import java.util.Enumeration;
-import fil.libre.repwifiapp.Commons;
public abstract class Engine implements IEngine {
-
- protected String getCmdWpaSup() {
- return "wpa_supplicant -B -dd -i" + Commons.INTERFACE_NAME + " -C" + Commons.SOCKET_DIR
- + " -P" + Commons.PID_FILE + " -I" + Commons.OVERLAY_FILE + " -e"
- + Commons.ENTROPY_FILE;
- }
-
- protected String getCmdWpaCli() {
- return "wpa_cli -p" + Commons.SOCKET_DIR + " -P" + Commons.PID_FILE + " -i"
- + Commons.INTERFACE_NAME;
- }
-
- protected abstract String getCmdWpaStart();
-
- public boolean deleteFileIfExists(String filePath) {
-
- if (filePath == null) {
- return false;
- }
-
- if (filePath.contains("*")) {
- // it's safer to reject bulk rm'ing
- return false;
- }
-
- if (filePath.contains(" -r ")) {
- // only file rm'ing acceppted
- return false;
- }
-
- // needs root (it only gets used by the 4p2 engine, working in
- // /data/misc/wifi)
- return executeRootCmd("if [ -e \"" + filePath + "\" ]; then rm \"" + filePath + "\"; fi");
-
- }
-
- public boolean chmodFile(String filePath, String mod) {
- // needs root (chmod)
- return executeRootCmd("chmod " + mod + " \"" + filePath + "\"");
- }
-
- @Override
- public boolean killBackEndProcesses() {
-
- // needs root (for killall)
-
- Utils.logDebug("killing wpa_supplicant..:");
- if (executeRootCmd("killall -SIGINT wpa_supplicant")) {
- Utils.logDebug("Killed wpa_supplicant");
- } else {
- Utils.logDebug("Wpa_supplicant NOT killed.");
- }
-
- Utils.logDebug("killing dhcpcd..");
- if (executeRootCmd("killall -SIGINT dhcpcd")) {
- Utils.logDebug("Killed dhcpcd");
- } else {
- Utils.logDebug("dhcpcd NOT killed.");
- }
-
- return true;
-
- }
-
- @Override
- public boolean clearWorkingDir() {
-
- // needs root (to work within /data/misc/wifi)
-
- Utils.logDebug("clearWorkingDir():");
-
- if (executeRootCmd("rm -r " + Commons.SOCKET_DIR)) {
- Utils.logDebug("removed socket dir");
- }
-
- if (executeRootCmd("rm " + Commons.ENTROPY_FILE)) {
- Utils.logDebug("removed entropy file");
- }
-
- if (executeRootCmd("rm " + Commons.PID_FILE)) {
- Utils.logDebug("removed pidfile");
- }
-
- if (executeRootCmd("rm " + Commons.SOFTAP_FILE)) {
- Utils.logDebug("removed softap file");
- }
-
- if (executeRootCmd("rm " + Commons.WPA_CONF)) {
- Utils.logDebug("removed wpa conf file");
- }
-
- if (executeRootCmd("rm " + Commons.P2P_CONF)) {
- Utils.logDebug("removed p2p conf file");
- }
-
- return true;
-
- }
-
- @Override
- public boolean startWpaSupplicant() {
-
- Utils.logDebug("startWpaSupplicant():");
-
- // needs root (for wpa_supplicant)
- if (executeRootCmd(getCmdWpaSup())) {
- return true;
- } else {
- Utils.logDebug("Failed to start wpa");
- return false;
- }
-
- }
-
+
@Override
public AccessPointInfo[] getAvailableNetworks() {
Utils.logDebug("getAvailableNetworks():");
- // killPreviousConnections();
-
- // Is it really necessary???
- // seems that clearing /data/misc/wifi is NOT necessary
- // so, commented out - Fil 2017-03-24
- /*
- * if (! clearWorkingDir()){ Utils.logError("Failed clearing dir");
- * return null; }
- */
-
- if (!startWpaSupplicant()) {
+ if (!WpaSupplicant.start()) {
Utils.logError("Failed starting wpa_supplicant");
return null;
}
- if (!createScanScripts()) {
- Utils.logError("Failed creating scripts");
- return null;
- }
-
- if (!scanNetworks()) {
+ if (!WpaCli.scanNetworks()) {
Utils.logError("failed scanning networks");
return null;
}
- if (!getScanResults()) {
+ String scanRes = WpaCli.getScanResults();
+
+ if (scanRes == null) {
Utils.logError("failed getting scan results");
return null;
}
- // chmod 664 scan_file to make it readable
- /*
- * if (!chmodFile(Commons.getScanFile(), "664")){
- * Utils.logError("failed chmodding scan_file"); return null; }
- */
-
- AccessPointInfo[] a = AccessPointInfo.parseScanResult(Commons.getScanFile());
+ AccessPointInfo[] a = AccessPointInfo.parseScanResult(scanRes);
if (a == null) {
Utils.logError("Unable to parse scan file into AccessPointInfo array");
return a;
@@ -200,30 +66,8 @@ public abstract class Engine implements IEngine {
@Override
public boolean disconnect() {
- // needs root (for wpa_cli)
-
- if (!isWpaSupplicantRunning()) {
- return true;
- }
-
- try {
+ return WpaCli.disconnect();
- RootCommand su = new RootCommand(getCmdWpaCli() + " disconnect");
- if (su.execute() == 0) {
- String out = su.getOutput();
- if (out != null && out.trim().replace("\n", "").equals("OK")) {
- return true;
- } else {
- return false;
- }
- } else {
- return false;
- }
-
- } catch (Exception e) {
- Utils.logError("Error while enabling network", e);
- return false;
- }
}
/***
@@ -231,51 +75,12 @@ public abstract class Engine implements IEngine {
*/
@Override
public ConnectionStatus getConnectionStatus() {
-
- Utils.logDebug("called getConnecitonStatus()");
- if (!isWpaSupplicantRunning()) {
- // wpa_supplicant is not running.
- // unable to determin status.
- Utils.logDebug("wpa not running, cannot get connection status.");
- return null;
-
- }
-
- try {
-
- RootCommand su = new RootCommand(getCmdWpaCli() + " status");
- if (su.execute() == 0) {
- String out = su.getOutput();
- if (out == null || out.trim().equals("")) {
- return null;
- } else {
- return ConnectionStatus.parseWpaCliOutput(out);
- }
- } else {
- return null;
- }
-
- } catch (Exception e) {
- Utils.logError("Error while executing wpa_cli status", e);
- return null;
- }
-
+ return WpaCli.getConnectionStatus();
}
@Override
public boolean isInterfaceAvailable(String ifaceName) throws SocketException {
- /*
- * String[]ifaces = getAvailableInterfaces(); if(ifaces == null ||
- * ifaces.length == 0){ return false; }
- *
- * for(String name : ifaces){
- *
- * if (name.equals(ifaceName)){ return true; } }
- *
- * return false;
- */
-
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface nif = interfaces.nextElement();
@@ -288,182 +93,40 @@ public abstract class Engine implements IEngine {
}
- @Override
- public String[] getAvailableInterfaces() {
-
- try {
-
- // No need for root for "ip link"
- // tested 2017-03-24 - Fil
- ShellCommand cmd = new ShellCommand("ip link");
- if (cmd.execute() == 0) {
-
- String out = cmd.getOutput();
- if (out == null || out.contains("\n") == false) {
- Utils.logDebug("No out from ip link");
- return null;
- }
-
- ArrayList<String> list = new ArrayList<String>();
-
- String[] lines = out.split("\n");
- for (String l : lines) {
-
- String[] fields = l.split(":");
- if (fields.length != 3) {
- continue;
- }
-
- String interfName = fields[1].trim();
- list.add(interfName);
-
- }
-
- String[] retArr = new String[list.size()];
- retArr = list.toArray(retArr);
-
- return retArr;
-
- } else {
- return null;
- }
-
- } catch (Exception e) {
- Utils.logError("Error while querying ip link", e);
- return null;
- }
-
- }
-
public boolean runDhcpcd() {
-
// needs root
- return executeRootCmd("dhcpcd " + Commons.INTERFACE_NAME);
-
- }
-
+ // option -w avoids dhcpcd forking to background,
+ // in order to keep control over its exit code, and be able to wait for it.
+ // option -A avoids ARP IP checking, we use it to save some seconds in the connection process.
+ return RootCommand.executeRootCmd("dhcpcd -w -A " + WpaSupplicant.INTERFACE_NAME);
+
+ }
+
+ public boolean runDhcpcd(DhcpSettings dhcpConfig) {
+
+ if (dhcpConfig == null || dhcpConfig.useDhcp){
+ Utils.logDebug("running dhchpc without dhcp settings, reverting to dhcp");
+ return runDhcpcd();
+ }
+
+ Utils.logDebug("Running dhcpcd with custom ip settings");
+ String cmdMask = "dhcpcd -w -A -S ip_address=%s -S routers=%s %s";
+ String cmd = String.format(cmdMask,
+ dhcpConfig.getStaticIPwithMask(),
+ dhcpConfig.getDefaultGateway(),
+ WpaSupplicant.INTERFACE_NAME);
+
+ return RootCommand.executeRootCmd(cmd);
+
+ }
+
+ public static boolean killDhcpcd(){
+ return RootCommand.executeRootCmd("killall -SIGINT dhcpcd");
+ }
+
public boolean interfaceUp() {
// needs root (tested)
- return executeRootCmd("ifconfig " + Commons.INTERFACE_NAME + " up");
- }
-
- /*
- * protected boolean executeCmd(String cmd){
- *
- * try {
- *
- * ShellCommand c = new ShellCommand(cmd); if ( c.execute() == 0){ return
- * true; }else { return false; }
- *
- * } catch (Exception e) { Utils.logError("Error executing \"" + cmd +
- * "\"",e); return false; }
- *
- * }
- */
-
- protected boolean executeRootCmd(String cmd) {
-
- try {
-
- RootCommand c = new RootCommand(cmd);
- if (c.execute() == 0) {
- return true;
- } else {
- return false;
- }
-
- } catch (Exception e) {
- Utils.logError("Error executing \"" + cmd + "\"", e);
- return false;
- }
- }
-
- protected boolean isWpaSupplicantRunning() {
-
- boolean retval = false;
-
- try {
-
- RootCommand su = new RootCommand("pidof wpa_supplicant");
- if (su.execute() == 0) {
-
- if (su.getOutput().trim().equals("")) {
- retval = false;
- } else {
- retval = true;
- }
-
- } else {
- retval = false;
- }
-
- } catch (Exception e) {
- Utils.logError("Exception during isWpaSupplicantRunning()", e);
- retval = false;
- }
-
- return retval;
-
- }
-
- protected boolean scanNetworks() {
-
- // needs root (for wpa_supplicant and wpa_cli)
- return executeRootCmd("bash " + Commons.getScriptScan());
-
- }
-
- protected boolean getScanResults() {
-
- // needs root (for wpa_supplicant and wpa_cli)
- boolean res = executeRootCmd("bash " + Commons.getScriptScanRes());
- if (!res) {
- return false;
- }
- return res;
-
- }
-
- protected boolean createScanScripts() {
-
- try {
-
- String scan = getCmdWpaCli() + " scan\n" + "if [ $? -ne 0 ]; then\n" + "exit 1\n"
- + "fi\n" + "sleep 2s\n";
-
- String scanRes = "if [ -e \"" + Commons.getScanFile() + "\" ]; then\n" + " rm \""
- + Commons.getScanFile() + "\"\n" + "fi\n" + getCmdWpaCli()
- + " scan_results > \"" + Commons.getScanFile() + "\"\n"
- + "if [ $? -ne 0 ]; then\n" + " exit 1\n" + "fi\n";
-
- if (!Utils.writeFile(Commons.getScriptScan(), scan, true)) {
-
- Exception e = Utils.getLastException();
- if (e != null) {
- Utils.logError("Error while writing scan script.", e);
- }
-
- return false;
- }
-
- if (!Utils.writeFile(Commons.getScriptScanRes(), scanRes, true)) {
-
- Exception e = Utils.getLastException();
- if (e != null) {
- Utils.logError("Error while writing getScanResults script.", e);
- }
-
- return false;
- }
-
- return true;
-
- } catch (Exception e) {
-
- Utils.logError("Error while creating the scanning script.", e);
- return false;
- }
-
+ return RootCommand.executeRootCmd("ifconfig " + WpaSupplicant.INTERFACE_NAME + " up");
}
}
diff --git a/app/src/fil/libre/repwifiapp/helpers/Engine6p0.java b/app/src/fil/libre/repwifiapp/helpers/Engine6p0.java
index d4ff0f7..3eff6c8 100644
--- a/app/src/fil/libre/repwifiapp/helpers/Engine6p0.java
+++ b/app/src/fil/libre/repwifiapp/helpers/Engine6p0.java
@@ -26,16 +26,9 @@ import fil.libre.repwifiapp.Commons;
public class Engine6p0 extends Engine {
@Override
- protected String getCmdWpaStart() {
- return "wpa_supplicant -B -dd -i" + Commons.INTERFACE_NAME + " -C" + Commons.SOCKET_DIR
- + " -P" + Commons.PID_FILE + " -I" + Commons.OVERLAY_FILE + " -e"
- + Commons.ENTROPY_FILE;
- }
-
- @Override
public boolean connect(AccessPointInfo info) {
- killBackEndProcesses();
+ WpaSupplicant.kill();
if (info == null) {
Utils.logDebug("Engine's connect() received a null AccessPointInfo");
@@ -62,81 +55,81 @@ public class Engine6p0 extends Engine {
// launch wpa_supplicant specifying our custom configuration and the
// socket file
- if (!executeRootCmd(getCmdWpaStart())) {
+ if (!WpaSupplicant.start()) {
Utils.logDebug("Unable to run wpa start");
return false;
}
// create new network and get network id
- String netID = createNetworkGetId();
+ String netID = WpaCli.createNetworkGetId();
if (netID == null) {
Utils.logDebug("Unable to fetch network id");
return false;
}
// set network SSID
- if (!setNetworkSSID(info.getSsid(), netID)) {
+ if (!WpaCli.setNetworkSSID(info.getSsid(), netID)) {
Utils.logDebug("Failed to set network ssid");
return false;
}
- if (info.isHidden() && !setNetworkScanSSID(netID)) {
+ if (info.isHidden() && !WpaCli.setNetworkScanSSID(netID)) {
Utils.logDebug("Failed to set scan_ssid 1 for hidden network.");
return false;
}
// set password (if any)
- if (!setNetworkPSK(info, netID)) {
+ if (!WpaCli.setNetworkPSK(info, netID)) {
Utils.logDebug("Failed to set network psk");
return false;
}
// select the network we just created
- if (!selectNetwork(netID)) {
+ if (!WpaCli.selectNetwork(netID)) {
Utils.logDebug("Unable to wpa_cli select network");
return false;
}
// enable the newtork
- if (!enableNetwork(netID)) {
+ if (!WpaCli.enableNetwork(netID)) {
Utils.logDebug("Unable to wpa_cli enable_newtork");
return false;
}
-
- // try to reassociate to Access Point
- /*
- * if (! reassociate()){
- * Utils.logDebug("Unable to wpa_cli reassociate"); return false; }
- */
+
+ // kill previous dhchcd instances
+ if (!RootCommand.executeRootCmd("killall -SIGINT dhcpcd")){
+ Utils.logError("Unable to kill previous instances of dhcpcd");
+ }
// get DHCP
Utils.logDebug("Attempt to run dhcpcd..");
- if (!runDhcpcd()) {
+ if (!runDhcpcd(info.getDhcpConfiguration())) {
Utils.logDebug("Failed to run dhcpcd");
return false;
}
// try to fetch gateway
- String gw = getGateway();
- if (gw == null || gw.trim().length() < 7) {
+ String gw = getGateWayTimeout(Commons.WAIT_FOR_GATEWAY);
+ if (gw == null || !InetAddressUtils.isIPv4Address(gw)) {
// failed to get gateway
Utils.logDebug("Failed to get gateway");
return false;
}
- if (!executeRootCmd("ndc network create 1")) {
+ if (!RootCommand.executeRootCmd("ndc network create 1")) {
Utils.logDebug("Failed to wpa_cli network create 1 ");
return false;
}
- if (!executeRootCmd("ndc network interface add 1 " + Commons.INTERFACE_NAME)) {
+ if (!RootCommand.executeRootCmd("ndc network interface add 1 "
+ + WpaSupplicant.INTERFACE_NAME)) {
Utils.logDebug("Failed to add interface.");
return false;
}
// set route to gateway for all traffic
- if (!executeRootCmd("ndc network route add 1 " + Commons.INTERFACE_NAME + " 0.0.0.0/0 "
- + gw)) {
+ if (!RootCommand.executeRootCmd("ndc network route add 1 " + WpaSupplicant.INTERFACE_NAME
+ + " 0.0.0.0/0 " + gw)) {
Utils.logDebug("Failed to add route to gateway");
return false;
}
@@ -147,7 +140,7 @@ public class Engine6p0 extends Engine {
}
// use network
- if (!executeRootCmd("ndc network default set 1")) {
+ if (!RootCommand.executeRootCmd("ndc network default set 1")) {
Utils.logDebug("Failed to set network as default");
return false;
}
@@ -156,163 +149,9 @@ public class Engine6p0 extends Engine {
}
- private String createNetworkGetId() {
-
- try {
-
- RootCommand su = new RootCommand(getCmdWpaCli() + " add_network");
- if (su.execute() == 0) {
- String out = su.getOutput();
- if (out == null || out.trim().equals("")) {
- return null;
- } else {
- return out.replace("\n", "");
- }
- } else {
- return null;
- }
-
- } catch (Exception e) {
- Utils.logError("Error while creating network", e);
- return null;
- }
-
- }
-
private boolean destroyNetwork() {
// needs root (tested)
- return executeRootCmd("ndc network destroy 1");
- }
-
- private boolean setNetworkSSID(String ssid, String networkID) {
-
- try {
-
- // needs root (wpa_cli)
- RootCommand su = new RootCommand(getCmdWpaCli() + " set_network " + networkID
- + " ssid '\"" + ssid + "\"'");
- if (su.execute() == 0) {
- String out = su.getOutput();
- if (out != null && out.trim().replace("\n", "").equals("OK")) {
- return true;
- } else {
- return false;
- }
- } else {
- return false;
- }
-
- } catch (Exception e) {
- Utils.logError("Error while setting network SSID", e);
- return false;
- }
-
- }
-
- private boolean setNetworkPSK(AccessPointInfo info, String networkID) {
-
- try {
-
- // needs root (wpa_cli)
-
- String cmdSetPass = null;
- if (info.needsPassword()) {
- cmdSetPass = getCmdWpaCli() + " set_network " + networkID + " psk '\""
- + info.getPassword() + "\"'";
- } else {
- cmdSetPass = getCmdWpaCli() + " set_network " + networkID + " key_mgmt NONE";
- }
-
- RootCommand su = new RootCommand(cmdSetPass);
- if (su.execute() == 0) {
- String out = su.getOutput();
- if (out != null && out.trim().replace("\n", "").equals("OK")) {
- return true;
- } else {
- return false;
- }
- } else {
- return false;
- }
-
- } catch (Exception e) {
- Utils.logError("Error while setting network PSK", e);
- return false;
- }
-
- }
-
- private boolean setNetworkScanSSID(String networkID) {
-
- try {
-
- // needs root (wpa_cli)
- RootCommand su = new RootCommand(getCmdWpaCli() + " set_network " + networkID
- + " scan_ssid 1");
- if (su.execute() == 0) {
- String out = su.getOutput();
- if (out != null && out.trim().replace("\n", "").equals("OK")) {
- return true;
- } else {
- return false;
- }
- } else {
- return false;
- }
-
- } catch (Exception e) {
- Utils.logError("Error while setting network SSID", e);
- return false;
- }
- }
-
- private boolean selectNetwork(String networkID) {
-
- try {
-
- // needs root (wpa_cli)
- RootCommand su = new RootCommand(getCmdWpaCli() + " select_network " + networkID);
- if (su.execute() == 0) {
- String out = su.getOutput();
- if (out != null && out.trim().replace("\n", "").equals("OK")) {
- return true;
- } else {
- return false;
- }
- } else {
- return false;
- }
-
- } catch (Exception e) {
- Utils.logError("Error while selecting network", e);
- return false;
- }
-
- }
-
- private boolean enableNetwork(String networkID) {
-
- try {
-
- // needs root (wpa_cli)
-
- RootCommand su = new RootCommand(getCmdWpaCli() + " enable_network " + networkID);
- if (su.execute() == 0) {
- String out = su.getOutput();
- if (out != null && out.trim().replace("\n", "").equals("OK")) {
- return true;
- } else {
- return false;
- }
- } else {
- return false;
- }
-
- } catch (Exception e) {
- Utils.logError("Error while enabling network", e);
- return false;
- }
-
+ return RootCommand.executeRootCmd("ndc network destroy 1");
}
private boolean setDns(String[] dnss, String gateway) {
@@ -343,7 +182,42 @@ public class Engine6p0 extends Engine {
cmd += " " + dnss[0];
}
- return executeRootCmd(cmd);
+ return RootCommand.executeRootCmd(cmd);
+ }
+
+ private String getGateWayTimeout(int timeoutMillis) {
+
+ String gw = getGateway();
+ if (gw != null && !gw.trim().isEmpty()) {
+ return gw;
+ }
+
+ Utils.logDebug("Gateway not available.. going into wait loop..");
+
+ // gateway not (yet) available
+ // waits for a maximum of timeoutMillis milliseconds
+ // to let the interface being registered.
+ int msWaited = 0;
+ while (msWaited < timeoutMillis) {
+
+ try {
+ Thread.sleep(100);
+ } catch (Exception e) {
+ return null;
+ }
+ msWaited += 100;
+
+ gw = getGateway();
+ if (gw != null && !gw.trim().isEmpty()) {
+ Utils.logDebug("Gateway found after wait loop!");
+ return gw;
+ }
+ }
+
+ // unable to get gateway
+ Utils.logError("Gateway not found after wait loop.");
+ return null;
+
}
private String getGateway() {
@@ -351,7 +225,7 @@ public class Engine6p0 extends Engine {
try {
// doesn't need root (tested)
- RootCommand cmd = new RootCommand("ip route show dev " + Commons.INTERFACE_NAME);
+ ShellCommand cmd = new ShellCommand("ip route show dev " + WpaSupplicant.INTERFACE_NAME);
if (cmd.execute() != 0) {
Utils.logDebug("command failed show route");
return null;
@@ -390,7 +264,8 @@ public class Engine6p0 extends Engine {
private boolean clearAddrs() {
// needs root (tested)
- return executeRootCmd("ndc interface clearaddrs " + Commons.INTERFACE_NAME);
+ return RootCommand.executeRootCmd("ndc interface clearaddrs "
+ + WpaSupplicant.INTERFACE_NAME);
}
} \ No newline at end of file
diff --git a/app/src/fil/libre/repwifiapp/helpers/IEngine.java b/app/src/fil/libre/repwifiapp/helpers/IEngine.java
index 037cf62..26ebddb 100644
--- a/app/src/fil/libre/repwifiapp/helpers/IEngine.java
+++ b/app/src/fil/libre/repwifiapp/helpers/IEngine.java
@@ -24,12 +24,6 @@ import java.net.SocketException;
public interface IEngine {
- public boolean startWpaSupplicant();
-
- public boolean killBackEndProcesses();
-
- public boolean clearWorkingDir();
-
public AccessPointInfo[] getAvailableNetworks();
public boolean connect(AccessPointInfo info);
@@ -40,6 +34,4 @@ public interface IEngine {
public boolean isInterfaceAvailable(String ifaceName) throws SocketException;
- public String[] getAvailableInterfaces();
-
}
diff --git a/app/src/fil/libre/repwifiapp/helpers/NetworkManager.java b/app/src/fil/libre/repwifiapp/helpers/NetworkManager.java
index db27f7e..96805a6 100644
--- a/app/src/fil/libre/repwifiapp/helpers/NetworkManager.java
+++ b/app/src/fil/libre/repwifiapp/helpers/NetworkManager.java
@@ -20,13 +20,16 @@
package fil.libre.repwifiapp.helpers;
+import org.json.JSONArray;
+import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
public class NetworkManager {
+ private static final String VERSION_NOTE = "RepWifiStorageVersion: 2.0\n";
private static final String F_SEP = "\t";
- private static final int NET_MAX_AGE = 365; // Expressed in days
+ private static final int NET_MAX_AGE = 1095; // Expressed in days
private String _knownNetworksFile = null;
@@ -34,7 +37,7 @@ public class NetworkManager {
this._knownNetworksFile = networksFilePath;
}
- private AccessPointInfo searchInFile(AccessPointInfo i) {
+ private AccessPointInfo getSavedInfo(AccessPointInfo i) {
if (i == null) {
return null;
@@ -63,12 +66,16 @@ public class NetworkManager {
// then return the best match (only ssid), if any
if (toTest.getSsid().equals(ssid)) {
+ i.setPassword(toTest.getPassword());
+ i.setDhcpConfiguration(toTest.getDhcpConfiguration());
+ i.setVpnProfileName(toTest.getVpnProfileName());
+
if (toTest.getBssid().equals(bssid)) {
- i.setPassword(toTest.getPassword());
+ // complete match, return.
return i;
} else {
- i.setPassword(toTest.getPassword());
+ // probable match
ret = i;
}
@@ -82,11 +89,6 @@ public class NetworkManager {
private boolean saveOrRemove(AccessPointInfo info, boolean save) {
- String iText = InfoToString(info);
- if (iText == null) {
- return false;
- }
-
AccessPointInfo[] existingNets = getKnownNetworks();
ArrayList<AccessPointInfo> newlist = new ArrayList<AccessPointInfo>();
@@ -151,7 +153,7 @@ public class NetworkManager {
}
- private AccessPointInfo getFromString(String savedString) {
+ private AccessPointInfo getFromStringOld(String savedString) {
if (savedString == null || savedString.trim().equals("")) {
return null;
@@ -168,11 +170,25 @@ public class NetworkManager {
String pass = fields[2];
String lastUsed = fields[3];
String auth = null;
+ String ipWmask = null;
+ String gw = null;
+ boolean useDhcp = true;
+ String vpnProfile = null;
if (fields.length > 4) {
auth = fields[4];
}
+ if (fields.length > 6) {
+ ipWmask = fields[5];
+ gw = fields[6];
+ useDhcp = false;
+ }
+
+ if (fields.length > 7) {
+ vpnProfile = fields[7];
+ }
+
long lastusedmillis = 0;
try {
lastusedmillis = Long.parseLong(lastUsed);
@@ -189,69 +205,129 @@ public class NetworkManager {
AccessPointInfo i = new AccessPointInfo(ssid, bssid, auth, null, null);
i.setPassword(pass);
i.setLastTimeUsed(lastusedmillis);
+ i.setVpnProfileName(vpnProfile);
+
+ if (!useDhcp) {
+ DhcpSettings s = DhcpSettings.parseSavedSettings(ipWmask, gw);
+ i.setDhcpConfiguration(s);
+ }
return i;
}
- private String InfoToString(AccessPointInfo info) {
+ private boolean saveList(AccessPointInfo[] list) {
- if (info == null) {
- return null;
- }
+ try {
- String bssid = info.getBssid();
- String ssid = info.getSsid();
- String pass = info.getPassword();
- String tsLastUsed = "" + info.getLastTimeUsed();
- String auth = info.getAuthType();
+ JSONArray jarr = new JSONArray();
+ for (AccessPointInfo i : list) {
- if (bssid == null || bssid.trim().equals("")) {
- return null;
- }
+ JSONObject jo = i.toJson();
+ if (jo == null) {
+ return false;
+ }
- if (ssid == null || ssid.trim().equals("")) {
- return null;
- }
+ jarr.put(jo);
- if (pass == null || pass.trim().equals("")) {
- return null;
- }
+ }
+
+ StringBuilder sb = new StringBuilder();
+ sb.append(VERSION_NOTE);
+ sb.append("\n");
+
+ sb.append(jarr.toString(2));
+
+ return Utils.writeFile(_knownNetworksFile, sb.toString(), true);
- if (auth == null) {
- auth = "";
+ } catch (Exception e) {
+ Utils.logError("Exception while saving AccessPointInfo array to JSON-formatted file.",
+ e);
+ return false;
}
- String iText = info.getBssid() + F_SEP + info.getSsid() + F_SEP + info.getPassword()
- + F_SEP + tsLastUsed + F_SEP + auth;
- return iText;
+ /*
+ * if (list == null) { return false; }
+ *
+ * String[] lines = new String[list.length];
+ *
+ * for (int i = 0; i < list.length; i++) {
+ *
+ * String storeString = InfoToString(list[i]); if (storeString == null)
+ * { return false; } lines[i] = storeString;
+ *
+ * }
+ *
+ * return Utils.writeFileLines(this._knownNetworksFile, lines, true);
+ */
}
- private boolean saveList(AccessPointInfo[] list) {
+ public boolean updateStorageVersion() {
- if (list == null) {
- return false;
+ String[] lines = Utils.readFileLines(_knownNetworksFile);
+ if (lines.length == 0) {
+ return true;
}
- String[] lines = new String[list.length];
+ if (lines[0].trim().equals(VERSION_NOTE)) {
+ return true;
- for (int i = 0; i < list.length; i++) {
+ } else {
- String storeString = InfoToString(list[i]);
- if (storeString == null) {
- return false;
+ AccessPointInfo[] infos = getKnownNetworksOld();
+ if (infos == null || infos.length == 0) {
+ return true;
}
- lines[i] = storeString;
+ return saveList(infos);
}
- return Utils.writeFileLines(this._knownNetworksFile, lines, true);
-
}
public AccessPointInfo[] getKnownNetworks() {
+ try {
+
+ String fconts = Utils.readFile(_knownNetworksFile);
+ if (fconts == null) {
+ return null;
+ }
+
+ if (!fconts.startsWith(VERSION_NOTE)) {
+ // wrong version, try to convert it
+ if (updateStorageVersion()) {
+ return getKnownNetworks();
+ } else {
+ return null;
+ }
+ }
+
+ JSONArray jarr = new JSONArray(fconts.replace(VERSION_NOTE, ""));
+ ArrayList<AccessPointInfo> list = new ArrayList<AccessPointInfo>();
+
+ int count = 0;
+ for (int i = 0; i < jarr.length(); i++) {
+ AccessPointInfo info = AccessPointInfo.fromJsonObject(jarr.getJSONObject(i));
+ if (info == null) {
+ continue;
+ }
+ count += 1;
+ list.add(info);
+ }
+
+ AccessPointInfo[] arr = new AccessPointInfo[count];
+ return list.toArray(arr);
+
+ } catch (Exception e) {
+ Utils.logError("Exception while parsing JSON content from storage file.", e);
+ return null;
+ }
+
+ }
+
+ public AccessPointInfo[] getKnownNetworksOld() {
+
ArrayList<AccessPointInfo> list = new ArrayList<AccessPointInfo>();
File f = new File(this._knownNetworksFile);
@@ -266,7 +342,7 @@ public class NetworkManager {
for (String l : lines) {
- AccessPointInfo info = getFromString(l);
+ AccessPointInfo info = getFromStringOld(l);
if (info != null) {
list.add(info);
}
@@ -282,7 +358,7 @@ public class NetworkManager {
public boolean isKnown(AccessPointInfo info) {
- AccessPointInfo i = searchInFile(info);
+ AccessPointInfo i = getSavedInfo(info);
if (i == null) {
return false;
} else {
@@ -300,7 +376,7 @@ public class NetworkManager {
}
public AccessPointInfo getSavedNetwork(AccessPointInfo i) {
- return searchInFile(i);
+ return getSavedInfo(i);
}
}
diff --git a/app/src/fil/libre/repwifiapp/helpers/OpenVpnManager.java b/app/src/fil/libre/repwifiapp/helpers/OpenVpnManager.java
new file mode 100644
index 0000000..5de2501
--- /dev/null
+++ b/app/src/fil/libre/repwifiapp/helpers/OpenVpnManager.java
@@ -0,0 +1,237 @@
+//
+// Copyright 2017 Filippo "Fil" Bergamo <fil.bergamo@riseup.net>
+//
+// This file is part of RepWifiApp.
+// This file is based upon the example file included in
+// de.blinkt.openvpn package by Arne Schwabe.
+//
+// RepWifiApp is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// RepWifiApp is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with RepWifiApp. If not, see <http://www.gnu.org/licenses/>.
+//
+// ********************************************************************
+
+package fil.libre.repwifiapp.helpers;
+
+import android.app.Activity;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ServiceConnection;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.os.IBinder;
+import android.os.RemoteException;
+import java.util.ArrayList;
+import java.util.List;
+import de.blinkt.openvpn.api.APIVpnProfile;
+import de.blinkt.openvpn.api.IOpenVPNAPIService;
+
+public class OpenVpnManager {
+
+ public static final String SERVICE_PACKAGE_NAME = "de.blinkt.openvpn";
+ public static final String APP_COMMON_NAME = "OpenVPN for Android";
+ public static final String PLACEHOLDER_APPNAME = "[VPN_EXT_APP]";
+
+ private static boolean VpnIsConnected;
+ private static OpenVpnManager _currentInstance;
+
+ protected IOpenVPNAPIService _vpnSvc;
+
+ private Activity _caller;
+ private ServiceConnection _svcConnection = new ServiceConnection() {
+ public void onServiceConnected(ComponentName className, IBinder service) {
+ _vpnSvc = IOpenVPNAPIService.Stub.asInterface(service);
+ }
+
+ public void onServiceDisconnected(ComponentName className) {
+ _vpnSvc = null;
+ }
+ };
+
+ private OpenVpnManager(Activity c) throws Exception {
+ this._caller = c;
+ bindService();
+ }
+
+ private void bindService() throws Exception {
+
+ Intent intentGetService = new Intent(IOpenVPNAPIService.class.getName());
+ intentGetService.setPackage(SERVICE_PACKAGE_NAME);
+ if (!_caller.bindService(intentGetService, _svcConnection, Context.BIND_AUTO_CREATE)) {
+ throw new Exception("FAILED to bind to OpenVPN service!");
+ }
+
+ }
+
+ private void unbindService() {
+ _caller.unbindService(_svcConnection);
+ }
+
+ private Intent askApiPermissionsGetIntentInternal() throws RemoteException {
+ return _vpnSvc.prepare(_caller.getPackageName());
+ }
+
+ private boolean startVpnInternal(String profileUuid) {
+
+ if (profileUuid == null) {
+ Utils.logError("Invoked startVpn with null uuid");
+ return false;
+ }
+
+ if (_vpnSvc == null) {
+ Utils.logError("Invoked startVpn but inner service is null.");
+ return false;
+ }
+
+ try {
+
+ _vpnSvc.startProfile(profileUuid);
+ VpnIsConnected = true;
+ return true;
+
+ } catch (RemoteException e) {
+ Utils.logError("Exception while starting vpn.", e);
+ return false;
+ }
+ }
+
+ private boolean disconnectInternal() {
+
+ if (_vpnSvc == null) {
+ Utils.logDebug("Attempted to disconnect from VPN, but inner service is null");
+ VpnIsConnected = false;
+ return true;
+ }
+
+ try {
+ _vpnSvc.disconnect();
+ VpnIsConnected = false;
+ return true;
+ } catch (RemoteException e) {
+ Utils.logError("Exception while disconnecting from vpn.", e);
+ return false;
+ }
+ }
+
+ private List<String> getExistingProfilesInternal(){
+
+ try {
+ List<APIVpnProfile> list = _vpnSvc.getProfiles();
+
+ List<String> ret = new ArrayList<String>();
+ for (APIVpnProfile vp : list) {
+ ret.add(vp.mName);
+ }
+
+ return ret;
+
+ } catch (RemoteException e) {
+ Utils.logError("Exception while retrieving profiles from vpn service.", e);
+ return null;
+ }
+
+ }
+
+ private String getUuidFromNameInternal(String profileName) {
+
+ if (_vpnSvc == null) {
+ Utils.logError("Called getUuidFromName but inner service is null!");
+ return null;
+ }
+
+ try {
+ List<APIVpnProfile> list = _vpnSvc.getProfiles();
+
+ for (APIVpnProfile vp : list) {
+ if (vp.mName.equals(profileName)) {
+ return vp.mUUID;
+ }
+ }
+
+ return null;
+
+ } catch (RemoteException e) {
+ Utils.logError("Exception while retrieving profiles from vpn service.", e);
+ return null;
+ }
+ }
+
+ public void close() {
+ if (_vpnSvc != null) {
+ unbindService();
+
+ }
+
+ }
+
+ public static void initialize(Activity caller){
+
+ if (_currentInstance != null){
+ return;
+ }
+
+ try {
+ _currentInstance = new OpenVpnManager(caller);
+ } catch (Exception e) {
+ Utils.logError("Exception while initializing vpn manager.",e);
+ }
+ }
+
+ public static boolean isExternalAppInstalled(Activity caller) {
+
+ try {
+
+ ApplicationInfo i;
+ i = caller.getPackageManager().getApplicationInfo(SERVICE_PACKAGE_NAME, 0);
+ return (i != null);
+
+ } catch (NameNotFoundException e) {
+ return false;
+ }
+
+ }
+
+ public static boolean startVpn(String profileUuid){
+ if (_currentInstance == null){
+ return false;
+ }
+ return _currentInstance.startVpnInternal(profileUuid);
+ }
+
+ public static boolean disconnect(){
+ if (_currentInstance == null){
+ return false;
+ }
+ return _currentInstance.disconnectInternal();
+ }
+
+ public static boolean isVpnConnected(){
+ return VpnIsConnected;
+ }
+
+ public static String getUuidFromName(String profileName){
+ if (_currentInstance == null){
+ return null;
+ }
+ return _currentInstance.getUuidFromNameInternal(profileName);
+ }
+
+ public static List<String> getExistingProfiles(){
+ return _currentInstance.getExistingProfilesInternal();
+ }
+
+ public static Intent askApiPermissionsGetIntent() throws RemoteException{
+ return _currentInstance.askApiPermissionsGetIntentInternal();
+ }
+
+}
diff --git a/app/src/fil/libre/repwifiapp/helpers/RootCommand.java b/app/src/fil/libre/repwifiapp/helpers/RootCommand.java
index 9d9f7d3..bd859c8 100644
--- a/app/src/fil/libre/repwifiapp/helpers/RootCommand.java
+++ b/app/src/fil/libre/repwifiapp/helpers/RootCommand.java
@@ -22,71 +22,89 @@ package fil.libre.repwifiapp.helpers;
import java.io.DataOutputStream;
import java.io.InputStream;
-import fil.libre.repwifiapp.Commons;
+
public class RootCommand extends ShellCommand {
+ // protected static final String CMD_WRAPPING = "export TEMPOUT=\"$(%s)\";echo \"$TEMPOUT\";exit $?";
+ protected static final String CMD_WRAPPING = "TEMPOUT=\"$(%s)\";ec=$?;echo \"$TEMPOUT\";exit $ec";
+
public RootCommand(String commandText) {
super(commandText);
this._cmdTxt = commandText;
}
+
+ public static boolean executeRootCmd(String cmd) {
+
+ try {
+ RootCommand c = new RootCommand(cmd);
+ if (c.execute() == 0) {
+ return true;
+ } else {
+ return false;
+ }
+
+ } catch (Exception e) {
+ Utils.logError("Error executing \"" + cmd + "\"", e);
+ return false;
+ }
+ }
+
@Override
public int execute() throws Exception {
+ if (this._cmdTxt == null) {
+ return EXITCODE_INVALID_INPUT;
+ }
+
Process su = Runtime.getRuntime().exec("su");
DataOutputStream stdin = new DataOutputStream(su.getOutputStream());
InputStream os = su.getInputStream();
InputStream es = su.getErrorStream();
- if (this._cmdTxt != null) {
-
- Utils.logDebug("SU:EXEC: " + this._cmdTxt);
+ Utils.logDebug("SU:EXEC: " + this._cmdTxt);
- this._cmdTxt += " > " + Commons.getTempOutFile();
-
- stdin.writeBytes(this._cmdTxt + "\n");
- stdin.flush();
- }
+ String wrappedCmd = String.format(CMD_WRAPPING, this._cmdTxt);
+
+ stdin.writeBytes(wrappedCmd + "\n");
+ stdin.flush();
StringBuilder sb = new StringBuilder();
sb.append(getStringFromStream(es));
sb.append(getStringFromStream(os));
- this._cmdOut = sb.toString();
-
- stdin.writeBytes("exit\n");
- stdin.flush();
-
int res = su.waitFor();
// re-read the output, in case it was empty when first tried
sb.append(getStringFromStream(es));
sb.append(getStringFromStream(os));
+ this._cmdOut = sb.toString();
+
Utils.logDebug("OUT: " + getOutput());
return res;
}
+
+ public int testRootAccess() throws Exception {
- @Override
- public String getOutput() {
+ Process su = Runtime.getRuntime().exec("su");
- String[] lastOut = Utils.readFileLines(Commons.getTempOutFile());
- if (lastOut == null) {
- return this._cmdOut;
- }
+ DataOutputStream stdin = new DataOutputStream(su.getOutputStream());
- String fout = "";
+ Utils.logDebug("Testing root access: executing simple \"su\"");
+ stdin.writeBytes("exit\n");
+ stdin.flush();
- for (String s : lastOut) {
- fout += s + "\n";
- }
+ int res = su.waitFor();
- return fout;
+ Utils.logDebug("Simple \"su\" exitcode: " + res);
+
+ return res;
}
diff --git a/app/src/fil/libre/repwifiapp/helpers/ShellCommand.java b/app/src/fil/libre/repwifiapp/helpers/ShellCommand.java
index fbeb719..f232ac7 100644
--- a/app/src/fil/libre/repwifiapp/helpers/ShellCommand.java
+++ b/app/src/fil/libre/repwifiapp/helpers/ShellCommand.java
@@ -5,6 +5,8 @@ import java.io.InputStream;
public class ShellCommand {
+ public static final int EXITCODE_INVALID_INPUT = -9;
+
protected String _cmdOut = "";
protected String _cmdTxt = "";
@@ -15,12 +17,13 @@ public class ShellCommand {
public int execute() throws Exception {
if (this._cmdTxt == null) {
- return -9;
+ return EXITCODE_INVALID_INPUT;
}
Utils.logDebug("EXEC: " + this._cmdTxt);
Process cmd = Runtime.getRuntime().exec(this._cmdTxt);
+
InputStream os = cmd.getInputStream();
InputStream es = cmd.getErrorStream();
@@ -47,6 +50,11 @@ public class ShellCommand {
protected String getStringFromStream(InputStream s) throws IOException {
+ java.util.Scanner sc = new java.util.Scanner(s,"UTF-8").useDelimiter("\\A");
+ return sc.hasNext() ? sc.next() : "";
+
+ /*
+
StringBuilder sb = new StringBuilder();
while ((s.available() > 0)) {
int b = s.read();
@@ -57,7 +65,7 @@ public class ShellCommand {
}
}
- return sb.toString();
+ return sb.toString();*/
}
@@ -65,17 +73,6 @@ public class ShellCommand {
return this._cmdOut;
- /*
- * String[] lastOut = Utils.readFileLines(Commons.getTempOutFile()); if
- * (lastOut == null){ return this._cmdOut; }
- *
- * String fout = "";
- *
- * for (String s : lastOut){ fout += s + "\n"; }
- *
- * return fout;
- */
-
}
}
diff --git a/app/src/fil/libre/repwifiapp/helpers/Utils.java b/app/src/fil/libre/repwifiapp/helpers/Utils.java
index 8cd90bf..ad10c1a 100644
--- a/app/src/fil/libre/repwifiapp/helpers/Utils.java
+++ b/app/src/fil/libre/repwifiapp/helpers/Utils.java
@@ -63,63 +63,50 @@ public class Utils {
Log.d(APP_NAME, msg);
}
- public static boolean writeFile(String filePath, String text, boolean overwrite) {
-
- FileWriter writer = null;
- boolean retval = false;
+ public static boolean writeFileLines(String filePath, String[] lines, boolean overwrite) {
- try {
+ if (lines == null) {
+ return false;
+ }
- writer = new FileWriter(filePath, (!overwrite));
- writer.write(text);
+ if (lines.length == 0) {
+ return true;
+ }
- retval = true;
+ StringBuilder sb = new StringBuilder();
- } catch (Exception e) {
- _lastException = e;
- retval = false;
- } finally {
+ for (String l : lines) {
- if (writer != null) {
- try {
- writer.close();
- } catch (IOException e) {
- logError("error while closing filewriter", e);
- }
+ if (l == null) {
+ return false;
}
+ sb.append(l + "\n");
}
- return retval;
+ return writeFile(filePath, sb.toString(), overwrite);
}
- public static boolean writeFileLines(String filePath, String[] lines, boolean overwrite) {
+ public static boolean writeFile(String filePath, String content, boolean overwrite) {
- if (lines == null) {
+ if (content == null) {
return false;
}
FileWriter writer = null;
- boolean retval = false;
try {
writer = new FileWriter(filePath, (!overwrite));
+ writer.write(content);
- if (lines.length == 0) {
- writer.write("");
- }
-
- for (String l : lines) {
- writer.write(l + "\n");
- }
-
- retval = true;
+ return true;
} catch (Exception e) {
_lastException = e;
- retval = false;
+ return false;
+
} finally {
if (writer != null) {
@@ -132,8 +119,6 @@ public class Utils {
}
- return retval;
-
}
public static String[] readFileLines(String filePath) {
@@ -152,7 +137,6 @@ public class Utils {
BufferedReader bufr = null;
List<String> lines = new ArrayList<String>();
- String[] ret = null;
try {
@@ -165,11 +149,13 @@ public class Utils {
}
String[] ar = new String[lines.size()];
- ret = lines.toArray(ar);
+
+ return lines.toArray(ar);
} catch (Exception e) {
logError("Error while reading file " + filePath, e);
- ret = null;
+ return null;
+
} finally {
try {
if (bufr != null) {
@@ -187,10 +173,61 @@ public class Utils {
}
}
- return ret;
-
}
+ public static String readFile(String filePath){
+
+ if (filePath == null) {
+ return null;
+ }
+
+ File f = new File(filePath);
+ if (!f.exists()) {
+ logError("File doesn't exist: " + filePath);
+ return null;
+ }
+
+ FileReader fr = null;
+ BufferedReader bufr = null;
+
+ StringBuilder sb = new StringBuilder();
+
+ try {
+
+ fr = new FileReader(filePath);
+ bufr = new BufferedReader(fr);
+ String line = "";
+
+ while ((line = bufr.readLine()) != null) {
+ sb.append(line);
+ sb.append("\n");
+ }
+
+ return sb.toString();
+
+ } catch (Exception e) {
+ logError("Error while reading file " + filePath, e);
+ return null;
+
+ } finally {
+ try {
+ if (bufr != null) {
+ bufr.close();
+ }
+ } catch (IOException ex) {
+ logError("error while closing filereader", ex);
+ }
+ try {
+ if (fr != null) {
+ fr.close();
+ }
+ } catch (IOException exc) {
+ logError("error while closing filereader", exc);
+ }
+ }
+
+ }
+
public static long daysToMilliseconds(int days) {
return (days * MILLIS_IN_DAY);
}
@@ -199,4 +236,120 @@ public class Utils {
return (milliseconds / MILLIS_IN_DAY);
}
+ public static boolean dumpLogcatToFile(String filePath) {
+
+ if (filePath == null) {
+ return false;
+ }
+
+ try {
+
+ String cmd1 = "logcat -d | grep " + APP_NAME + ">" + filePath;
+ String cmd2 = "logcat -d | grep " + Commons.getContext().getPackageName() + ">>"
+ + filePath;
+ String SEP_LOG = "\n\n---------- [REPWIFI_LOG_SEPARATOR] ----------\n\n";
+
+ RootCommand c1 = new RootCommand(cmd1);
+ RootCommand c2 = new RootCommand(cmd2);
+
+ if (c1.execute() != 0) {
+ return false;
+ }
+
+ if (!writeFile(filePath, SEP_LOG, false)) {
+ return false;
+ }
+
+ if (c2.execute() != 0) {
+ return false;
+ }
+
+ return true;
+
+ } catch (Exception e) {
+ logError("Exception during log dump.", e);
+ return false;
+ }
+
+ }
+
+ public static String netmaskIntToString(int mask) {
+
+ if (mask < 8 || mask > 32) {
+ return null;
+ }
+
+ StringBuilder sb = new StringBuilder(32);
+ StringBuilder sb2 = new StringBuilder(15);
+
+ for (int i = 0; i < mask; i++) {
+ sb.append("1");
+ }
+
+ for (int i = 0; i < 32 - mask; i++) {
+ sb.append("0");
+ }
+
+ for (int i = 0; i < 3; i++) {
+ String bitString = sb.substring((i * 8), (i * 8) + 8);
+ int ibyte = Integer.parseInt(bitString, 2);
+ sb2.append(ibyte);
+ sb2.append(".");
+ }
+ String bitString = sb.substring(24, 32);
+ int ibyte = Integer.parseInt(bitString, 2);
+ sb2.append(ibyte);
+
+ return sb2.toString();
+
+ }
+
+ public static int netmaskStringToInt(String mask) {
+
+ if (mask == null) {
+ return -1;
+ }
+
+ String[] octs = mask.split("\\.");
+ if (octs.length != 4) {
+ return -1;
+ }
+
+ int intmask = 0;
+ boolean prevIsZero = false;
+ for (String o : octs) {
+
+ int intval = 0;
+
+ try {
+ intval = Integer.parseInt(o, 10);
+ } catch (NumberFormatException e) {
+ return -1;
+ }
+
+ String b = Integer.toBinaryString(intval);
+ if (b.length() != 8 && b.contains("1")) {
+ //invalid mask! has ones after a zero
+ return -1;
+ }
+ for (int i = 0; i < b.length(); i++) {
+ if (b.charAt(i) == '0') {
+ prevIsZero = true;
+
+ } else if (prevIsZero) {
+ // invalid mask
+ return -1;
+
+ } else {
+ intmask += 1;
+ }
+
+ }
+
+ }
+
+ return intmask;
+
+ }
+
}
diff --git a/app/src/fil/libre/repwifiapp/helpers/WpaCli.java b/app/src/fil/libre/repwifiapp/helpers/WpaCli.java
new file mode 100644
index 0000000..8bd6561
--- /dev/null
+++ b/app/src/fil/libre/repwifiapp/helpers/WpaCli.java
@@ -0,0 +1,263 @@
+package fil.libre.repwifiapp.helpers;
+
+public abstract class WpaCli {
+
+ private static final int SCAN_WAIT_INTERVAL = 3;
+ private static final String BASE_COMMAND = "wpa_cli -p" + WpaSupplicant.SOCKET_DIR + " -P"
+ + WpaSupplicant.PID_FILE + " -i" + WpaSupplicant.INTERFACE_NAME;
+
+ public static String createNetworkGetId() {
+
+ try {
+
+ RootCommand su = new RootCommand(BASE_COMMAND + " add_network");
+ if (su.execute() == 0) {
+ String out = su.getOutput();
+ if (out == null || out.trim().equals("")) {
+ return null;
+ } else {
+ return out.replace("\n", "");
+ }
+ } else {
+ return null;
+ }
+
+ } catch (Exception e) {
+ Utils.logError("Error while creating network", e);
+ return null;
+ }
+
+ }
+
+ public static boolean setNetworkSSID(String ssid, String networkID) {
+
+ try {
+
+ // needs root (wpa_cli)
+ RootCommand su = new RootCommand(BASE_COMMAND + " set_network " + networkID
+ + " ssid '\"" + ssid + "\"'");
+ if (su.execute() == 0) {
+ String out = su.getOutput();
+ if (out != null && out.trim().replace("\n", "").equals("OK")) {
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ return false;
+ }
+
+ } catch (Exception e) {
+ Utils.logError("Error while setting network SSID", e);
+ return false;
+ }
+
+ }
+
+ public static boolean setNetworkPSK(AccessPointInfo info, String networkID) {
+
+ try {
+
+ // needs root (wpa_cli)
+
+ String cmdSetPass = null;
+ if (info.needsPassword()) {
+ cmdSetPass = BASE_COMMAND + " set_network " + networkID + " psk '\""
+ + info.getPassword() + "\"'";
+ } else {
+ cmdSetPass = BASE_COMMAND + " set_network " + networkID + " key_mgmt NONE";
+ }
+
+ RootCommand su = new RootCommand(cmdSetPass);
+ if (su.execute() == 0) {
+ String out = su.getOutput();
+ if (out != null && out.trim().replace("\n", "").equals("OK")) {
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ return false;
+ }
+
+ } catch (Exception e) {
+ Utils.logError("Error while setting network PSK", e);
+ return false;
+ }
+
+ }
+
+ public static boolean setNetworkScanSSID(String networkID) {
+
+ try {
+
+ // needs root (wpa_cli)
+ RootCommand su = new RootCommand(BASE_COMMAND + " set_network " + networkID
+ + " scan_ssid 1");
+ if (su.execute() == 0) {
+ String out = su.getOutput();
+ if (out != null && out.trim().replace("\n", "").equals("OK")) {
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ return false;
+ }
+
+ } catch (Exception e) {
+ Utils.logError("Error while setting network SSID", e);
+ return false;
+ }
+ }
+
+ public static boolean selectNetwork(String networkID) {
+
+ try {
+
+ // needs root (wpa_cli)
+ RootCommand su = new RootCommand(BASE_COMMAND + " select_network " + networkID);
+ if (su.execute() == 0) {
+ String out = su.getOutput();
+ if (out != null && out.trim().replace("\n", "").equals("OK")) {
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ return false;
+ }
+
+ } catch (Exception e) {
+ Utils.logError("Error while selecting network", e);
+ return false;
+ }
+
+ }
+
+ public static boolean enableNetwork(String networkID) {
+
+ try {
+
+ // needs root (wpa_cli)
+
+ RootCommand su = new RootCommand(BASE_COMMAND + " enable_network " + networkID);
+ if (su.execute() == 0) {
+ String out = su.getOutput();
+ if (out != null && out.trim().replace("\n", "").equals("OK")) {
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ return false;
+ }
+
+ } catch (Exception e) {
+ Utils.logError("Error while enabling network", e);
+ return false;
+ }
+
+ }
+
+ public static boolean scanNetworks() {
+
+ // needs root (for wpa_supplicant and wpa_cli)
+ return RootCommand.executeRootCmd(BASE_COMMAND
+ + " scan; if [ $? -ne 0 ]; then exit 1; fi; sleep " + SCAN_WAIT_INTERVAL);
+
+ }
+
+ public static String getScanResults() {
+
+ try {
+
+ RootCommand su = new RootCommand(BASE_COMMAND
+ + " scan_results; if [ $? -ne 0 ]; then exit 1; fi ");
+ if (su.execute() == 0) {
+ String out = su.getOutput();
+ if (out == null || out.trim().equals("")) {
+ return null;
+ } else {
+ return out;
+ }
+ } else {
+ return null;
+ }
+
+ } catch (Exception e) {
+ Utils.logError("Error while executing wpa_cli status", e);
+ return null;
+ }
+
+ /*
+ * // needs root (for wpa_supplicant and wpa_cli) boolean res =
+ * RootCommand.executeRootCmd(); if (!res) { return false; } return res;
+ */
+
+ }
+
+ /***
+ * returns null if unable to determine connection status for any reason.
+ */
+ public static ConnectionStatus getConnectionStatus() {
+
+ Utils.logDebug("called getConnecitonStatus()");
+ if (!WpaSupplicant.isRunning()) {
+ // wpa_supplicant is not running.
+ // unable to determine status.
+ Utils.logDebug("wpa not running, cannot get connection status.");
+ return null;
+
+ }
+
+ try {
+
+ RootCommand su = new RootCommand(BASE_COMMAND + " status");
+ if (su.execute() == 0) {
+ String out = su.getOutput();
+ if (out == null || out.trim().equals("")) {
+ return null;
+ } else {
+ return ConnectionStatus.parseWpaCliOutput(out);
+ }
+ } else {
+ return null;
+ }
+
+ } catch (Exception e) {
+ Utils.logError("Error while executing wpa_cli status", e);
+ return null;
+ }
+
+ }
+
+ public static boolean disconnect() {
+
+ // needs root (for wpa_cli)
+
+ if (!WpaSupplicant.isRunning()) {
+ return true;
+ }
+
+ try {
+
+ RootCommand su = new RootCommand(BASE_COMMAND + " disconnect");
+ if (su.execute() == 0) {
+ String out = su.getOutput();
+ if (out != null && out.trim().replace("\n", "").equals("OK")) {
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ return false;
+ }
+
+ } catch (Exception e) {
+ Utils.logError("Error while enabling network", e);
+ return false;
+ }
+ }
+
+}
diff --git a/app/src/fil/libre/repwifiapp/helpers/WpaSupplicant.java b/app/src/fil/libre/repwifiapp/helpers/WpaSupplicant.java
new file mode 100644
index 0000000..1dfe449
--- /dev/null
+++ b/app/src/fil/libre/repwifiapp/helpers/WpaSupplicant.java
@@ -0,0 +1,65 @@
+package fil.libre.repwifiapp.helpers;
+
+
+public abstract class WpaSupplicant {
+
+ public static final String INTERFACE_NAME = "wlan0";
+ public static final String WORKDIR = "/data/misc/wifi";
+ public static final String PID_FILE = WORKDIR + "/pidfile";
+ public static final String SOCKET_DIR = WORKDIR + "/sockets/";
+ public static final String SOFTAP_FILE = WORKDIR + "/softap.conf";
+ public static final String P2P_CONF = WORKDIR + "/p2p_supplicant.conf";
+ public static final String WPA_CONF = WORKDIR + "/wpa_supplicant.conf";
+ public static final String ENTROPY_FILE = WORKDIR + "/entropy.bin";
+ public static final String OVERLAY_FILE = "/system/etc/wifi/wpa_supplicant_overlay.conf";
+
+ protected static final String BASE_COMMNAD = "wpa_supplicant -B -dd -i" + INTERFACE_NAME + " -C" + SOCKET_DIR + " -P" + PID_FILE
+ + " -I" + OVERLAY_FILE + " -e" + ENTROPY_FILE;
+
+ public static boolean start() {
+
+ Utils.logDebug("startWpaSupplicant():");
+
+ // needs root (for wpa_supplicant)
+ if (RootCommand.executeRootCmd(BASE_COMMNAD)) {
+ return true;
+ } else {
+ Utils.logDebug("Failed to start wpa");
+ return false;
+ }
+
+ }
+
+ public static boolean kill(){
+ return RootCommand.executeRootCmd("killall -SIGINT wpa_supplicant");
+ }
+
+ public static boolean isRunning() {
+
+ boolean retval = false;
+
+ try {
+
+ RootCommand su = new RootCommand("pidof wpa_supplicant");
+ if (su.execute() == 0) {
+
+ if (su.getOutput().trim().equals("")) {
+ retval = false;
+ } else {
+ retval = true;
+ }
+
+ } else {
+ retval = false;
+ }
+
+ } catch (Exception e) {
+ Utils.logError("Exception during isWpaSupplicantRunning()", e);
+ retval = false;
+ }
+
+ return retval;
+
+ }
+
+}