Skip to content

Commit

Permalink
Revert back to the original service implementation.
Browse files Browse the repository at this point in the history
Move a sometimes slow task to a thread.
  • Loading branch information
ruiaraujo committed Nov 26, 2017
1 parent eea35b3 commit 1ff3c97
Show file tree
Hide file tree
Showing 5 changed files with 79 additions and 83 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

Expand All @@ -42,26 +43,6 @@ public class Wifi {
private static final String TAG = "Wifi Connecter";
private static final int MAX_PRIORITY = 99999;

/**
* Change the password of an existing configured network and connect to it
*
* @param wifiMgr
* @param config
* @param newPassword
* @return
*/
public static int changePasswordAndConnect(final Context ctx, final WifiManager wifiMgr, final WifiConfiguration config, final String newPassword, final int numOpenNetworksKept) {
ConfigSec.setupSecurity(config, ConfigSec.getWifiConfigurationSecurity(config), newPassword);
final int networkId = wifiMgr.updateNetwork(config);
if (networkId == -1) {
// Update failed.
return -1;
}
// Force the change to apply.
wifiMgr.disconnect();
return connectToConfiguredNetwork(ctx, wifiMgr, config, true);
}

/**
* Configure a network, and connect to it.
*
Expand All @@ -70,7 +51,7 @@ public static int changePasswordAndConnect(final Context ctx, final WifiManager
* @param password Password for secure network or is ignored.
* @return
*/
public static int connectToNewNetwork(final Context ctx, final WifiManager wifiMgr, final ScanResult scanResult, final String password, final int numOpenNetworksKept) {
public static int connectToNewNetwork(final WifiManager wifiMgr, final ScanResult scanResult, final String password, final int numOpenNetworksKept) {
final String security = ConfigSec.getScanResultSecurity(scanResult);

if (ConfigSec.isOpenNetwork(security)) {
Expand Down Expand Up @@ -103,19 +84,17 @@ public static int connectToNewNetwork(final Context ctx, final WifiManager wifiM
return -1;
}

return connectToConfiguredNetwork(ctx, wifiMgr, config, true);
return connectToConfiguredNetwork(wifiMgr, config);
}

/**
* Connect to a configured network.
*
* @param ctx
* @param wifiManager
* @param wifiMgr
* @param config
* @param reassociate
* @return
*/
private static int connectToConfiguredNetwork(final Context ctx, final WifiManager wifiMgr, WifiConfiguration config, boolean reassociate) {
private static int connectToConfiguredNetwork(final WifiManager wifiMgr, WifiConfiguration config) {
final String security = ConfigSec.getWifiConfigurationSecurity(config);
int configId = config.networkId;
int oldPri = config.priority;
Expand Down Expand Up @@ -159,8 +138,7 @@ private static int connectToConfiguredNetwork(final Context ctx, final WifiManag
return -1;
}

final boolean connect = reassociate ? wifiMgr.reassociate() : wifiMgr.reconnect();
if (!connect) {
if (!wifiMgr.reassociate()) {
return -1;
}

Expand Down Expand Up @@ -229,6 +207,10 @@ private static int getMaxPriority(final WifiManager wifiManager) {
}

public static void cleanPreviousConfiguration(final WifiManager wifiMgr, final ScanResult hotspot, String hotspotSecurity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) {
return; // we can't delete network above 6.0
}

WifiConfiguration config;
do {
config = getWifiConfiguration(wifiMgr, hotspot, null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@
*/
package org.exobel.routerkeygen;

import android.app.IntentService;
import android.annotation.TargetApi;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
Expand All @@ -31,8 +32,10 @@
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

Expand All @@ -45,7 +48,7 @@
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class AutoConnectService extends IntentService implements onConnectionListener {
public class AutoConnectService extends Service implements onConnectionListener {
public final static String SCAN_RESULT = "org.exobel.routerkeygen.SCAN_RESULT";
public final static String KEY_LIST = "org.exobel.routerkeygen.KEY_LIST";

Expand All @@ -55,6 +58,7 @@ public class AutoConnectService extends IntentService implements onConnectionLis
private final static int FAILING_MINIMUM_TIME = 1500;
private final int UNIQUE_ID = R.string.app_name
+ AutoConnectService.class.getName().hashCode();
final private Binder mBinder = new LocalBinder();
private NotificationManager mNotificationManager;
private Handler handler;
private ScanResult network;
Expand All @@ -77,10 +81,6 @@ public class AutoConnectService extends IntentService implements onConnectionLis
tryingConnection();
}
};
public AutoConnectService() {
super("AutoConnectService");
}


private static PendingIntent getDefaultPendingIntent(Context context) {
final Intent i = new Intent(context, CancelOperationActivity.class)
Expand All @@ -94,10 +94,13 @@ private static PendingIntent getDefaultPendingIntent(Context context) {
}

@Override
protected void onHandleIntent(Intent intent) {
if (intent == null) {
return;
}
public IBinder onBind(Intent intent) {
return mBinder;
}

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@SuppressWarnings("deprecation")
public void onCreate() {
handler = new Handler();
wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Expand All @@ -111,13 +114,21 @@ protected void onHandleIntent(Intent intent) {
mNumOpenNetworksKept = Settings.Global.getInt(getContentResolver(),
Settings.Global.WIFI_NUM_OPEN_NETWORKS_KEPT, 10);

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null) {
stopSelf();
return START_NOT_STICKY;
}
attempts = 0;
currentNetworkId = -1;
network = intent.getParcelableExtra(SCAN_RESULT);
keys = intent.getStringArrayListExtra(KEY_LIST);
final ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
final NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (!registered.get()){
if (!registered.get()) {
registerReceiver(mReceiver, new IntentFilter(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION));
registerReceiver(mReceiver, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
registered.set(true);
Expand Down Expand Up @@ -152,19 +163,19 @@ protected void onHandleIntent(Intent intent) {
.build());
cancelNotification = false;
stopSelf();
return;
return START_NOT_STICKY;
}
} else {
Wifi.cleanPreviousConfiguration(wifi, network, network.capabilities);
tryingConnection();
}
return;
return START_STICKY;
}

private void disconnectCurrent(){
private int disconnectCurrent() {
final ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
final NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (!registered.get()){
if (!registered.get()) {
registerReceiver(mReceiver, new IntentFilter(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION));
registerReceiver(mReceiver, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
registered.set(true);
Expand All @@ -174,10 +185,12 @@ private void disconnectCurrent(){
waitingToDisconnect.set(true);
if (wifi.disconnect()) {
// besides disconnecting, we clean any previous configuration
Wifi.cleanPreviousConfiguration(wifi, network, network.capabilities);
new Thread(() -> Wifi.cleanPreviousConfiguration(wifi, network, network.capabilities)).start();
cancelNotification = true;
handler.postDelayed(tryAfterDisconnecting, DISCONNECT_WAITING_TIME);

return 1;

} else {
waitingToDisconnect.set(false);
mNotificationManager.notify(
Expand All @@ -188,10 +201,12 @@ private void disconnectCurrent(){
.build());
cancelNotification = false;
stopSelf();
return -1;
}
} else {
Log.d(TAG, "Not connected");
tryingConnection();
return 0;
}
}

Expand All @@ -201,7 +216,7 @@ private void tryingConnection() {
scanningStarted.set(true);

// If attempt counter is too high, we are done here.
if (keys.size() <= attempts){
if (keys.size() <= attempts) {
Log.e(TAG, "Attempt counter too big, stopping");
reenableAllHotspots();
mNotificationManager.notify(
Expand All @@ -214,7 +229,7 @@ private void tryingConnection() {
return;
}

currentNetworkId = Wifi.connectToNewNetwork(this, wifi, network, keys.get(attempts), mNumOpenNetworksKept);
currentNetworkId = Wifi.connectToNewNetwork(wifi, network, keys.get(attempts), mNumOpenNetworksKept);
Log.d(AutoConnectManager.class.getSimpleName(), "Trying " + keys.get(attempts));
if (currentNetworkId != -1) {
lastTimeDisconnected = System.currentTimeMillis();
Expand Down Expand Up @@ -267,14 +282,14 @@ public void onDestroy() {

@Override
public void onFailedConnection(int supplicantError) {
if (waitingToDisconnect.get()){
if (waitingToDisconnect.get()) {
Log.d(TAG, "onFailed, as expected, start scan");
waitingToDisconnect.set(false);
tryingConnection();
return;
}

if (!scanningStarted.get()){
if (!scanningStarted.get()) {
Log.d(TAG, "onFailed, not yet started");
return;
}
Expand All @@ -293,14 +308,14 @@ public void onFailedConnection(int supplicantError) {
wifi.removeNetwork(currentNetworkId);

// The password has to go through handshake phase.
if (attempts != handshakeAttempt.get()){
if (attempts != handshakeAttempt.get()) {
Log.w(TAG, "Handshaked password does not match the attempt");
final int failedAttempts = sameHandshakeAttempts.incrementAndGet();

if (failedAttempts >= 8) {
Log.w(TAG, "Too many missed handshakes, trying without it.");
sameHandshakeAttempts.set(0);
attempts+=1;
attempts += 1;

} else if (failedAttempts >= 4) {
Log.w(TAG, "Too many missed handshakes, Reinit");
Expand All @@ -313,23 +328,19 @@ public void onFailedConnection(int supplicantError) {
}

// Failed to connect, increase attempt ctr to move to next password
attempts+=1;
attempts += 1;
tryingConnection();
}

@Override
public void onFourWayHandshake(int supplicantError){
public void onFourWayHandshake(int supplicantError) {
handshakeAttempt.set(attempts);
Log.d(AutoConnectManager.class.getSimpleName(),
String.format("4Way handshake - Trying %s, error: %s", keys.get(attempts), supplicantError));
}

@Override
public void onNetworkChanged(NetworkInfo networkInfo, String bssid, WifiInfo wifiInfo) {
// If scanning not yet started, not interested in network change.
if (!scanningStarted.get()){
return;
}
}

@Override
Expand All @@ -340,20 +351,20 @@ public void onSuccessfulConection(int supplicantError) {
return;
}

if (waitingToDisconnect.get()){
if (waitingToDisconnect.get()) {
Log.d(TAG, "onSuccess, but waiting to disconnect...");
disconnectCurrent();
return;
}

final WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService (Context.WIFI_SERVICE);
final WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
final WifiInfo wifiInfo = wifiManager == null ? null : wifiManager.getConnectionInfo();
final String connectedSsid = wifiInfo == null ? null : wifiInfo.getSSID();
Log.d(TAG, String.format("onSuccess, connected to: %s, state: %s, error: %s",
connectedSsid, wifiInfo==null?"NULL":wifiInfo.getSupplicantState(), supplicantError));
connectedSsid, wifiInfo == null ? "NULL" : wifiInfo.getSupplicantState(), supplicantError));

if (wifiInfo != null
&& wifiInfo.getSupplicantState() != SupplicantState.COMPLETED){
&& wifiInfo.getSupplicantState() != SupplicantState.COMPLETED) {
Log.d(TAG, "Not really connected.");
tryingConnection();
return;
Expand All @@ -366,8 +377,7 @@ public void onSuccessfulConection(int supplicantError) {
&& !StringUtils.isEmpty(network.SSID)
&& !("0x").equals(connectedSsid)
&& !network.SSID.equals(connectedSsid)
&& !("\""+network.SSID+"\"").equals(connectedSsid))
{
&& !("\"" + network.SSID + "\"").equals(connectedSsid)) {
Log.d(TAG, String.format("Connected SSID does not match target, connected: %s target: %s", connectedSsid, network.SSID));
disconnectCurrent();
return;
Expand All @@ -394,4 +404,14 @@ private void reenableAllHotspots() {
}
}
}

/**
* Class for clients to access. Because we know this service always runs in
* the same process as its clients, we don't need to deal with IPC.
*/
private class LocalBinder extends Binder {
AutoConnectService getService() {
return AutoConnectService.this;
}
}
}
Loading

0 comments on commit 1ff3c97

Please sign in to comment.