aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/fil/libre/repwifiapp/helpers
diff options
context:
space:
mode:
Diffstat (limited to 'app/src/fil/libre/repwifiapp/helpers')
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/AccessPointInfo.java359
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/ConnectionStatus.java153
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/Engine.java859
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/Engine4p2.java131
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/Engine6p0.java715
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/IEngine.java39
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/NetworkButton.java26
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/NetworkManager.java546
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/RootCommand.java150
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/ShellCommand.java150
-rw-r--r--app/src/fil/libre/repwifiapp/helpers/Utils.java332
11 files changed, 1683 insertions, 1777 deletions
diff --git a/app/src/fil/libre/repwifiapp/helpers/AccessPointInfo.java b/app/src/fil/libre/repwifiapp/helpers/AccessPointInfo.java
index 65c8b24..d6e2eb3 100644
--- a/app/src/fil/libre/repwifiapp/helpers/AccessPointInfo.java
+++ b/app/src/fil/libre/repwifiapp/helpers/AccessPointInfo.java
@@ -24,173 +24,202 @@ import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import fil.libre.repwifiapp.Commons;
+public class AccessPointInfo implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+ private static final int MAX_SSID_LENGTH = 32;
+
+ private String _ssid;
+ private String _bssid;
+ private String _auth;
+ private String _level;
+ private String _freq;
+ private String _password;
+ private boolean _isHidden = false;
+ private long _lastTimeUsed;
+
+ public AccessPointInfo(String ssid, String bssid, String authType, String level, String freq) {
+
+ this._ssid = ssid;
+ this._bssid = bssid;
+ this._auth = authType;
+ this._level = level;
+ this._freq = freq;
+
+ }
+
+ public String getSsid() {
+ return this._ssid;
+ }
+
+ public String getSsid(int maxLength) {
+ String txt = getSsid();
+ if (maxLength > 4 && txt.length() > maxLength) {
+ txt = txt.substring(0, maxLength - 3) + "...";
+ }
+ return txt;
+ }
+
+ public void setHidden(boolean hidden) {
+ this._isHidden = hidden;
+ }
+
+ public boolean isHidden() {
+ return this._isHidden;
+ }
+
+ public String getBssid() {
+ return this._bssid;
+ }
+
+ public void setBssid(String bssid) {
+ this._bssid = bssid;
+ }
+
+ public String getAuthType() {
+ return this._auth;
+ }
+
+ public String getSignlalStrength() {
+ return this._level;
+ }
+
+ public String getFrequency() {
+ return this._freq;
+ }
+
+ public long getLastTimeUsed() {
+ return this._lastTimeUsed;
+ }
+
+ public void setLastTimeUsed(long timeStampInMillis) {
+ this._lastTimeUsed = timeStampInMillis;
+ }
+
+ public boolean isOlderThan(int days) {
+
+ if (this._lastTimeUsed == 0) {
+ return false;
+ }
+
+ long timeDiff = System.currentTimeMillis() - this._lastTimeUsed;
+ long spanMillis = Utils.daysToMilliseconds(days);
+
+ if (timeDiff > spanMillis) {
+ return true;
+ } else {
+ return false;
+ }
+
+ }
+
+ public String getPassword() {
+ return this._password;
+ }
+
+ public void setPassword(String password) {
+ this._password = password;
+ }
+
+ public boolean needsPassword() {
+
+ if ((this._auth == null) || (this._auth.equals(""))) {
+ // TODO
+ // check if default behavior should be with or without password,
+ // when no auth info is available.
+ return false;
+ }
+
+ if (this._auth.contains("WPA2") || this._auth.contains("WPA")) {
+ return true;
+ } else {
+ return false;
+ }
+
+ }
+
+ protected static AccessPointInfo parseLine(String line) {
+
+ try {
+
+ String[] params = line.split("\t");
+ if (params.length != 5) {
+ return null;
+ }
+
+ String bssid = params[0];
+ String freq = params[1];
+ String level = params[2];
+ String auth = params[3];
+ String ssid = params[4];
+
+ if (ssid.length() == 0 || ssid.length() > MAX_SSID_LENGTH) {
+ // invalid SSID.
+ return null;
+ }
+
+ AccessPointInfo info = new AccessPointInfo(ssid, bssid, auth, level, freq);
+ return info;
+
+ } catch (Exception e) {
+ Utils.logError("Error while parsing line: " + line, e);
+ return null;
+ }
+
+ }
+
+ public static AccessPointInfo[] parseScanResult(String scanResultFile) {
+
+ 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");
+ return null;
+ }
+
+ String[] lines = Utils.readFileLines(scanResultFile);
+ List<AccessPointInfo> nets = new ArrayList<AccessPointInfo>();
+
+ if (lines == null) {
+ return null;
+ }
+
+ for (String l : lines) {
+ if (l.startsWith(Commons.SCAN_FILE_HDR)) {
+ // strip off the header
+ continue;
+ }
+
+ if (l.trim().equals("")) {
+ // empty line, skip.
+ continue;
+ }
+
+ // try to parse line into network info
+ AccessPointInfo info = AccessPointInfo.parseLine(l);
+ if (info == null) {
+ Utils.logError("Failed to parse line into AccessPointInfo: " + l);
+ continue;
+ }
+
+ nets.add(info);
+
+ }
+
+ AccessPointInfo[] a = new AccessPointInfo[nets.size()];
+ a = nets.toArray(a);
+ return a;
+
+ } catch (Exception e) {
+ Utils.logError("Error while parsing scan results in class AccessPointInfo", e);
+ return null;
+ }
-public class AccessPointInfo implements Serializable{
-
- private static final long serialVersionUID = 1L;
-
- private String _ssid;
- private String _bssid;
- private String _auth;
- private String _level;
- private String _freq;
- private String _password;
- private long _lastTimeUsed;
-
- public AccessPointInfo(String ssid, String bssid, String authType, String level, String freq){
-
- this._ssid = ssid;
- this._bssid = bssid;
- this._auth = authType;
- this._level = level;
- this._freq = freq;
-
- }
-
- public String getSSID(){
- return this._ssid;
- }
-
- public String getBSSID(){
- return this._bssid;
- }
-
- public String getAuthType(){
- return this._auth;
- }
-
- public String getSignlalStrength(){
- return this._level;
- }
-
- public String getFrequency(){
- return this._freq;
- }
-
- public long getLastTimeUsed(){
- return this._lastTimeUsed;
- }
-
- public void setLastTimeUsed(long timeStampInMillis){
- this._lastTimeUsed = timeStampInMillis;
- }
-
- public boolean isOlderThan(int days){
-
- if (this._lastTimeUsed == 0){
- return false;
- }
-
- long timeDiff = System.currentTimeMillis() - this._lastTimeUsed;
- long spanMillis = Utils.daysToMilliseconds(days);
-
- if (timeDiff > spanMillis){
- return true;
- }else{
- return false;
- }
-
-
- }
-
- public String getPassword(){
- return this._password;
- }
-
- public void setPassword(String password){
- this._password = password;
- }
-
- public boolean needsPassword(){
-
- if ( (this._auth == null) || (this._auth.equals("")) ){
- //TODO
- //check if default behavior should be with or without password,
- //when no auth info is available.
- return false;
- }
-
- if (this._auth.contains("WPA2") || this._auth.contains("WPA")){
- return true;
- }
- else {
- return false;
- }
-
- }
-
- protected static AccessPointInfo parseLine(String line){
-
- try{
-
- String[] params = line.split("\t");
- if (params.length != 5){
- return null;
- }
-
- String bssid = params[0];
- String freq = params[1];
- String level = params[2];
- String auth = params[3];
- String ssid = params [4];
-
- AccessPointInfo info = new AccessPointInfo(ssid, bssid, auth, level, freq);
- return info;
-
- }catch (Exception e){
- Utils.logError("Error while parsing line: " + line, e);
- return null;
- }
-
- }
-
- public static AccessPointInfo[] parseScanResult(String scanResultFile){
-
- try {
-
- File f = new File(scanResultFile);
- if (! f.exists()){
- Utils.logError("AccessPointInfo.parseScanResult(): The provided scan result file doesn't exist");
- return null;
- }
-
- String[] lines = Utils.readFileLines(Commons.getScanFile());
- List<AccessPointInfo> nets = new ArrayList<AccessPointInfo>();
-
- for(String l : lines){
- if (l.startsWith(Commons.SCAN_FILE_HDR)){
- //strip off the header
- continue;
- }
-
- if (l.trim().equals("")){
- //empty line, skip.
- continue;
- }
-
- //try to parse line into network info
- AccessPointInfo info = AccessPointInfo.parseLine(l);
- if (info == null){
- Utils.logError("Failed to parse line into AccessPointInfo: " + l);
- continue;
- }
-
- nets.add(info);
-
- }
-
- AccessPointInfo[] a = new AccessPointInfo[nets.size()];
- a = nets.toArray(a);
- return a;
-
- } catch (Exception e) {
- Utils.logError("Error while parsing scan results in class AccessPointInfo",e);
- return null;
- }
-
- }
+ }
}
diff --git a/app/src/fil/libre/repwifiapp/helpers/ConnectionStatus.java b/app/src/fil/libre/repwifiapp/helpers/ConnectionStatus.java
index f7cb8d7..c26dae9 100644
--- a/app/src/fil/libre/repwifiapp/helpers/ConnectionStatus.java
+++ b/app/src/fil/libre/repwifiapp/helpers/ConnectionStatus.java
@@ -22,85 +22,82 @@ package fil.libre.repwifiapp.helpers;
import java.io.Serializable;
-public class ConnectionStatus implements Serializable{
+public class ConnectionStatus implements Serializable {
- /**
+ /**
*
*/
- private static final long serialVersionUID = 1L;
- public static final String STATUS_CONNECTED = "COMPLETED";
- public static final String STATUS_INACTIVE = "INACTIVE";
- public static final String STATUS_DISCONNECTED = "DISCONNECTED";
- public static final String STATUS_UNDEFINED = "UNDEFINED";
-
- public String status;
- 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";
- private static final String KeyBSSID = "bssid";
- private static final String KeyIP = "ip_address";
-
- public static ConnectionStatus parseWpaCliOutput(String wpaCliOutput){
-
- if (wpaCliOutput == null){
- return null;
- }
-
- if (wpaCliOutput.trim().length() == 0){
- return null;
- }
-
- String[] lines = wpaCliOutput.split("\n");
-
- ConnectionStatus s = new ConnectionStatus();
- for(String line : lines){
-
- if (line.trim().equals("")){
- continue;
- }
-
- String[] fields = line.split(F_SEP);
- if(fields.length < 2){
- continue;
- }
-
- String key = fields[0];
- String val = fields[1];
-
- if (key.equals(KeyBSSID)){
- s.BSSID = val;
- }
- else if (key.equals(KeySSID)){
- s.SSID = val;
- }
- else if (key.equals(KeyStatus)){
- s.status = val;
- }
- else if (key.equals(KeyIP)){
- s.IP = val;
- }
-
- }
-
- return s;
-
- }
-
- public boolean isConnected(){
-
- if (this.status == null){
- return false;
- }
-
- if (this.status.equals(STATUS_CONNECTED)){
- return true;
- }else{
- return false;
- }
- }
-
+ private static final long serialVersionUID = 1L;
+ public static final String STATUS_CONNECTED = "COMPLETED";
+ public static final String STATUS_INACTIVE = "INACTIVE";
+ public static final String STATUS_DISCONNECTED = "DISCONNECTED";
+ public static final String STATUS_UNDEFINED = "UNDEFINED";
+
+ public String status;
+ 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";
+ private static final String KeyBSSID = "bssid";
+ private static final String KeyIP = "ip_address";
+
+ public static ConnectionStatus parseWpaCliOutput(String wpaCliOutput) {
+
+ if (wpaCliOutput == null) {
+ return null;
+ }
+
+ if (wpaCliOutput.trim().length() == 0) {
+ return null;
+ }
+
+ String[] lines = wpaCliOutput.split("\n");
+
+ ConnectionStatus s = new ConnectionStatus();
+ for (String line : lines) {
+
+ if (line.trim().equals("")) {
+ continue;
+ }
+
+ String[] fields = line.split(F_SEP);
+ if (fields.length < 2) {
+ continue;
+ }
+
+ String key = fields[0];
+ String val = fields[1];
+
+ if (key.equals(KeyBSSID)) {
+ s.BSSID = val;
+ } else if (key.equals(KeySSID)) {
+ s.SSID = val;
+ } else if (key.equals(KeyStatus)) {
+ s.status = val;
+ } else if (key.equals(KeyIP)) {
+ s.IP = val;
+ }
+
+ }
+
+ return s;
+
+ }
+
+ public boolean isConnected() {
+
+ if (this.status == null) {
+ return false;
+ }
+
+ if (this.status.equals(STATUS_CONNECTED)) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
}
diff --git a/app/src/fil/libre/repwifiapp/helpers/Engine.java b/app/src/fil/libre/repwifiapp/helpers/Engine.java
index 5a2f2b2..68d8745 100644
--- a/app/src/fil/libre/repwifiapp/helpers/Engine.java
+++ b/app/src/fil/libre/repwifiapp/helpers/Engine.java
@@ -20,449 +20,450 @@
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 {
-public abstract class Engine implements IEngine{
-
- public static final String DNS1 = "193.183.98.154";
- public static final String DNS2 = "87.98.175.85";
-
- protected String getCmdWpaSup(){
- return "wpa_supplicant -B -dd -i" + Commons.INTERFACE_NAME + " -C\"" +Commons.SOCKET_DIR + "\" -P\"" + Commons.PID_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 killPreviousConnections() {
-
- //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??? --- Fil
- if (! clearWorkingDir()){
- Utils.logError("Failed clearing dir");
- return null;
- }
-
- if (! startWpaSupplicant()){
- Utils.logError("Failed starting wpa_supplicant");
- return null;
- }
-
- if (! createScanScripts()){
- Utils.logError("Failed creating scripts");
- return null;
- }
-
- if (! scanNetworks()){
- Utils.logError("failed scanning networks");
- return null;
- }
-
- if (!getScanResults()){
- 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());
- if (a == null){
- Utils.logError("Unable to parse scan file into AccessPointInfo array");
- }
-
- return a;
-
- }
-
- @Override
- public abstract boolean connect(AccessPointInfo info);
-
- @Override
- public boolean disconnect(){
-
- //needs root (for wpa_cli)
-
- if (! isWpaSupplicantRunning()){
- return true;
- }
-
- try {
-
- 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;
- }
- }
-
- /***
- * returns null if unable to determine connection status for any reason.
- */
- @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;
- }
-
- }
-
- @Override
- public boolean isInterfaceAvailable(String ifaceName){
-
- String[]ifaces = getAvailableInterfaces();
- if(ifaces == null || ifaces.length == 0){
- return false;
- }
-
- for(String name : ifaces){
- if (name.equals(ifaceName)){
- return true;
- }
- }
-
- return false;
- }
-
- @Override
- public String[] getAvailableInterfaces(){
-
- try {
-
- 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);
-
- }
-
- 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)
- return executeRootCmd("bash " + Commons.getScriptScanRes());
-
- }
-
- 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" +
- "sleep 1s\n";
+ 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;
+ }
-
- if (! Utils.writeFile(Commons.getScriptScan(),scan,true) ){
+ protected String getCmdWpaCli() {
+ return "wpa_cli -p" + Commons.SOCKET_DIR + " -P" + Commons.PID_FILE + " -i"
+ + Commons.INTERFACE_NAME;
+ }
- Exception e = Utils.getLastException();
- if (e != null){
- Utils.logError("Error while writing scan script.",e);
- }
+ protected abstract String getCmdWpaStart();
- return false;
- }
+ public boolean deleteFileIfExists(String filePath) {
-
- if (! Utils.writeFile(Commons.getScriptScanRes(),scanRes,true) ){
+ if (filePath == null) {
+ return false;
+ }
- Exception e = Utils.getLastException();
- if (e != null){
- Utils.logError("Error while writing getScanResults script.",e);
- }
+ if (filePath.contains("*")) {
+ // it's safer to reject bulk rm'ing
+ return false;
+ }
- 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");
- return true;
+ }
- } catch (Exception e) {
+ public boolean chmodFile(String filePath, String mod) {
+ // needs root (chmod)
+ return executeRootCmd("chmod " + mod + " \"" + filePath + "\"");
+ }
- Utils.logError("Error while creating the scanning script.",e);
- return false;
- }
+ @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()) {
+ Utils.logError("Failed starting wpa_supplicant");
+ return null;
+ }
+
+ if (!createScanScripts()) {
+ Utils.logError("Failed creating scripts");
+ return null;
+ }
+
+ if (!scanNetworks()) {
+ Utils.logError("failed scanning networks");
+ return null;
+ }
+
+ if (!getScanResults()) {
+ 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());
+ if (a == null) {
+ Utils.logError("Unable to parse scan file into AccessPointInfo array");
+ return a;
+ }
+
+ Utils.logDebug("# of APs found: " + a.length);
+
+ return a;
+
+ }
+
+ @Override
+ public abstract boolean connect(AccessPointInfo info);
+
+ @Override
+ public boolean disconnect() {
+
+ // needs root (for wpa_cli)
+
+ if (!isWpaSupplicantRunning()) {
+ return true;
+ }
+
+ try {
+
+ 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;
+ }
+ }
+
+ /***
+ * returns null if unable to determine connection status for any reason.
+ */
+ @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;
+ }
+
+ }
+
+ @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();
+ String nm = nif.getName();
+ if (nm.equals(ifaceName)) {
+ return true;
+ }
+ }
+ return false;
+
+ }
+
+ @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);
+
+ }
+
+ 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;
+ }
+
+ }
}
diff --git a/app/src/fil/libre/repwifiapp/helpers/Engine4p2.java b/app/src/fil/libre/repwifiapp/helpers/Engine4p2.java
deleted file mode 100644
index 12d8da8..0000000
--- a/app/src/fil/libre/repwifiapp/helpers/Engine4p2.java
+++ /dev/null
@@ -1,131 +0,0 @@
-//
-// 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 fil.libre.repwifiapp.Commons;
-
-
-public class Engine4p2 extends Engine{
-
- @Override
- protected String getCmdWpaStart(){
- return "wpa_supplicant -B -dd -i" + Commons.INTERFACE_NAME + " -C\"" + Commons.SOCKET_DIR + "\" -c\"" + Commons.WPA_CONF + "\" -P\"" + Commons.PID_FILE + "\"";
- }
-
- public boolean loadModules(){
- try {
- //TODO
- //implement kernel modules loading
- return true;
- } catch (Exception e) {
- Utils.logError("Error while loading kernel modules",e);
- return false;
- }
- }
-
- @Override
- public boolean connect(AccessPointInfo info){
-
- killPreviousConnections();
-
- if (info == null){
- Utils.logDebug("Engine's connect() received a null AccessPointInfo");
- return false;
- }
-
- if (! createConfigFile(info)){
- return false;
- }
-
- //launch wpa_supplicant specifying our custom configuration and the socket file
- if (! executeRootCmd(getCmdWpaStart())){
- Utils.logError("wpa_supplicant connection command failed.");
- return false;
- }
-
- //negotiate DHCP lease
- if (!runDhcpcd()){
- return false;
- }
-
- //set DNS's
- if (! executeRootCmd("setprop net.dns1 " + DNS1)){
- Utils.logError("setting dns1 failed");
- return false;
- }
-
- if (! executeRootCmd("setprop net.dns2 " + DNS2)){
- Utils.logError("setting dns2 failed");
- return false;
- }
-
- //TODO
- //implement wpa_cli command to query wpa_supplicant's state
- //in order to confirm that connection was successful.
-
- return true;
-
- }
-
- private boolean createConfigFile(AccessPointInfo info){
-
- try {
-
- if (! deleteFileIfExists(Commons.WPA_CONF)){
- Utils.logError("Unable to remove wpa_supplicant.conf before writing it.");
- return false;
- }
-
- String configText = "ctrl_interface=DIR=" + Commons.SOCKET_DIR + "\n" +
- "update_config=1\n" +
- "network={\n"+
- " ssid=\"" + info.getSSID() + "\"\n";
-
- if (info.needsPassword()){
- configText += " psk=\""+ info.getPassword() + "\"\n";
- }else {
- configText += " key_mgmt=NONE\n";
- }
-
- configText += "}\n";
-
- if ( ! Utils.writeFile(Commons.WPA_CONF, configText, true) ){
- Utils.logError("Unable to write wpa_supplicant.conf file!");
- return false;
- }
-
- //chmod wpa_supplicant.conf, in order to make it accessible
- if(chmodFile(Commons.WPA_CONF, "666")){
- return true;
- }else {
- Utils.logError("Unable to chmod wpa_supplicant.conf");
- return false;
- }
-
- } catch (Exception e) {
- Utils.logError("Error while creating wpa_supplicant.conf",e);
- return false;
- }
-
- }
-
-
-}
diff --git a/app/src/fil/libre/repwifiapp/helpers/Engine6p0.java b/app/src/fil/libre/repwifiapp/helpers/Engine6p0.java
index 9cbfeaf..d4ff0f7 100644
--- a/app/src/fil/libre/repwifiapp/helpers/Engine6p0.java
+++ b/app/src/fil/libre/repwifiapp/helpers/Engine6p0.java
@@ -20,352 +20,377 @@
package fil.libre.repwifiapp.helpers;
+import org.apache.http.conn.util.InetAddressUtils;
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();
+
+ if (info == null) {
+ Utils.logDebug("Engine's connect() received a null AccessPointInfo");
+ return false;
+ }
+
+ // clear any previously set network
+ if (!destroyNetwork()) {
+ Utils.logDebug("Unable to ndc destroy network");
+ return false;
+ }
+
+ // clear interface's ip
+ if (!clearAddrs()) {
+ Utils.logDebug("Unable to ndc clearaddrs");
+ return false;
+ }
+
+ // bring up interface
+ if (!interfaceUp()) {
+ Utils.logDebug("Unable to bring up interface.");
+ return false;
+ }
+
+ // launch wpa_supplicant specifying our custom configuration and the
+ // socket file
+ if (!executeRootCmd(getCmdWpaStart())) {
+ Utils.logDebug("Unable to run wpa start");
+ return false;
+ }
+
+ // create new network and get network id
+ String netID = createNetworkGetId();
+ if (netID == null) {
+ Utils.logDebug("Unable to fetch network id");
+ return false;
+ }
+
+ // set network SSID
+ if (!setNetworkSSID(info.getSsid(), netID)) {
+ Utils.logDebug("Failed to set network ssid");
+ return false;
+ }
+
+ if (info.isHidden() && !setNetworkScanSSID(netID)) {
+ Utils.logDebug("Failed to set scan_ssid 1 for hidden network.");
+ return false;
+ }
+
+ // set password (if any)
+ if (!setNetworkPSK(info, netID)) {
+ Utils.logDebug("Failed to set network psk");
+ return false;
+ }
+
+ // select the network we just created
+ if (!selectNetwork(netID)) {
+ Utils.logDebug("Unable to wpa_cli select network");
+ return false;
+ }
+
+ // enable the newtork
+ if (!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; }
+ */
+
+ // get DHCP
+ Utils.logDebug("Attempt to run dhcpcd..");
+ if (!runDhcpcd()) {
+ Utils.logDebug("Failed to run dhcpcd");
+ return false;
+ }
+
+ // try to fetch gateway
+ String gw = getGateway();
+ if (gw == null || gw.trim().length() < 7) {
+ // failed to get gateway
+ Utils.logDebug("Failed to get gateway");
+ return false;
+ }
+
+ if (!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)) {
+ 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)) {
+ Utils.logDebug("Failed to add route to gateway");
+ return false;
+ }
+
+ if (!setDns(Commons.getDnss(), gw)) {
+ Utils.logDebug("Failed to set DNS");
+ return false;
+ }
+
+ // use network
+ if (!executeRootCmd("ndc network default set 1")) {
+ Utils.logDebug("Failed to set network as default");
+ return false;
+ }
+
+ return true;
+
+ }
+
+ 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;
+ }
+
+ }
+
+ private boolean setDns(String[] dnss, String gateway) {
+
+ if (dnss == null || dnss.length == 0) {
+ // the DNS setting has been left blank
+ // try to use the gateway as dns
+
+ if (gateway == null || gateway.length() == 0) {
+ // no possible DNS.
+ return false;
+ }
+
+ dnss = new String[] { gateway, gateway };
+
+ }
+
+ if (!InetAddressUtils.isIPv4Address(dnss[0])) {
+ // invalid ip can't proceed.
+ return false;
+ }
+
+ String cmd = "ndc resolver setnetdns 1 " + dnss[0];
+
+ if (dnss.length > 1 && InetAddressUtils.isIPv4Address(dnss[1])) {
+ cmd += " " + dnss[1];
+ } else {
+ cmd += " " + dnss[0];
+ }
+
+ return executeRootCmd(cmd);
+ }
+
+ private String getGateway() {
+
+ try {
+
+ // doesn't need root (tested)
+ RootCommand cmd = new RootCommand("ip route show dev " + Commons.INTERFACE_NAME);
+ if (cmd.execute() != 0) {
+ Utils.logDebug("command failed show route");
+ return null;
+ }
+
+ // read command output
+ String out = cmd.getOutput();
+ if (out == null) {
+ return null;
+ }
+
+ String[] lines = out.split("\n");
+
+ for (String l : lines) {
+
+ if (l.contains("default via")) {
+
+ String[] f = l.split(" ");
+ if (f.length > 2) {
+
+ // found route's address:
+ return f[2];
+
+ }
+ }
+ }
+
+ return null;
+
+ } catch (Exception e) {
+ Utils.logError("Error while trying to fetch route", e);
+ return null;
+ }
+
+ }
+
+ private boolean clearAddrs() {
+ // needs root (tested)
+ return executeRootCmd("ndc interface clearaddrs " + Commons.INTERFACE_NAME);
+ }
-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){
-
- killPreviousConnections();
-
- if (info == null){
- Utils.logDebug("Engine's connect() received a null AccessPointInfo");
- return false;
- }
-
- //clear any previously set network
- if (! destroyNetwork()){
- Utils.logDebug("Unable to ndc destroy network");
- return false;
- }
-
- //clear interface's ip
- if (! clearAddrs()){
- Utils.logDebug("Unable to ndc clearaddrs");
- return false;
- }
-
- //bring up interface
- if(! interfaceUp()){
- Utils.logDebug("Unable to bring up interface.");
- return false;
- }
-
- //launch wpa_supplicant specifying our custom configuration and the socket file
- if (! executeRootCmd(getCmdWpaStart())){
- Utils.logDebug("Unable to run wpa start");
- return false;
- }
-
- //create new network and get network id
- String netID = createNetworkGetId();
- if (netID == null){
- Utils.logDebug("Unable to fetch network id");
- return false;
- }
-
- //set network SSID
- if (! setNetworkSSID(info.getSSID(), netID)){
- Utils.logDebug("Failed to set network ssid");
- return false;
- }
-
- //set password (if any)
- if(! setNetworkPSK(info, netID)){
- Utils.logDebug("Failed to set network psk");
- return false;
- }
-
- // select the network we just created
- if (! selectNetwork(netID)){
- Utils.logDebug("Unable to wpa_cli select network");
- return false;
- }
-
- //enable the newtork
- if (! 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;
- }
-
- //get DHCP
- Utils.logDebug("Attempt to run dhcpcd..");
- if (!runDhcpcd()){
- Utils.logDebug("Failed to run dhcpcd");
- return false;
- }
-
- //try to fetch gateway
- String gw = getGateway();
- if (gw == null || gw.trim().length() < 7){
- //failed to get gateway
- Utils.logDebug("Failed to get gateway");
- return false;
- }
-
- if (! 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)){
- 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)){
- Utils.logDebug("Failed to add route to gateway");
- return false;
- }
-
- //set DNS
- if (! executeRootCmd("ndc resolver setnetdns 1 " + " " + DNS1 + " " + DNS2)){
- Utils.logDebug("Failed to set DNS");
- return false;
- }
-
- //use network
- if (! executeRootCmd("ndc network default set 1")){
- Utils.logDebug("Failed to set network as default");
- return false;
- }
-
- //TODO
- //implement wpa_cli query for status
- //in order to be sure that connection is extablished
-
- return true;
-
-
-
- }
-
- 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 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;
- }
-
- }
-
- private boolean reassociate(){
-
- try {
-
- //needs root (wpa_cli)
-
- RootCommand su = new RootCommand(getCmdWpaCli() + " reassociate");
- 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 reassociating network", e);
- return false;
- }
-
- }
-
- private String getGateway(){
-
- try {
-
- //doesn't need root (tested)
- ShellCommand cmd = new ShellCommand("ip route show dev " + Commons.INTERFACE_NAME);
- if (cmd.execute() != 0){
- Utils.logDebug("command failed show route");
- return null;
- }
-
- //read command output
- String out = cmd.getOutput();
- if (out == null){
- return null;
- }
-
- String[] lines = out.split("\n");
-
- for (String l : lines){
-
- if (l.contains("default via")){
-
- String[] f = l.split(" ");
- if (f.length > 2){
-
- //found route's address:
- return f[2];
-
- }
- }
- }
-
- return null;
-
- } catch (Exception e) {
- Utils.logError("Error while trying to fetch route",e);
- return null;
- }
-
- }
-
- private boolean clearAddrs(){
- //needs root (tested)
- return executeRootCmd("ndc interface clearaddrs " + Commons.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 1e33f1c..037cf62 100644
--- a/app/src/fil/libre/repwifiapp/helpers/IEngine.java
+++ b/app/src/fil/libre/repwifiapp/helpers/IEngine.java
@@ -20,25 +20,26 @@
package fil.libre.repwifiapp.helpers;
+import java.net.SocketException;
public interface IEngine {
-
- public boolean startWpaSupplicant();
-
- public boolean killPreviousConnections();
-
- public boolean clearWorkingDir();
-
- public AccessPointInfo[] getAvailableNetworks();
-
- public boolean connect(AccessPointInfo info);
-
- public boolean disconnect();
-
- public ConnectionStatus getConnectionStatus();
-
- public boolean isInterfaceAvailable(String ifaceName);
-
- public String[] getAvailableInterfaces();
-
+
+ public boolean startWpaSupplicant();
+
+ public boolean killBackEndProcesses();
+
+ public boolean clearWorkingDir();
+
+ public AccessPointInfo[] getAvailableNetworks();
+
+ public boolean connect(AccessPointInfo info);
+
+ public boolean disconnect();
+
+ public ConnectionStatus getConnectionStatus();
+
+ public boolean isInterfaceAvailable(String ifaceName) throws SocketException;
+
+ public String[] getAvailableInterfaces();
+
}
diff --git a/app/src/fil/libre/repwifiapp/helpers/NetworkButton.java b/app/src/fil/libre/repwifiapp/helpers/NetworkButton.java
index 9a7c523..7d0bdf9 100644
--- a/app/src/fil/libre/repwifiapp/helpers/NetworkButton.java
+++ b/app/src/fil/libre/repwifiapp/helpers/NetworkButton.java
@@ -23,19 +23,17 @@ package fil.libre.repwifiapp.helpers;
import android.content.Context;
import android.widget.Button;
-public class NetworkButton extends Button{
+public class NetworkButton extends Button {
+
+ private String _bssid = "";
+
+ public NetworkButton(Context context, String networkBSSID) {
+ super(context);
+ this._bssid = networkBSSID;
+ }
+
+ public String getNetworkBSSID() {
+ return this._bssid;
+ }
- private String _bssid = "";
-
- public NetworkButton(Context context, String networkBSSID){
- super(context);
- this._bssid = networkBSSID;
- }
-
- public String getNetworkBSSID(){
- return this._bssid;
- }
-
-
-
}
diff --git a/app/src/fil/libre/repwifiapp/helpers/NetworkManager.java b/app/src/fil/libre/repwifiapp/helpers/NetworkManager.java
index 33acbb7..db27f7e 100644
--- a/app/src/fil/libre/repwifiapp/helpers/NetworkManager.java
+++ b/app/src/fil/libre/repwifiapp/helpers/NetworkManager.java
@@ -25,272 +25,282 @@ import java.util.ArrayList;
public class NetworkManager {
- private static final String F_SEP = "\t";
- private static final int NET_MAX_AGE = 365; //Expressed in days
-
- private String _knownNetworksFile = null;
-
- public NetworkManager(String networksFilePath){
- this._knownNetworksFile = networksFilePath;
- }
-
- private AccessPointInfo searchInFile(AccessPointInfo i){
-
- if (i == null){
- return null;
- }
-
- String bssid = i.getBSSID();
- String ssid = i.getSSID();
-
- if (bssid == null || ssid == null || bssid.trim().equals("") || ssid.trim().equals("")){
- return null;
- }
-
- AccessPointInfo ret = null;
- AccessPointInfo[] list = getKnownNetworks();
-
- if (list == null){
- return null;
- }
-
- for(AccessPointInfo toTest : list){
-
- // try to match both bssid and ssid.
- // if bssid doesn't match, but ssid does,
- // then the network is a candidate.
- // if no bssid equality is found,
- // then return the best match (only ssid), if any
- if (toTest.getSSID().equals(ssid)){
-
- if (toTest.getBSSID().equals(bssid)){
- i.setPassword(toTest.getPassword());
- return i;
-
- }else{
- i.setPassword(toTest.getPassword());
- ret = i;
- }
-
- }
-
- }
-
- return ret;
-
- }
-
- 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>();
-
- if (existingNets == null || existingNets.length == 0){
- //no existing storage yet, create it
-
- if (save){
- //set timestamp
- info.setLastTimeUsed(System.currentTimeMillis());
- newlist.add(info);
- AccessPointInfo[] newContents = new AccessPointInfo[newlist.size()];
- newContents = newlist.toArray(newContents);
-
- return saveList(newContents);
-
- }else{
- //nothing to do, return
- return true;
- }
-
- }
-
-
- if (save){
- //add the updated info to the storage
- info.setLastTimeUsed(System.currentTimeMillis());
- newlist.add(info);
- }
-
- for(AccessPointInfo old : existingNets){
-
- if (old == null){
- //error while loading from file. skip.
- continue;
- }
-
- // keep network only if it's not older than the max age for a network
- else if (old.isOlderThan(NET_MAX_AGE)){
- //skip it
- continue;
- }
-
- else if (old.getBSSID().equals(info.getBSSID()) && old.getSSID().equals(info.getSSID())){
- //found previously saved entry for the same network we are managing
- //skip it
- continue;
- }
-
- else{
- //old network info that can be kept in the storage
- newlist.add(old);
- }
-
- }
-
-
- AccessPointInfo[] newContents = new AccessPointInfo[newlist.size()];
- newContents = newlist.toArray(newContents);
-
- return saveList(newContents);
-
- }
-
- private AccessPointInfo getFromString(String savedString){
-
- if (savedString == null || savedString.trim().equals("")) {
- return null;
- }
-
- String[] fields = savedString.split(F_SEP);
-
- if (fields.length != 4 ){
- return null;
- }
-
- String bssid = fields[0];
- String ssid = fields[1];
- String pass = fields[2];
- String lastUsed = fields[3];
-
- long lastusedmillis = 0;
- try {
- lastusedmillis = Long.parseLong(lastUsed);
- } catch (NumberFormatException e) {
- //invalid format
- Utils.logError("Invalid time format in network manager \""+lastUsed +"\". Network BSSID: " + bssid, e);
- }
-
- if (bssid.trim().equals("") || ssid.trim().equals("") || pass.trim().equals("")){
- return null;
- }
-
- AccessPointInfo i = new AccessPointInfo(ssid, bssid, null, null, null);
- i.setPassword(pass);
- i.setLastTimeUsed(lastusedmillis);
-
- return i;
-
- }
-
- private String InfoToString(AccessPointInfo info){
-
- if (info == null){
- return null;
- }
-
- String bssid = info.getBSSID();
- String ssid = info.getSSID();
- String pass = info.getPassword();
- String tsLastUsed = "" + info.getLastTimeUsed();
-
- if (bssid == null || bssid.trim().equals("")){
- return null;
- }
-
- if (ssid == null || ssid.trim().equals("")){
- return null;
- }
-
- if (pass == null || pass.trim().equals("")){
- return null;
- }
-
- String iText = info.getBSSID() + F_SEP + info.getSSID() + F_SEP + info.getPassword() + F_SEP + tsLastUsed;
- return iText;
-
- }
-
- private boolean saveList(AccessPointInfo[] list){
-
- 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);
-
- }
-
- public AccessPointInfo[] getKnownNetworks(){
-
- ArrayList<AccessPointInfo> list = new ArrayList<AccessPointInfo>();
-
- File f = new File(this._knownNetworksFile);
- if (! f.exists()){
- return null;
- }
-
- String[] lines = Utils.readFileLines(_knownNetworksFile);
- if (lines == null || lines.length == 0){
- return null;
- }
-
- for(String l : lines){
-
- AccessPointInfo info = getFromString(l);
- if (info != null){
- list.add(info);
- }
-
- }
-
- AccessPointInfo[] ret = new AccessPointInfo[list.size()];
- ret = list.toArray(ret);
-
- return ret;
-
- }
-
- public boolean isKnown(AccessPointInfo info){
-
- AccessPointInfo i = searchInFile(info);
- if (i == null){
- return false;
- }else {
- return true;
- }
-
- }
-
- public boolean save(AccessPointInfo info){
- return saveOrRemove(info, true);
- }
-
- public boolean remove(AccessPointInfo info){
- return saveOrRemove(info, false);
- }
-
- public AccessPointInfo getSavedNetwork(AccessPointInfo i){
- return searchInFile(i);
- }
-
-
-
+ private static final String F_SEP = "\t";
+ private static final int NET_MAX_AGE = 365; // Expressed in days
+
+ private String _knownNetworksFile = null;
+
+ public NetworkManager(String networksFilePath) {
+ this._knownNetworksFile = networksFilePath;
+ }
+
+ private AccessPointInfo searchInFile(AccessPointInfo i) {
+
+ if (i == null) {
+ return null;
+ }
+
+ String bssid = i.getBssid();
+ String ssid = i.getSsid();
+
+ if (bssid == null || ssid == null || bssid.trim().equals("") || ssid.trim().equals("")) {
+ return null;
+ }
+
+ AccessPointInfo ret = null;
+ AccessPointInfo[] list = getKnownNetworks();
+
+ if (list == null) {
+ return null;
+ }
+
+ for (AccessPointInfo toTest : list) {
+
+ // try to match both bssid and ssid.
+ // if bssid doesn't match, but ssid does,
+ // then the network is a candidate.
+ // if no bssid equality is found,
+ // then return the best match (only ssid), if any
+ if (toTest.getSsid().equals(ssid)) {
+
+ if (toTest.getBssid().equals(bssid)) {
+ i.setPassword(toTest.getPassword());
+ return i;
+
+ } else {
+ i.setPassword(toTest.getPassword());
+ ret = i;
+ }
+
+ }
+
+ }
+
+ return ret;
+
+ }
+
+ 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>();
+
+ if (existingNets == null || existingNets.length == 0) {
+ // no existing storage yet, create it
+
+ if (save) {
+ // set timestamp
+ info.setLastTimeUsed(System.currentTimeMillis());
+ newlist.add(info);
+ AccessPointInfo[] newContents = new AccessPointInfo[newlist.size()];
+ newContents = newlist.toArray(newContents);
+
+ return saveList(newContents);
+
+ } else {
+ // nothing to do, return
+ return true;
+ }
+
+ }
+
+ if (save) {
+ // add the updated info to the storage
+ info.setLastTimeUsed(System.currentTimeMillis());
+ newlist.add(info);
+ }
+
+ for (AccessPointInfo old : existingNets) {
+
+ if (old == null) {
+ // error while loading from file. skip.
+ continue;
+ }
+
+ // keep network only if it's not older than the max age for a
+ // network
+ else if (old.isOlderThan(NET_MAX_AGE)) {
+ // skip it
+ continue;
+ }
+
+ else if (old.getBssid().equals(info.getBssid()) && old.getSsid().equals(info.getSsid())) {
+ // found previously saved entry for the same network we are
+ // managing
+ // skip it
+ continue;
+ }
+
+ else {
+ // old network info that can be kept in the storage
+ newlist.add(old);
+ }
+
+ }
+
+ AccessPointInfo[] newContents = new AccessPointInfo[newlist.size()];
+ newContents = newlist.toArray(newContents);
+
+ return saveList(newContents);
+
+ }
+
+ private AccessPointInfo getFromString(String savedString) {
+
+ if (savedString == null || savedString.trim().equals("")) {
+ return null;
+ }
+
+ String[] fields = savedString.split(F_SEP);
+
+ if (fields.length < 4) {
+ return null;
+ }
+
+ String bssid = fields[0];
+ String ssid = fields[1];
+ String pass = fields[2];
+ String lastUsed = fields[3];
+ String auth = null;
+
+ if (fields.length > 4) {
+ auth = fields[4];
+ }
+
+ long lastusedmillis = 0;
+ try {
+ lastusedmillis = Long.parseLong(lastUsed);
+ } catch (NumberFormatException e) {
+ // invalid format
+ Utils.logError("Invalid time format in network manager \"" + lastUsed
+ + "\". Network BSSID: " + bssid, e);
+ }
+
+ if (bssid.trim().equals("") || ssid.trim().equals("") || pass.trim().equals("")) {
+ return null;
+ }
+
+ AccessPointInfo i = new AccessPointInfo(ssid, bssid, auth, null, null);
+ i.setPassword(pass);
+ i.setLastTimeUsed(lastusedmillis);
+
+ return i;
+
+ }
+
+ private String InfoToString(AccessPointInfo info) {
+
+ if (info == null) {
+ return null;
+ }
+
+ String bssid = info.getBssid();
+ String ssid = info.getSsid();
+ String pass = info.getPassword();
+ String tsLastUsed = "" + info.getLastTimeUsed();
+ String auth = info.getAuthType();
+
+ if (bssid == null || bssid.trim().equals("")) {
+ return null;
+ }
+
+ if (ssid == null || ssid.trim().equals("")) {
+ return null;
+ }
+
+ if (pass == null || pass.trim().equals("")) {
+ return null;
+ }
+
+ if (auth == null) {
+ auth = "";
+ }
+
+ String iText = info.getBssid() + F_SEP + info.getSsid() + F_SEP + info.getPassword()
+ + F_SEP + tsLastUsed + F_SEP + auth;
+ return iText;
+
+ }
+
+ private boolean saveList(AccessPointInfo[] list) {
+
+ 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);
+
+ }
+
+ public AccessPointInfo[] getKnownNetworks() {
+
+ ArrayList<AccessPointInfo> list = new ArrayList<AccessPointInfo>();
+
+ File f = new File(this._knownNetworksFile);
+ if (!f.exists()) {
+ return null;
+ }
+
+ String[] lines = Utils.readFileLines(_knownNetworksFile);
+ if (lines == null || lines.length == 0) {
+ return null;
+ }
+
+ for (String l : lines) {
+
+ AccessPointInfo info = getFromString(l);
+ if (info != null) {
+ list.add(info);
+ }
+
+ }
+
+ AccessPointInfo[] ret = new AccessPointInfo[list.size()];
+ ret = list.toArray(ret);
+
+ return ret;
+
+ }
+
+ public boolean isKnown(AccessPointInfo info) {
+
+ AccessPointInfo i = searchInFile(info);
+ if (i == null) {
+ return false;
+ } else {
+ return true;
+ }
+
+ }
+
+ public boolean save(AccessPointInfo info) {
+ return saveOrRemove(info, true);
+ }
+
+ public boolean remove(AccessPointInfo info) {
+ return saveOrRemove(info, false);
+ }
+
+ public AccessPointInfo getSavedNetwork(AccessPointInfo i) {
+ return searchInFile(i);
+ }
+
}
diff --git a/app/src/fil/libre/repwifiapp/helpers/RootCommand.java b/app/src/fil/libre/repwifiapp/helpers/RootCommand.java
index bcb6d0f..9d9f7d3 100644
--- a/app/src/fil/libre/repwifiapp/helpers/RootCommand.java
+++ b/app/src/fil/libre/repwifiapp/helpers/RootCommand.java
@@ -19,91 +19,75 @@
// ********************************************************************
package fil.libre.repwifiapp.helpers;
-import java.io.BufferedReader;
+
import java.io.DataOutputStream;
import java.io.InputStream;
-import java.io.InputStreamReader;
-
import fil.libre.repwifiapp.Commons;
-public class RootCommand {
-
- private String _cmdOut = "";
- private String _cmdTxt = "";
-
- public RootCommand(String commandText){
- this._cmdTxt = commandText;
- }
-
- public int execute() throws Exception{
- return execute(0);
- }
-
- public int execute(int sleepSecsAfterCmd) throws Exception{
-
- Process su = Runtime.getRuntime().exec("su");
-
- DataOutputStream stdin = new DataOutputStream(su.getOutputStream());
- InputStream os = su.getInputStream();
- BufferedReader stdOut = new BufferedReader(new InputStreamReader(os));
- InputStream es = su.getErrorStream();
- BufferedReader stdError = new BufferedReader(new InputStreamReader(es));
-
- if ( this._cmdTxt != null ){
-
- Utils.logDebug("SU:EXEC: " + this._cmdTxt);
-
- this._cmdTxt += " > " + Commons.getTempOutFile();
-
- stdin.writeBytes(this._cmdTxt + "\n");
- stdin.flush();
- }
-
- /* if (sleepSecsAfterCmd > 0){
- Thread.sleep(sleepSecsAfterCmd * 1000);
- }*/
-
- StringBuilder sb = new StringBuilder();
- String s = null;
-
- while ( (es.available() > 0) && (s = stdError.readLine()) != null) {
- sb.append(s + "\n");
- }
-
- while ( (os.available() > 0) && (s = stdOut.readLine()) != null) {
- sb.append(s + "\n");
- }
-
- this._cmdOut = sb.toString();
-
- stdin.writeBytes("exit\n");
- stdin.flush();
-
- int res = su.waitFor();
-
- Utils.logDebug("OUT: " + getOutput());
-
- return res;
-
- }
-
- public String getOutput(){
-
- String[] lastOut = Utils.readFileLines(Commons.getTempOutFile());
- if (lastOut == null){
- return this._cmdOut;
- }
-
- String fout = "";
-
- for (String s : lastOut){
- fout += s + "\n";
- }
-
- return fout;
-
- }
-
-
-
+public class RootCommand extends ShellCommand {
+
+ public RootCommand(String commandText) {
+ super(commandText);
+ this._cmdTxt = commandText;
+ }
+
+ @Override
+ public int execute() throws Exception {
+
+ 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);
+
+ this._cmdTxt += " > " + Commons.getTempOutFile();
+
+ stdin.writeBytes(this._cmdTxt + "\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));
+
+ Utils.logDebug("OUT: " + getOutput());
+
+ return res;
+
+ }
+
+ @Override
+ public String getOutput() {
+
+ 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/ShellCommand.java b/app/src/fil/libre/repwifiapp/helpers/ShellCommand.java
index e2004a7..fbeb719 100644
--- a/app/src/fil/libre/repwifiapp/helpers/ShellCommand.java
+++ b/app/src/fil/libre/repwifiapp/helpers/ShellCommand.java
@@ -4,82 +4,78 @@ import java.io.IOException;
import java.io.InputStream;
public class ShellCommand {
-
- private String _cmdOut = "";
- private String _cmdTxt = "";
-
- public ShellCommand(String commandText){
- this._cmdTxt = commandText;
- }
-
-
- public int execute() throws Exception{
-
- if ( this._cmdTxt == null ){
- return -9;
- }
-
- Utils.logDebug("EXEC: " + this._cmdTxt);
-
- Process cmd = Runtime.getRuntime().exec(this._cmdTxt);
-
- InputStream os = cmd.getInputStream();
- InputStream es = cmd.getErrorStream();
-
- StringBuilder sb = new StringBuilder();
-
- sb.append(getStringFromStream(es));
- sb.append(getStringFromStream(os));
-
- int res = cmd.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("EXITCODE: " + res);
- Utils.logDebug("OUT: " + getOutput());
-
- return res;
-
- }
-
- private String getStringFromStream(InputStream s) throws IOException{
-
- StringBuilder sb = new StringBuilder();
- while ( (s.available() > 0) ) {
- int b = s.read();
- if (b>=0){
- sb.append((char)b);
- }else{
- break;
- }
- }
-
- return sb.toString();
-
- }
-
-
- public String getOutput(){
-
- 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;*/
-
- }
+
+ protected String _cmdOut = "";
+ protected String _cmdTxt = "";
+
+ public ShellCommand(String commandText) {
+ this._cmdTxt = commandText;
+ }
+
+ public int execute() throws Exception {
+
+ if (this._cmdTxt == null) {
+ return -9;
+ }
+
+ Utils.logDebug("EXEC: " + this._cmdTxt);
+
+ Process cmd = Runtime.getRuntime().exec(this._cmdTxt);
+
+ InputStream os = cmd.getInputStream();
+ InputStream es = cmd.getErrorStream();
+
+ StringBuilder sb = new StringBuilder();
+
+ sb.append(getStringFromStream(es));
+ sb.append(getStringFromStream(os));
+
+ int res = cmd.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("EXITCODE: " + res);
+ Utils.logDebug("OUT: " + getOutput());
+
+ return res;
+
+ }
+
+ protected String getStringFromStream(InputStream s) throws IOException {
+
+ StringBuilder sb = new StringBuilder();
+ while ((s.available() > 0)) {
+ int b = s.read();
+ if (b >= 0) {
+ sb.append((char) b);
+ } else {
+ break;
+ }
+ }
+
+ return sb.toString();
+
+ }
+
+ public String getOutput() {
+
+ 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 d30eb2e..8cd90bf 100644
--- a/app/src/fil/libre/repwifiapp/helpers/Utils.java
+++ b/app/src/fil/libre/repwifiapp/helpers/Utils.java
@@ -32,175 +32,171 @@ import android.util.Log;
public class Utils {
- private static final long MILLIS_IN_DAY = 86400000;
-
- public static final String APP_NAME = "RepWifi";
-
- private static Exception _lastException = null;
-
- public static Exception getLastException(){
- return _lastException;
- }
-
- public static void logError(String msg, Exception e){
- Log.e(APP_NAME,msg,e);
- }
-
- public static void logError(String msg){
- Log.e(APP_NAME,msg);
- }
-
- public static void logDebug(String msg){
- logDebug(msg,0);
- }
-
- public static void logDebug(String msg, int level){
-
- if (level < Commons.getLogPriority()){
- return;
- }
-
- Log.d(APP_NAME,msg);
- }
-
-
- public static boolean writeFile(String filePath, String text, boolean overwrite){
-
- FileWriter writer = null;
- boolean retval = false;
-
- try {
-
- writer = new FileWriter(filePath, (! overwrite));
- writer.write(text);
-
- retval = true;
-
- } catch (Exception e) {
- _lastException = e;
- retval = false;
- }
- finally{
-
- if (writer != null){
- try {
- writer.close();
- } catch (IOException e) {
- logError("error while closing filewriter",e);
- }
- }
-
- }
-
- return retval;
-
- }
-
- public static boolean writeFileLines(String filePath, String[] lines, boolean overwrite){
-
- if (lines == null){
- return false;
- }
-
- FileWriter writer = null;
- boolean retval = false;
-
- try {
-
- writer = new FileWriter(filePath, (! overwrite));
-
- if (lines.length == 0){
- writer.write("");
- }
-
- for(String l : lines){
- writer.write(l + "\n");
- }
-
- retval = true;
-
- } catch (Exception e) {
- _lastException = e;
- retval = false;
- }
- finally{
-
- if (writer != null){
- try {
- writer.close();
- } catch (IOException e) {
- logError("error while closing filewriter",e);
- }
- }
-
- }
-
- return retval;
-
- }
-
- public static String[] readFileLines(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;
+ private static final long MILLIS_IN_DAY = 86400000;
+
+ public static final String APP_NAME = "RepWifi";
+
+ private static Exception _lastException = null;
+
+ public static Exception getLastException() {
+ return _lastException;
+ }
+
+ public static void logError(String msg, Exception e) {
+ Log.e(APP_NAME, msg, e);
+ }
+
+ public static void logError(String msg) {
+ Log.e(APP_NAME, msg);
+ }
+
+ public static void logDebug(String msg) {
+ logDebug(msg, 0);
+ }
+
+ public static void logDebug(String msg, int level) {
+
+ if (level < Commons.getLogPriority()) {
+ return;
+ }
+
+ Log.d(APP_NAME, msg);
+ }
+
+ public static boolean writeFile(String filePath, String text, boolean overwrite) {
+
+ FileWriter writer = null;
+ boolean retval = false;
+
+ try {
+
+ writer = new FileWriter(filePath, (!overwrite));
+ writer.write(text);
+
+ retval = true;
+
+ } catch (Exception e) {
+ _lastException = e;
+ retval = false;
+ } finally {
+
+ if (writer != null) {
+ try {
+ writer.close();
+ } catch (IOException e) {
+ logError("error while closing filewriter", e);
+ }
+ }
+
+ }
+
+ return retval;
+
+ }
+
+ public static boolean writeFileLines(String filePath, String[] lines, boolean overwrite) {
+
+ if (lines == null) {
+ return false;
+ }
+
+ FileWriter writer = null;
+ boolean retval = false;
+
+ try {
+
+ writer = new FileWriter(filePath, (!overwrite));
+
+ if (lines.length == 0) {
+ writer.write("");
+ }
+
+ for (String l : lines) {
+ writer.write(l + "\n");
+ }
+
+ retval = true;
+
+ } catch (Exception e) {
+ _lastException = e;
+ retval = false;
+ } finally {
+
+ if (writer != null) {
+ try {
+ writer.close();
+ } catch (IOException e) {
+ logError("error while closing filewriter", e);
+ }
+ }
+
+ }
+
+ return retval;
+
+ }
+
+ public static String[] readFileLines(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;
-
+
List<String> lines = new ArrayList<String>();
String[] ret = null;
-
- try {
-
- fr = new FileReader(filePath);
- bufr = new BufferedReader(fr);
- String line ="";
-
- while((line = bufr.readLine()) != null){
- lines.add(line);
- }
-
- String[] ar = new String[lines.size()];
- ret = lines.toArray(ar);
-
- } catch (Exception e) {
- logError("Error while reading file " + filePath,e);
- ret = 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);
- }
- }
-
- return ret;
-
- }
-
- public static long daysToMilliseconds(int days){
- return (days * MILLIS_IN_DAY);
- }
-
- public static long millisecondsToDays(long milliseconds){
- return (milliseconds / MILLIS_IN_DAY);
- }
-
+
+ try {
+
+ fr = new FileReader(filePath);
+ bufr = new BufferedReader(fr);
+ String line = "";
+
+ while ((line = bufr.readLine()) != null) {
+ lines.add(line);
+ }
+
+ String[] ar = new String[lines.size()];
+ ret = lines.toArray(ar);
+
+ } catch (Exception e) {
+ logError("Error while reading file " + filePath, e);
+ ret = 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);
+ }
+ }
+
+ return ret;
+
+ }
+
+ public static long daysToMilliseconds(int days) {
+ return (days * MILLIS_IN_DAY);
+ }
+
+ public static long millisecondsToDays(long milliseconds) {
+ return (milliseconds / MILLIS_IN_DAY);
+ }
+
}