diff options
Diffstat (limited to 'src')
34 files changed, 229 insertions, 3199 deletions
diff --git a/src/se/leap/bitmaskclient/AboutActivity.java b/src/se/leap/bitmaskclient/AboutActivity.java index a3320c81..6d025422 100644 --- a/src/se/leap/bitmaskclient/AboutActivity.java +++ b/src/se/leap/bitmaskclient/AboutActivity.java @@ -18,7 +18,7 @@ public class AboutActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + super.onCreate(savedInstanceState); setContentView(R.layout.about); TextView ver = (TextView) findViewById(R.id.version); @@ -34,15 +34,7 @@ public class AboutActivity extends Activity { ver.setText(getString(R.string.version_info,name,version)); - - TextView translation = (TextView) findViewById(R.id.translation); - - // Don't print a text for myself - if ( getString(R.string.translationby).contains("Arne Schwabe")) - translation.setVisibility(TextView.INVISIBLE); - else - translation.setText(R.string.translationby); - setResult(VIEWED); + setResult(VIEWED); } } diff --git a/src/se/leap/bitmaskclient/ConfigHelper.java b/src/se/leap/bitmaskclient/ConfigHelper.java index 6b49d7d7..a8bd3b7a 100644 --- a/src/se/leap/bitmaskclient/ConfigHelper.java +++ b/src/se/leap/bitmaskclient/ConfigHelper.java @@ -47,142 +47,12 @@ import android.util.Base64; * */ public class ConfigHelper { - - public static SharedPreferences shared_preferences; private static KeyStore keystore_trusted; final public static String NG_1024 = "eeaf0ab9adb38dd69c33f80afa8fc5e86072618775ff3c0b9ea2314c9c256576d674df7496ea81d3383b4813d692c6e0e0d5d8e250b98be48e495c1d6089dad15dc7d7b46154d6b6ce8ef4ad69b15d4982559b297bcf1885c529f566660e57ec68edbc3c05726cc02fd4cbf4976eaa9afd5138fe8376435b9fc61d2fc0eb06e3"; final public static BigInteger G = new BigInteger("2"); - - private static boolean checkSharedPrefs() { - try { - if(shared_preferences == null) - shared_preferences = Dashboard.getAppContext().getSharedPreferences(Dashboard.SHARED_PREFERENCES,Context.MODE_PRIVATE); - } catch (Exception e) { - return false; - } - - return true; - } - - /** - * Saves a JSON object into class scope Shared Preferences - * @param shared_preferences_key - * @param content - */ - public static void saveSharedPref(String shared_preferences_key, JSONObject content) { - - SharedPreferences.Editor shared_preferences_editor = shared_preferences - .edit(); - shared_preferences_editor.putString(shared_preferences_key, - content.toString()); - shared_preferences_editor.commit(); - } - - /** - * Saves a String object into class scope Shared Preferences - * @param shared_preferences_key - * @param content - */ - public static void saveSharedPref(String shared_preferences_key, String content) { - - SharedPreferences.Editor shared_preferences_editor = shared_preferences - .edit(); - shared_preferences_editor.putString(shared_preferences_key, - content); - shared_preferences_editor.commit(); - } - - /** - * Saves a boolean object into class scope Shared Preferences - * @param shared_preferences_key - * @param content - */ - public static void saveSharedPref(String shared_preferences_key, boolean content) { - - SharedPreferences.Editor shared_preferences_editor = shared_preferences - .edit(); - shared_preferences_editor.putBoolean(shared_preferences_key, content); - shared_preferences_editor.commit(); - } - - /** - * Saves an int into class scope Shared Preferences - * - * @param shared_preferences_key - * @param value - */ - protected static void saveSharedPref(String shared_preferences_key, int value) { - SharedPreferences.Editor shared_preferences_editor = shared_preferences.edit(); - shared_preferences_editor.putInt(shared_preferences_key, value).commit(); - } - - /** - * Gets String object from class scope Shared Preferences - * @param shared_preferences_key - * @return the string correspondent to the key parameter - */ - public static String getStringFromSharedPref(String shared_preferences_key) { - String content = null; - content = shared_preferences.getString(shared_preferences_key, ""); - return content; - } - - /** - * Gets JSON object from class scope Shared Preferences - * @param shared_preferences_key - * @return the JSON object correspondent to the key parameter - */ - public static JSONObject getJsonFromSharedPref(String shared_preferences_key) throws JSONException { - JSONObject content = null; - if ( checkSharedPrefs() ) { - String json_string = shared_preferences.getString(shared_preferences_key, ""); - content = new JSONObject(json_string); - } - - return content; - } - - /* - * This method defaults to false. - * If you use this method, be sure to fail-closed on false! - * TODO This is obviously less than ideal...solve it! - */ - public static boolean getBoolFromSharedPref(String shared_preferences_key) { - boolean value = false; - if ( checkSharedPrefs() ) { - value = shared_preferences.getBoolean(shared_preferences_key, false); - } - return value; - } - - /** - * Get an int from SharedPreferences - * - * @param shared_preferences_key Key to retrieve - * @return The value for the key or 0 - */ - protected static int getIntFromSharedPref(String shared_preferences_key) { - return shared_preferences.getInt(shared_preferences_key, 0); - } - - protected static boolean sharedPrefContainsKey(String shared_preferences_key) { - return shared_preferences.contains(shared_preferences_key); - } - /* - * This method defaults to false. - * If you use this method, be sure to fail-closed on false! - * TODO This is obviously less than ideal...solve it! - */ - public static boolean removeFromSharedPref(String shared_preferences_key) { - SharedPreferences.Editor shared_preferences_editor = shared_preferences - .edit(); - shared_preferences_editor.remove(shared_preferences_key); - return shared_preferences_editor.commit(); - } - public static boolean checkErroneousDownload(String downloaded_string) { try { if(new JSONObject(downloaded_string).has(ProviderAPI.ERRORS) || downloaded_string.isEmpty()) { @@ -214,15 +84,6 @@ public class ConfigHelper { System.arraycopy(in, i, ret, 0, len - i); return ret; } - - /** - * Sets class scope Shared Preferences - * @param shared_preferences - */ - public static void setSharedPreferences( - SharedPreferences shared_preferences) { - ConfigHelper.shared_preferences = shared_preferences; - } public static X509Certificate parseX509CertificateFromString(String certificate_string) { java.security.cert.Certificate certificate = null; diff --git a/src/se/leap/bitmaskclient/ConfigurationWizard.java b/src/se/leap/bitmaskclient/ConfigurationWizard.java index cf027660..1c5f6048 100644 --- a/src/se/leap/bitmaskclient/ConfigurationWizard.java +++ b/src/se/leap/bitmaskclient/ConfigurationWizard.java @@ -40,6 +40,7 @@ import android.content.BroadcastReceiver; import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
+import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Handler;
@@ -85,10 +86,12 @@ implements ProviderListFragment.Callbacks, NewProviderDialogInterface, ProviderD public ProviderAPIResultReceiver providerAPI_result_receiver;
private ProviderAPIBroadcastReceiver_Update providerAPI_broadcast_receiver_update;
+ private static SharedPreferences preferences; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
+ preferences = getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE);
setContentView(R.layout.configuration_wizard_activity);
mProgressBar = (ProgressBar) findViewById(R.id.progressbar_configuration_wizard);
@@ -101,10 +104,8 @@ implements ProviderListFragment.Callbacks, NewProviderDialogInterface, ProviderD IntentFilter update_intent_filter = new IntentFilter(ProviderAPI.UPDATE_PROGRESSBAR);
update_intent_filter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(providerAPI_broadcast_receiver_update, update_intent_filter);
-
- ConfigHelper.setSharedPreferences(getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE));
-
- loadPreseededProviders();
+
+ loadPreseededProviders();
// Only create our fragments if we're not restoring a saved instance
if ( savedInstanceState == null ){
@@ -136,9 +137,9 @@ implements ProviderListFragment.Callbacks, NewProviderDialogInterface, ProviderD public void refreshProviderList(int top_padding) {
ProviderListFragment new_provider_list_fragment = new ProviderListFragment();
Bundle top_padding_bundle = new Bundle();
- top_padding_bundle.putInt(getResources().getString(R.string.top_padding), top_padding);
+ top_padding_bundle.putInt(ProviderListFragment.TOP_PADDING, top_padding);
new_provider_list_fragment.setArguments(top_padding_bundle);
-
+
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.configuration_wizard_layout, new_provider_list_fragment, ProviderListFragment.TAG)
@@ -150,7 +151,7 @@ implements ProviderListFragment.Callbacks, NewProviderDialogInterface, ProviderD if(resultCode == ProviderAPI.PROVIDER_OK) {
mConfigState.setAction(PROVIDER_SET);
- if (ConfigHelper.getBoolFromSharedPref(EIP.ALLOWED_ANON)){
+ if (preferences.getBoolean(EIP.ALLOWED_ANON, false)){
mConfigState.putExtra(SERVICES_RETRIEVED, true);
downloadAnonCert();
} else {
@@ -166,7 +167,7 @@ implements ProviderListFragment.Callbacks, NewProviderDialogInterface, ProviderD showDownloadFailedDialog(getCurrentFocus(), reason_to_fail);
mProgressBar.setVisibility(ProgressBar.GONE);
progressbar_description.setVisibility(TextView.GONE);
- ConfigHelper.removeFromSharedPref(Provider.KEY); + preferences.edit().remove(Provider.KEY).commit(); setResult(RESULT_CANCELED, mConfigState);
}
else if(resultCode == ProviderAPI.CORRECTLY_DOWNLOADED_CERTIFICATE) {
@@ -204,15 +205,17 @@ implements ProviderListFragment.Callbacks, NewProviderDialogInterface, ProviderD provider_list_fragment.hideAllBut(provider_index); boolean danger_on = true; - if(ConfigHelper.sharedPrefContainsKey(ProviderItem.DANGER_ON)) - danger_on = ConfigHelper.getBoolFromSharedPref(ProviderItem.DANGER_ON); + if(preferences.contains(ProviderItem.DANGER_ON)) + danger_on = preferences.getBoolean(ProviderItem.DANGER_ON, false); setUpProvider(selected_provider.providerMainUrl(), danger_on); }
@Override
public void onBackPressed() {
try {
- if(ConfigHelper.getJsonFromSharedPref(Provider.KEY) == null || ConfigHelper.getJsonFromSharedPref(Provider.KEY).length() == 0) {
+ boolean is_provider_set_up = new JSONObject(preferences.getString(Provider.KEY, "no provider")) != null ? true : false;
+ boolean is_provider_set_up_truly = new JSONObject(preferences.getString(Provider.KEY, "no provider")).length() != 0 ? true : false;
+ if(!is_provider_set_up || !is_provider_set_up_truly) {
askDashboardToQuitApp();
} else {
setResult(RESULT_OK);
@@ -275,12 +278,7 @@ implements ProviderListFragment.Callbacks, NewProviderDialogInterface, ProviderD ProviderItem provider = providers_iterator.next();
if(provider.name().equalsIgnoreCase(id)) {
break;
-//<<<<<<< HEAD -// }
-// index++;
-//======= - } else index++;
-//>>>>>>> bug/more-detailed-response-to-CW-errors + } else index++; }
return index;
}
@@ -432,8 +430,7 @@ implements ProviderListFragment.Callbacks, NewProviderDialogInterface, ProviderD }
private void autoSelectProvider(String provider_main_url, boolean danger_on) {
- - ConfigHelper.saveSharedPref(ProviderItem.DANGER_ON, danger_on);
+ getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putBoolean(ProviderItem.DANGER_ON, danger_on).commit();
onItemSelected(getId(provider_main_url));
}
@@ -498,14 +495,10 @@ implements ProviderListFragment.Callbacks, NewProviderDialogInterface, ProviderD public void cancelSettingUpProvider() {
provider_list_fragment = (ProviderListFragment) getFragmentManager().findFragmentByTag(ProviderListFragment.TAG);
- if(provider_list_fragment != null && ConfigHelper.sharedPrefContainsKey(ProviderItem.DANGER_ON)) {
+ if(provider_list_fragment != null && preferences.contains(ProviderItem.DANGER_ON)) {
provider_list_fragment.removeLastItem();
}
-
- ConfigHelper.removeFromSharedPref(Provider.KEY);
- ConfigHelper.removeFromSharedPref(ProviderItem.DANGER_ON);
- ConfigHelper.removeFromSharedPref(EIP.ALLOWED_ANON);
- ConfigHelper.removeFromSharedPref(EIP.KEY);
+ preferences.edit().remove(Provider.KEY).remove(ProviderItem.DANGER_ON).remove(EIP.ALLOWED_ANON).remove(EIP.KEY).commit();
}
@Override
diff --git a/src/se/leap/bitmaskclient/Dashboard.java b/src/se/leap/bitmaskclient/Dashboard.java index 44cf8247..65fd2d5b 100644 --- a/src/se/leap/bitmaskclient/Dashboard.java +++ b/src/se/leap/bitmaskclient/Dashboard.java @@ -21,7 +21,6 @@ import org.json.JSONObject; import se.leap.bitmaskclient.R; import se.leap.bitmaskclient.ProviderAPIResultReceiver.Receiver; -import se.leap.openvpn.MainActivity; import android.app.Activity; import android.app.AlertDialog; import android.app.DialogFragment; @@ -55,15 +54,11 @@ public class Dashboard extends Activity implements LogInDialog.LogInDialogInterf protected static final int CONFIGURE_LEAP = 0; protected static final int SWITCH_PROVIDER = 1; - private static final String TAG_EIP_FRAGMENT = "EIP_DASHBOARD_FRAGMENT"; final public static String SHARED_PREFERENCES = "LEAPPreferences"; final public static String ACTION_QUIT = "quit"; public static final String REQUEST_CODE = "request_code"; - - - private ProgressBar mProgressBar; private TextView eipStatus; @@ -90,11 +85,10 @@ public class Dashboard extends Activity implements LogInDialog.LogInDialogInterf mProgressBar = (ProgressBar) findViewById(R.id.eipProgress); - ConfigHelper.setSharedPreferences(getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE)); - preferences = ConfigHelper.shared_preferences; + preferences = getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE); - authed_eip = ConfigHelper.getBoolFromSharedPref(EIP.AUTHED_EIP); - if (ConfigHelper.getStringFromSharedPref(Provider.KEY).isEmpty()) + authed_eip = preferences.getBoolean(EIP.AUTHED_EIP, false); + if (preferences.getString(Provider.KEY, "").isEmpty()) startActivityForResult(new Intent(this,ConfigurationWizard.class),CONFIGURE_LEAP); else buildDashboard(); @@ -110,12 +104,13 @@ public class Dashboard extends Activity implements LogInDialog.LogInDialogInterf if ( requestCode == CONFIGURE_LEAP || requestCode == SWITCH_PROVIDER) { // It should be equivalent: if ( (requestCode == CONFIGURE_LEAP) || (data!= null && data.hasExtra(STOP_FIRST))) { if ( resultCode == RESULT_OK ){ - ConfigHelper.saveSharedPref(EIP.PARSED_SERIAL, 0); - ConfigHelper.saveSharedPref(EIP.AUTHED_EIP, authed_eip); - - startService( new Intent(EIP.ACTION_UPDATE_EIP_SERVICE) ); + getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putInt(EIP.PARSED_SERIAL, 0).commit(); + getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putBoolean(EIP.AUTHED_EIP, authed_eip).commit(); + Intent updateEIP = new Intent(getApplicationContext(), EIP.class); + updateEIP.setAction(EIP.ACTION_UPDATE_EIP_SERVICE); + startService(updateEIP); buildDashboard(); - + invalidateOptionsMenu(); if(data != null && data.hasExtra(LogInDialog.VERB)) { View view = ((ViewGroup)findViewById(android.R.id.content)).getChildAt(0); logInDialog(view, Bundle.EMPTY); @@ -181,8 +176,9 @@ public class Dashboard extends Activity implements LogInDialog.LogInDialogInterf public boolean onPrepareOptionsMenu(Menu menu) { JSONObject provider_json; try { - provider_json = ConfigHelper.getJsonFromSharedPref(Provider.KEY); + provider_json = new JSONObject(getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE).getString(Provider.KEY, "")); JSONObject service_description = provider_json.getJSONObject(Provider.SERVICE); + if(service_description.getBoolean(Provider.ALLOW_REGISTRATION)) { if(authed_eip) { menu.findItem(R.id.login_button).setVisible(false); @@ -213,18 +209,14 @@ public class Dashboard extends Activity implements LogInDialog.LogInDialogInterf intent = new Intent(this, AboutActivity.class); startActivity(intent); return true; - case R.id.legacy_interface: - intent = new Intent(this,MainActivity.class); - startActivity(intent); - return true; case R.id.switch_provider: if (Provider.getInstance().hasEIP()){ - if (ConfigHelper.getBoolFromSharedPref(EIP.AUTHED_EIP)){ + if (getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).getBoolean(EIP.AUTHED_EIP, false)){ logOut(); } eipStop(); } - ConfigHelper.removeFromSharedPref(Provider.KEY); + getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().remove(Provider.KEY).commit(); startActivityForResult(new Intent(this,ConfigurationWizard.class), SWITCH_PROVIDER); return true; case R.id.login_button: @@ -268,7 +260,7 @@ public class Dashboard extends Activity implements LogInDialog.LogInDialogInterf provider_API_command.putExtra(ProviderAPI.RECEIVER_KEY, providerAPI_result_receiver); mProgressBar.setVisibility(ProgressBar.VISIBLE); - eipStatus.setText("Starting to login"); + eipStatus.setText(R.string.authenticating_message); //mProgressBar.setMax(4); startService(provider_API_command); } @@ -299,7 +291,9 @@ public class Dashboard extends Activity implements LogInDialog.LogInDialogInterf if(mProgressBar == null) mProgressBar = (ProgressBar) findViewById(R.id.eipProgress); mProgressBar.setVisibility(ProgressBar.VISIBLE); if(eipStatus == null) eipStatus = (TextView) findViewById(R.id.eipStatus); - eipStatus.setText("Starting to logout"); + eipStatus.setText(R.string.logout_message); + // eipStatus.setText("Starting to logout"); + startService(provider_API_command); //mProgressBar.setMax(1); @@ -354,73 +348,76 @@ public class Dashboard extends Activity implements LogInDialog.LogInDialogInterf setResult(RESULT_OK); authed_eip = true; - ConfigHelper.saveSharedPref(EIP.AUTHED_EIP, authed_eip); - invalidateOptionsMenu(); + getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putBoolean(EIP.AUTHED_EIP, authed_eip).commit(); + invalidateOptionsMenu(); mProgressBar.setVisibility(ProgressBar.GONE); + changeStatusMessage(resultCode); //Cookie session_id = new BasicClientCookie(session_id_cookie_key, session_id_string); downloadAuthedUserCertificate(/*session_id*/); } else if(resultCode == ProviderAPI.SRP_AUTHENTICATION_FAILED) { logInDialog(getCurrentFocus(), resultData); - eipStatus.setText("Login failed"); - mProgressBar.setVisibility(ProgressBar.GONE); } else if(resultCode == ProviderAPI.LOGOUT_SUCCESSFUL) { authed_eip = false; - ConfigHelper.saveSharedPref(EIP.AUTHED_EIP, authed_eip); - - changeStatusMessage(resultCode); + getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putBoolean(EIP.AUTHED_EIP, authed_eip).commit(); mProgressBar.setVisibility(ProgressBar.GONE); mProgressBar.setProgress(0); invalidateOptionsMenu(); setResult(RESULT_OK); + changeStatusMessage(resultCode); + } else if(resultCode == ProviderAPI.LOGOUT_FAILED) { setResult(RESULT_CANCELED); - eipStatus.setText("Didn't log out"); + changeStatusMessage(resultCode); mProgressBar.setVisibility(ProgressBar.GONE); - //mProgressBar.setProgress(0); - Toast.makeText(getApplicationContext(), R.string.log_out_failed_message, Toast.LENGTH_LONG).show(); } else if(resultCode == ProviderAPI.CORRECTLY_DOWNLOADED_CERTIFICATE) { setResult(RESULT_OK); + changeStatusMessage(resultCode); mProgressBar.setVisibility(ProgressBar.GONE); - changeStatusMessage(resultCode); - //mProgressBar.setProgress(0); - Toast.makeText(getApplicationContext(), R.string.successful_authed_cert_downloaded_message, Toast.LENGTH_LONG).show(); } else if(resultCode == ProviderAPI.INCORRECTLY_DOWNLOADED_CERTIFICATE) { setResult(RESULT_CANCELED); + changeStatusMessage(resultCode); mProgressBar.setVisibility(ProgressBar.GONE); - //mProgressBar.setProgress(0); - changeStatusMessage(resultCode); - Toast.makeText(getApplicationContext(), R.string.authed_cert_download_failed_message, Toast.LENGTH_LONG).show(); - } + } } private void changeStatusMessage(final int previous_result_code) { // TODO Auto-generated method stub ResultReceiver eip_status_receiver = new ResultReceiver(new Handler()){ - @Override - protected void onReceiveResult(int resultCode, Bundle resultData) { + protected void onReceiveResult(int resultCode, Bundle resultData){ super.onReceiveResult(resultCode, resultData); String request = resultData.getString(EIP.REQUEST_TAG); - if(resultCode == RESULT_OK) { - if(request.equalsIgnoreCase(EIP.ACTION_IS_EIP_RUNNING)) { - switch (previous_result_code) { - case ProviderAPI.LOGOUT_SUCCESSFUL: eipStatus.setText(R.string.anonymous_secured_status); break; + if (request.equalsIgnoreCase(EIP.ACTION_IS_EIP_RUNNING)){ + if (resultCode == Activity.RESULT_OK){ + + switch(previous_result_code){ + case ProviderAPI.SRP_AUTHENTICATION_SUCCESSFUL: eipStatus.setText(R.string.succesful_authentication_message); break; + case ProviderAPI.SRP_AUTHENTICATION_FAILED: eipStatus.setText(R.string.authentication_failed_message); break; case ProviderAPI.CORRECTLY_DOWNLOADED_CERTIFICATE: eipStatus.setText(R.string.authed_secured_status); break; - } + case ProviderAPI.INCORRECTLY_DOWNLOADED_CERTIFICATE: eipStatus.setText(R.string.incorrectly_downloaded_certificate_message); break; + case ProviderAPI.LOGOUT_SUCCESSFUL: eipStatus.setText(R.string.anonymous_secured_status); break; + case ProviderAPI.LOGOUT_FAILED: eipStatus.setText(R.string.log_out_failed_message); break; + + } } - } else { - if(request.equalsIgnoreCase(EIP.ACTION_IS_EIP_RUNNING)) { - switch (previous_result_code) { - case ProviderAPI.LOGOUT_SUCCESSFUL: eipStatus.setText(R.string.future_anonymous_secured_status); break; + else if(resultCode == Activity.RESULT_CANCELED){ + + switch(previous_result_code){ + + case ProviderAPI.SRP_AUTHENTICATION_SUCCESSFUL: eipStatus.setText(R.string.succesful_authentication_message); break; + case ProviderAPI.SRP_AUTHENTICATION_FAILED: eipStatus.setText(R.string.authentication_failed_message); break; case ProviderAPI.CORRECTLY_DOWNLOADED_CERTIFICATE: eipStatus.setText(R.string.future_authed_secured_status); break; + case ProviderAPI.INCORRECTLY_DOWNLOADED_CERTIFICATE: eipStatus.setText(R.string.incorrectly_downloaded_certificate_message); break; + case ProviderAPI.LOGOUT_SUCCESSFUL: eipStatus.setText(R.string.future_anonymous_secured_status); break; + case ProviderAPI.LOGOUT_FAILED: eipStatus.setText(R.string.log_out_failed_message); break; } } } + } }; - eipIsRunning(eip_status_receiver); - + eipIsRunning(eip_status_receiver); } /** diff --git a/src/se/leap/bitmaskclient/EIP.java b/src/se/leap/bitmaskclient/EIP.java index 2b7fd39f..e773e3b9 100644 --- a/src/se/leap/bitmaskclient/EIP.java +++ b/src/se/leap/bitmaskclient/EIP.java @@ -16,10 +16,14 @@ */ package se.leap.bitmaskclient; +import java.util.Calendar; import java.util.Collection; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.NoSuchElementException; +import java.util.Set; +import java.util.TreeMap; import java.util.Vector; import org.json.JSONArray; @@ -35,13 +39,13 @@ import se.leap.openvpn.OpenVpnService; import se.leap.openvpn.OpenVpnService.LocalBinder; import se.leap.openvpn.ProfileManager; import se.leap.openvpn.VpnProfile; - import android.app.Activity; import android.app.IntentService; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; +import android.drm.DrmStore.Action; import android.os.Bundle; import android.os.IBinder; import android.os.ResultReceiver; @@ -72,6 +76,7 @@ public final class EIP extends IntentService { public final static String SERVICE_API_PATH = "config/eip-service.json"; public final static String RECEIVER_TAG = "receiverTag"; public final static String REQUEST_TAG = "requestTag"; + public final static String TAG = "se.leap.bitmaskclient.EIP"; private static Context context; @@ -96,13 +101,7 @@ public final class EIP extends IntentService { context = getApplicationContext(); - try { - eipDefinition = ConfigHelper.getJsonFromSharedPref(KEY); - parsedEipSerial = ConfigHelper.getIntFromSharedPref(PARSED_SERIAL); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + updateEIPService(); this.retreiveVpnService(); } @@ -141,7 +140,6 @@ public final class EIP extends IntentService { } private static ServiceConnection mVpnServiceConn = new ServiceConnection() { - @Override public void onServiceConnected(ComponentName name, IBinder service) { LocalBinder binder = (LocalBinder) service; @@ -149,17 +147,22 @@ public final class EIP extends IntentService { mBound = true; if (mReceiver != null && mPending != null) { - + boolean running = mVpnService.isRunning(); + int resultCode = Activity.RESULT_CANCELED; - if (mPending.equals(ACTION_IS_EIP_RUNNING)) + if (mPending.equals(ACTION_IS_EIP_RUNNING)){ resultCode = (running) ? Activity.RESULT_OK : Activity.RESULT_CANCELED; - if (mPending.equals(ACTION_START_EIP)) + + } + else if (mPending.equals(ACTION_START_EIP)){ resultCode = (running) ? Activity.RESULT_OK : Activity.RESULT_CANCELED; - else if (mPending.equals(ACTION_STOP_EIP)) + } + else if (mPending.equals(ACTION_STOP_EIP)){ resultCode = (running) ? Activity.RESULT_CANCELED : Activity.RESULT_OK; + } Bundle resultData = new Bundle(); resultData.putString(REQUEST_TAG, ACTION_IS_EIP_RUNNING); mReceiver.send(resultCode, resultData); @@ -178,6 +181,7 @@ public final class EIP extends IntentService { mReceiver.send(Activity.RESULT_CANCELED, resultData); } } + }; @@ -190,25 +194,42 @@ public final class EIP extends IntentService { * Note: If the request to bind OpenVpnService is successful, the ResultReceiver * will be notified in {@link onServiceConnected()} */ - private void isRunning() { - Bundle resultData = new Bundle(); - resultData.putString(REQUEST_TAG, ACTION_IS_EIP_RUNNING); - int resultCode = Activity.RESULT_CANCELED; - if (mBound) { - resultCode = (mVpnService.isRunning()) ? Activity.RESULT_OK : Activity.RESULT_CANCELED; - - if (mReceiver != null){ - mReceiver.send(resultCode, resultData); - } - } else { - mPending = ACTION_IS_EIP_RUNNING; - boolean retrieved_vpn_service = retreiveVpnService(); - if(!retrieved_vpn_service && mReceiver != null) { - mReceiver.send(resultCode, resultData); - } - } - } - + + private void isRunning() { + Bundle resultData = new Bundle(); + resultData.putString(REQUEST_TAG, ACTION_IS_EIP_RUNNING); + int resultCode = Activity.RESULT_CANCELED; + if (mBound) { + resultCode = (mVpnService.isRunning()) ? Activity.RESULT_OK : Activity.RESULT_CANCELED; + + if (mReceiver != null){ + mReceiver.send(resultCode, resultData); + } + } else { + mPending = ACTION_IS_EIP_RUNNING; + boolean retrieved_vpn_service = retreiveVpnService(); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + boolean running = false; + try { + running = mVpnService.isRunning(); + } catch (NullPointerException e){ + e.printStackTrace(); + } + + if (retrieved_vpn_service && running && mReceiver != null){ + mReceiver.send(Activity.RESULT_OK, resultData); + } + else{ + mReceiver.send(Activity.RESULT_CANCELED, resultData); + } + } + } + /** * Initiates an EIP connection by selecting a gateway and preparing and sending an * Intent to {@link se.leap.openvpn.LaunchVPN} @@ -250,8 +271,8 @@ public final class EIP extends IntentService { */ private void updateEIPService() { try { - eipDefinition = ConfigHelper.getJsonFromSharedPref(EIP.KEY); - parsedEipSerial = ConfigHelper.getIntFromSharedPref(PARSED_SERIAL); + eipDefinition = new JSONObject(getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).getString(KEY, "")); + parsedEipSerial = getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).getInt(PARSED_SERIAL, 0); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -259,9 +280,9 @@ public final class EIP extends IntentService { if(parsedEipSerial == 0) { // Delete all vpn profiles ProfileManager vpl = ProfileManager.getInstance(context); - Collection<VpnProfile> profiles = vpl.getProfiles(); - for (VpnProfile profile : profiles){ - vpl.removeProfile(context, profile); + VpnProfile[] profiles = (VpnProfile[]) vpl.getProfiles().toArray(new VpnProfile[vpl.getProfiles().size()]); + for (int current_profile = 0; current_profile < profiles.length; current_profile++){ + vpl.removeProfile(context, profiles[current_profile]); } } if (eipDefinition.optInt("serial") > parsedEipSerial) @@ -274,10 +295,62 @@ public final class EIP extends IntentService { * @return The gateway to connect to */ private OVPNGateway selectGateway() { - // TODO Implement gateway selection logic based on TZ or preferences - // TODO Implement search through gateways loaded from SharedPreferences // TODO Remove String arg constructor in favor of findGatewayByName(String) - return new OVPNGateway("first"); + + Calendar cal = Calendar.getInstance(); + int localOffset = cal.get(Calendar.ZONE_OFFSET) / 3600000; + TreeMap<Integer, Set<String>> offsets = new TreeMap<Integer, Set<String>>(); + JSONObject locationsObjects = null; + Iterator<String> locations = null; + try { + locationsObjects = eipDefinition.getJSONObject("locations"); + locations = locationsObjects.keys(); + } catch (JSONException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + while (locations.hasNext()) { + String locationName = locations.next(); + JSONObject location = null; + try { + location = locationsObjects.getJSONObject(locationName); + + // Distance along the numberline of Prime Meridian centric, assumes UTC-11 through UTC+12 + int dist = Math.abs(localOffset - location.optInt("timezone")); + // Farther than 12 timezones and it's shorter around the "back" + if (dist > 12) + dist = 12 - (dist -12); // Well i'll be. Absolute values make equations do funny things. + + Set<String> set = offsets.get(dist); + if (set == null) set = new HashSet<String>(); + set.add(locationName); + offsets.put(dist, set); + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + String closestLocation = offsets.isEmpty() ? "" : offsets.firstEntry().getValue().iterator().next(); + JSONArray gateways = null; + String chosenHost = null; + try { + gateways = eipDefinition.getJSONArray("gateways"); + for (int i = 0; i < gateways.length(); i++) { + JSONObject gw = gateways.getJSONObject(i); + if ( gw.getString("location").equalsIgnoreCase(closestLocation) || closestLocation.isEmpty()){ + chosenHost = gw.getString("host"); + break; + } + } + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return new OVPNGateway(chosenHost); } /** @@ -315,8 +388,7 @@ public final class EIP extends IntentService { e.printStackTrace(); } } - - ConfigHelper.saveSharedPref(PARSED_SERIAL, eipDefinition.optInt(Provider.API_RETURN_SERIAL)); + getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putInt(PARSED_SERIAL, eipDefinition.optInt(Provider.API_RETURN_SERIAL)).commit(); } /** @@ -352,12 +424,10 @@ public final class EIP extends IntentService { ProfileManager vpl = ProfileManager.getInstance(context); try { - if ( mName == "first" ) { - mName = vpl.getProfiles().iterator().next().mName; - } - - mVpnProfile = vpl.getProfileByName(mName); - + if ( mName == null ) + mVpnProfile = vpl.getProfiles().iterator().next(); + else + mVpnProfile = vpl.getProfileByName(mName); } catch (NoSuchElementException e) { updateEIPService(); this.loadVpnProfile(); // FIXME catch infinite loops @@ -383,9 +453,10 @@ public final class EIP extends IntentService { for (Iterator<VpnProfile> it = profiles.iterator(); it.hasNext(); ){ VpnProfile p = it.next(); try { - if ( p.mName.contains( gateway.getString("host") ) ) + if ( p.mName.equalsIgnoreCase( gateway.getString("host") ) ){ it.remove(); vpl.removeProfile(context, p); + } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); diff --git a/src/se/leap/bitmaskclient/EipServiceFragment.java b/src/se/leap/bitmaskclient/EipServiceFragment.java index b409394b..74755a5c 100644 --- a/src/se/leap/bitmaskclient/EipServiceFragment.java +++ b/src/se/leap/bitmaskclient/EipServiceFragment.java @@ -24,7 +24,7 @@ import android.widget.RelativeLayout; import android.widget.Switch; import android.widget.TextView; -public class EipServiceFragment extends Fragment implements StateListener, OnClickListener, OnCheckedChangeListener { +public class EipServiceFragment extends Fragment implements StateListener, OnCheckedChangeListener { private static final String IS_EIP_PENDING = "is_eip_pending"; @@ -58,7 +58,6 @@ public class EipServiceFragment extends Fragment implements StateListener, OnCli eipFragment.findViewById(R.id.eipProgress).setVisibility(View.VISIBLE); eipStatus = (TextView) eipFragment.findViewById(R.id.eipStatus); - eipStatus.setOnClickListener(this); eipSwitch = (Switch) eipFragment.findViewById(R.id.eipSwitch); @@ -107,21 +106,6 @@ public class EipServiceFragment extends Fragment implements StateListener, OnCli } @Override - public void onClick(View buttonView) { - if (buttonView.equals(eipStatus)) - showEIPLog(); - } - - /** - * Launches the se.leap.openvpn.LogWindow Activity showing detailed OpenVPN log - */ - public void showEIPLog(){ - Intent intent = new Intent(getActivity().getBaseContext(),LogWindow.class); - intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); - startActivity(intent); - } - - @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (buttonView.equals(eipSwitch) && !eipAutoSwitched){ if (isChecked){ diff --git a/src/se/leap/bitmaskclient/LeapHttpClient.java b/src/se/leap/bitmaskclient/LeapHttpClient.java index 837da236..885b5105 100644 --- a/src/se/leap/bitmaskclient/LeapHttpClient.java +++ b/src/se/leap/bitmaskclient/LeapHttpClient.java @@ -34,7 +34,6 @@ import android.content.Context; * */ public class LeapHttpClient extends DefaultHttpClient { - final Context context; private static LeapHttpClient client; @@ -43,10 +42,8 @@ public class LeapHttpClient extends DefaultHttpClient { * @param context * @return the new client. */ - public static LeapHttpClient getInstance(Context context) { + public static LeapHttpClient getInstance(String cert_string) { if(client == null) { - client = new LeapHttpClient(context); - String cert_string = ConfigHelper.getStringFromSharedPref(Provider.CA_CERT); if(cert_string != null) { ConfigHelper.addTrustedCertificate("provider_ca_certificate", cert_string); } @@ -77,8 +74,4 @@ public class LeapHttpClient extends DefaultHttpClient { throw new AssertionError(e); } } - - public LeapHttpClient(Context context) { - this.context = context; - } } diff --git a/src/se/leap/bitmaskclient/LeapSRPSession.java b/src/se/leap/bitmaskclient/LeapSRPSession.java index 0849f777..a317d95e 100644 --- a/src/se/leap/bitmaskclient/LeapSRPSession.java +++ b/src/se/leap/bitmaskclient/LeapSRPSession.java @@ -41,7 +41,8 @@ public class LeapSRPSession { final public static String M1 = "M1"; final public static String M2 = "M2"; final public static String TOKEN = "token"; - + final public static String AUTHORIZATION_HEADER= "Authorization"; + private SRPParameters params; private String username; private String password; diff --git a/src/se/leap/bitmaskclient/ProviderAPI.java b/src/se/leap/bitmaskclient/ProviderAPI.java index ff6dd852..7aafa2e3 100644 --- a/src/se/leap/bitmaskclient/ProviderAPI.java +++ b/src/se/leap/bitmaskclient/ProviderAPI.java @@ -444,25 +444,6 @@ public class ProviderAPI extends IntentService { * @return a bundle with a boolean value mapped to a key named RESULT_KEY, and which is true if the update was successful. */ private Bundle setUpProvider(Bundle task) { -//<<<<<<< HEAD -// Bundle result = new Bundle(); -// int progress = 0; -// boolean danger_on = task.getBoolean(ProviderItem.DANGER_ON); -// String provider_main_url = task.getString(Provider.MAIN_URL); -// if(downloadCACert(provider_main_url, danger_on)) { -// broadcast_progress(progress++); -// result.putBoolean(RESULT_KEY, true); -// if(getAndSetProviderJson(provider_main_url)) { -// broadcast_progress(progress++); -// if(getAndSetEipServiceJson()) -// broadcast_progress(progress++); -// } -// } -// return result; -// } -// -// -//======= int progress = 0; Bundle current_download = new Bundle(); @@ -496,8 +477,8 @@ public class ProviderAPI extends IntentService { private Bundle downloadCACert(String provider_main_url, boolean danger_on) { Bundle result = new Bundle(); String cert_string = downloadWithCommercialCA(provider_main_url + "/ca.crt", danger_on); - if(validCertificate(cert_string)) { - ConfigHelper.saveSharedPref(Provider.CA_CERT, cert_string); + if(validCertificate(cert_string)) { + getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putString(Provider.CA_CERT, cert_string).commit(); result.putBoolean(RESULT_KEY, true); } else { String reason_to_fail = pickErrorMessage(cert_string); @@ -538,8 +519,8 @@ public class ProviderAPI extends IntentService { String name = provider_json.getString(Provider.NAME); //TODO setProviderName(name); - ConfigHelper.saveSharedPref(Provider.KEY, provider_json); - ConfigHelper.saveSharedPref(EIP.ALLOWED_ANON, provider_json.getJSONObject(Provider.SERVICE).getBoolean(EIP.ALLOWED_ANON)); + getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putString(Provider.KEY, provider_json.toString()).commit(); + getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putBoolean(EIP.ALLOWED_ANON, provider_json.getJSONObject(Provider.SERVICE).getBoolean(EIP.ALLOWED_ANON)).commit(); result.putBoolean(RESULT_KEY, true); } catch (JSONException e) { @@ -561,13 +542,13 @@ public class ProviderAPI extends IntentService { Bundle result = new Bundle(); String eip_service_json_string = ""; try { - JSONObject provider_json = ConfigHelper.getJsonFromSharedPref(Provider.KEY); + JSONObject provider_json = new JSONObject(getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).getString(Provider.KEY, "")); String eip_service_url = provider_json.getString(Provider.API_URL) + "/" + provider_json.getString(Provider.API_VERSION) + "/" + EIP.SERVICE_API_PATH; eip_service_json_string = downloadWithProviderCA(eip_service_url, true); JSONObject eip_service_json = new JSONObject(eip_service_json_string); eip_service_json.getInt(Provider.API_RETURN_SERIAL); - - ConfigHelper.saveSharedPref(EIP.KEY, eip_service_json); + + getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putString(EIP.KEY, eip_service_json.toString()).commit(); result.putBoolean(RESULT_KEY, true); } catch (JSONException e) { @@ -620,12 +601,12 @@ public class ProviderAPI extends IntentService { URLConnection url_connection = provider_url.openConnection(); url_connection.setConnectTimeout(seconds_of_timeout*1000); if(!LeapSRPSession.getToken().isEmpty()) - url_connection.addRequestProperty(LeapSRPSession.TOKEN, LeapSRPSession.getToken()); + url_connection.addRequestProperty(LeapSRPSession.AUTHORIZATION_HEADER, "Token token = " + LeapSRPSession.getToken()); json_file_content = new Scanner(url_connection.getInputStream()).useDelimiter("\\A").next(); } catch (MalformedURLException e) { json_file_content = formatErrorMessage(R.string.malformed_url); } catch(SocketTimeoutException e) { - json_file_content = formatErrorMessage(R.string.server_is_down_message); + json_file_content = formatErrorMessage(R.string.server_unreachable_message); } catch (IOException e) { if(provider_url != null) { json_file_content = downloadWithProviderCA(string_url, danger_on); @@ -657,13 +638,13 @@ public class ProviderAPI extends IntentService { (HttpsURLConnection)url.openConnection(); urlConnection.setSSLSocketFactory(getProviderSSLSocketFactory()); if(!LeapSRPSession.getToken().isEmpty()) - urlConnection.addRequestProperty(LeapSRPSession.TOKEN, LeapSRPSession.getToken()); + urlConnection.addRequestProperty(LeapSRPSession.AUTHORIZATION_HEADER, "Token token=" + LeapSRPSession.getToken()); json_file_content = new Scanner(urlConnection.getInputStream()).useDelimiter("\\A").next(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnknownHostException e) { - json_file_content = formatErrorMessage(R.string.server_is_down_message); + json_file_content = formatErrorMessage(R.string.server_unreachable_message); } catch (IOException e) { // The downloaded certificate doesn't validate our https connection. if(danger_on) { @@ -685,7 +666,7 @@ public class ProviderAPI extends IntentService { } private javax.net.ssl.SSLSocketFactory getProviderSSLSocketFactory() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException { - String provider_cert_string = ConfigHelper.getStringFromSharedPref(Provider.CA_CERT); + String provider_cert_string = getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).getString(Provider.CA_CERT,""); java.security.cert.Certificate provider_certificate = ConfigHelper.parseX509CertificateFromString(provider_cert_string); @@ -746,7 +727,7 @@ public class ProviderAPI extends IntentService { System.out.println("String ignoring certificate = " + string); } catch (FileNotFoundException e) { e.printStackTrace(); - string = formatErrorMessage(R.string.server_is_down_message); + string = formatErrorMessage(R.string.server_unreachable_message); } catch (IOException e) { // The downloaded certificate doesn't validate our https connection. e.printStackTrace(); @@ -778,7 +759,7 @@ public class ProviderAPI extends IntentService { int responseCode = urlConnection.getResponseCode(); broadcast_progress(progress++); LeapSRPSession.setToken(""); - Log.d("logout", Integer.toString(responseCode)); + Log.d(TAG, Integer.toString(responseCode)); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -817,11 +798,12 @@ public class ProviderAPI extends IntentService { try { String type_of_certificate = task.getString(ConfigurationWizard.TYPE_OF_CERTIFICATE); - JSONObject provider_json = ConfigHelper.getJsonFromSharedPref(Provider.KEY); + JSONObject provider_json = new JSONObject(getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).getString(Provider.KEY, "")); + String provider_main_url = provider_json.getString(Provider.API_URL); URL new_cert_string_url = new URL(provider_main_url + "/" + provider_json.getString(Provider.API_VERSION) + "/" + EIP.CERTIFICATE); - boolean danger_on = ConfigHelper.getBoolFromSharedPref(ProviderItem.DANGER_ON); + boolean danger_on = getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).getBoolean(ProviderItem.DANGER_ON, false); String cert_string = downloadWithProviderCA(new_cert_string_url.toString(), danger_on); @@ -847,12 +829,12 @@ public class ProviderAPI extends IntentService { try { RSAPrivateKey keyCert = ConfigHelper.parseRsaKeyFromString(keyString); keyString = Base64.encodeToString( keyCert.getEncoded(), Base64.DEFAULT ); - ConfigHelper.saveSharedPref(EIP.PRIVATE_KEY, "-----BEGIN RSA PRIVATE KEY-----\n"+keyString+"-----END RSA PRIVATE KEY-----"); + getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putString(EIP.PRIVATE_KEY, "-----BEGIN RSA PRIVATE KEY-----\n"+keyString+"-----END RSA PRIVATE KEY-----").commit(); X509Certificate certCert = ConfigHelper.parseX509CertificateFromString(certificateString); certificateString = Base64.encodeToString( certCert.getEncoded(), Base64.DEFAULT); - ConfigHelper.saveSharedPref(EIP.CERTIFICATE, "-----BEGIN CERTIFICATE-----\n"+certificateString+"-----END CERTIFICATE-----"); - + getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE).edit().putString(EIP.CERTIFICATE, "-----BEGIN CERTIFICATE-----\n"+certificateString+"-----END CERTIFICATE-----").commit(); + return true; } catch (CertificateException e) { // TODO Auto-generated catch block diff --git a/src/se/leap/bitmaskclient/ProviderDetailFragment.java b/src/se/leap/bitmaskclient/ProviderDetailFragment.java index fd8b29d9..3ed04184 100644 --- a/src/se/leap/bitmaskclient/ProviderDetailFragment.java +++ b/src/se/leap/bitmaskclient/ProviderDetailFragment.java @@ -11,6 +11,7 @@ import android.app.AlertDialog; import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
+import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
@@ -28,7 +29,7 @@ public class ProviderDetailFragment extends DialogFragment { LayoutInflater inflater = getActivity().getLayoutInflater();
View provider_detail_view = inflater.inflate(R.layout.provider_detail_fragment, null);
- JSONObject provider_json = ConfigHelper.getJsonFromSharedPref(Provider.KEY);
+ JSONObject provider_json = new JSONObject(getActivity().getSharedPreferences(Dashboard.SHARED_PREFERENCES, getActivity().MODE_PRIVATE).getString(Provider.KEY, ""));
final TextView domain = (TextView)provider_detail_view.findViewById(R.id.provider_detail_domain);
domain.setText(provider_json.getString(Provider.DOMAIN));
@@ -82,11 +83,9 @@ public class ProviderDetailFragment extends DialogFragment { @Override
public void onCancel(DialogInterface dialog) {
- super.onCancel(dialog); - ConfigHelper.removeFromSharedPref(Provider.KEY);
- ConfigHelper.removeFromSharedPref(ProviderItem.DANGER_ON);
- ConfigHelper.removeFromSharedPref(EIP.ALLOWED_ANON);
- ConfigHelper.removeFromSharedPref(EIP.KEY); + super.onCancel(dialog);
+ SharedPreferences.Editor editor = getActivity().getSharedPreferences(Dashboard.SHARED_PREFERENCES, Activity.MODE_PRIVATE).edit();
+ editor.remove(Provider.KEY).remove(ProviderItem.DANGER_ON).remove(EIP.ALLOWED_ANON).remove(EIP.KEY).commit(); interface_with_configuration_wizard.showAllProviders(); }
diff --git a/src/se/leap/bitmaskclient/ProviderListFragment.java b/src/se/leap/bitmaskclient/ProviderListFragment.java index 45047982..f35cf739 100644 --- a/src/se/leap/bitmaskclient/ProviderListFragment.java +++ b/src/se/leap/bitmaskclient/ProviderListFragment.java @@ -39,7 +39,7 @@ public class ProviderListFragment extends ListFragment { public static String TAG = "provider_list_fragment";
public static String SHOW_ALL_PROVIDERS = "show_all_providers";
-
+ public static String TOP_PADDING = "top padding from providerlistfragment";
private ProviderListAdapter<ProviderItem> content_adapter;
/**
@@ -120,9 +120,8 @@ public class ProviderListFragment extends ListFragment { && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
}
- String top_padding_key = getResources().getString(R.string.top_padding);
- if(getArguments() != null && getArguments().containsKey(top_padding_key)) {
- int topPadding = getArguments().getInt(top_padding_key);
+ if(getArguments() != null && getArguments().containsKey(TOP_PADDING)) {
+ int topPadding = getArguments().getInt(TOP_PADDING);
View current_view = getView();
getView().setPadding(current_view.getPaddingLeft(), topPadding, current_view.getPaddingRight(), current_view.getPaddingBottom());
}
diff --git a/src/se/leap/openvpn/ConfigConverter.java b/src/se/leap/openvpn/ConfigConverter.java deleted file mode 100644 index 3c6bf91e..00000000 --- a/src/se/leap/openvpn/ConfigConverter.java +++ /dev/null @@ -1,454 +0,0 @@ - -package se.leap.openvpn; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.List; -import java.util.Vector; - -import se.leap.bitmaskclient.R; - -import android.app.Activity; -import android.app.AlertDialog; -import android.app.AlertDialog.Builder; -import android.app.ListActivity; -import android.content.ActivityNotFoundException; -import android.content.Intent; -import android.os.Bundle; -import android.os.Environment; -import android.security.KeyChain; -import android.security.KeyChainAliasCallback; -import android.util.Base64; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.widget.ArrayAdapter; -import android.widget.CheckBox; -import se.leap.openvpn.ConfigParser.ConfigParseError; - -public class ConfigConverter extends ListActivity { - - public static final String IMPORT_PROFILE = "se.leap.openvpn.IMPORT_PROFILE"; - - private VpnProfile mResult; - private ArrayAdapter<String> mArrayAdapter; - - private List<String> mPathsegments; - - private String mAliasName=null; - - private int RESULT_INSTALLPKCS12 = 7; - - private String mPossibleName=null; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.config_converter); - } - - - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if(item.getItemId()==R.id.cancel){ - setResult(Activity.RESULT_CANCELED); - finish(); - } else if(item.getItemId()==R.id.ok) { - if(mResult==null) { - log("Importing the config had error, cannot save it"); - return true; - } - - Intent in = installPKCS12(); - - if(in != null) - startActivityForResult(in, RESULT_INSTALLPKCS12); - else - saveProfile(); - - return true; - } - - return super.onOptionsItemSelected(item); - - } - - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - if(requestCode==RESULT_INSTALLPKCS12) { - if(resultCode==Activity.RESULT_OK) { - showCertDialog(); - } - } - - super.onActivityResult(requestCode, resultCode, data); - } - - private void saveProfile() { - Intent result = new Intent(); - ProfileManager vpl = ProfileManager.getInstance(this); - - if(((CheckBox)findViewById(R.id.correcttls)).isChecked() && isOldCNFormat()) { - convertTLSRemote(); - } - - setUniqueProfileName(vpl); - vpl.addProfile(mResult); - vpl.saveProfile(this, mResult); - vpl.saveProfileList(this); - result.putExtra(VpnProfile.EXTRA_PROFILEUUID,mResult.getUUID().toString()); - setResult(Activity.RESULT_OK, result); - finish(); - } - - - - private void convertTLSRemote() { - if(mResult.mRemoteCN.startsWith("/")) - mResult.mRemoteCN = mResult.mRemoteCN.substring(1); - mResult.mRemoteCN = mResult.mRemoteCN.replace("/", ", "); - } - - public void showCertDialog () { - try { - KeyChain.choosePrivateKeyAlias(this, - new KeyChainAliasCallback() { - - public void alias(String alias) { - // Credential alias selected. Remember the alias selection for future use. - mResult.mAlias=alias; - saveProfile(); - } - - - }, - new String[] {"RSA"}, // List of acceptable key types. null for any - null, // issuer, null for any - mResult.mServerName, // host name of server requesting the cert, null if unavailable - -1, // port of server requesting the cert, -1 if unavailable - mAliasName); // alias to preselect, null if unavailable - } catch (ActivityNotFoundException anf) { - Builder ab = new AlertDialog.Builder(this); - ab.setTitle(R.string.broken_image_cert_title); - ab.setMessage(R.string.broken_image_cert); - ab.setPositiveButton(android.R.string.ok, null); - ab.show(); - } - } - - - private Intent installPKCS12() { - - if(!((CheckBox)findViewById(R.id.importpkcs12)).isChecked()) { - setAuthTypeToEmbeddedPKCS12(); - return null; - - } - String pkcs12datastr = mResult.mPKCS12Filename; - if(pkcs12datastr!=null && pkcs12datastr.startsWith(VpnProfile.INLINE_TAG)) { - Intent inkeyintent = KeyChain.createInstallIntent(); - - pkcs12datastr= pkcs12datastr.substring(VpnProfile.INLINE_TAG.length()); - - - byte[] pkcs12data = Base64.decode(pkcs12datastr, Base64.DEFAULT); - - - inkeyintent.putExtra(KeyChain.EXTRA_PKCS12,pkcs12data ); - - if(mAliasName.equals("")) - mAliasName=null; - - if(mAliasName!=null){ - inkeyintent.putExtra(KeyChain.EXTRA_NAME, mAliasName); - } - return inkeyintent; - - } - return null; - } - - - - private void setAuthTypeToEmbeddedPKCS12() { - if(mResult.mPKCS12Filename!=null && mResult.mPKCS12Filename.startsWith(VpnProfile.INLINE_TAG)) { - if(mResult.mAuthenticationType==VpnProfile.TYPE_USERPASS_KEYSTORE) - mResult.mAuthenticationType=VpnProfile.TYPE_USERPASS_PKCS12; - - if(mResult.mAuthenticationType==VpnProfile.TYPE_KEYSTORE) - mResult.mAuthenticationType=VpnProfile.TYPE_PKCS12; - - } - } - - - - - - private void setUniqueProfileName(ProfileManager vpl) { - int i=0; - - String newname = mPossibleName; - - while(vpl.getProfileByName(newname)!=null) { - i++; - if(i==1) - newname = getString(R.string.converted_profile); - else - newname = getString(R.string.converted_profile_i,i); - } - - mResult.mName=newname; - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - MenuInflater inflater = getMenuInflater(); - inflater.inflate(R.menu.import_menu, menu); - return true; - } - - private String embedFile(String filename) { - return embedFile(filename, false); - } - - private String embedFile(String filename, boolean base64encode) - { - if(filename==null) - return null; - - // Already embedded, nothing to do - if(filename.startsWith(VpnProfile.INLINE_TAG)) - return filename; - - File possibleFile = findFile(filename); - if(possibleFile==null) - return filename; - else - return readFileContent(possibleFile,base64encode); - - } - - private File findFile(String filename) { - File foundfile =findFileRaw(filename); - - if (foundfile==null && filename!=null && !filename.equals("")) - log(R.string.import_could_not_open,filename); - - return foundfile; - } - - - - private File findFileRaw(String filename) - { - if(filename == null || filename.equals("")) - return null; - - // Try diffent path relative to /mnt/sdcard - File sdcard = Environment.getExternalStorageDirectory(); - File root = new File("/"); - - Vector<File> dirlist = new Vector<File>(); - - for(int i=mPathsegments.size()-1;i >=0 ;i--){ - String path = ""; - for (int j = 0;j<=i;j++) { - path += "/" + mPathsegments.get(j); - } - dirlist.add(new File(path)); - } - dirlist.add(sdcard); - dirlist.add(root); - - - String[] fileparts = filename.split("/"); - for(File rootdir:dirlist){ - String suffix=""; - for(int i=fileparts.length-1; i >=0;i--) { - if(i==fileparts.length-1) - suffix = fileparts[i]; - else - suffix = fileparts[i] + "/" + suffix; - - File possibleFile = new File(rootdir,suffix); - if(!possibleFile.canRead()) - continue; - - // read the file inline - return possibleFile; - - } - } - return null; - } - - String readFileContent(File possibleFile, boolean base64encode) { - byte [] filedata; - try { - filedata = readBytesFromFile(possibleFile); - } catch (IOException e) { - log(e.getLocalizedMessage()); - return null; - } - - String data; - if(base64encode) { - data = Base64.encodeToString(filedata, Base64.DEFAULT); - } else { - data = new String(filedata); - - } - return VpnProfile.INLINE_TAG + data; - - } - - - private byte[] readBytesFromFile(File file) throws IOException { - InputStream input = new FileInputStream(file); - - long len= file.length(); - - - // Create the byte array to hold the data - byte[] bytes = new byte[(int) len]; - - // Read in the bytes - int offset = 0; - int bytesRead = 0; - while (offset < bytes.length - && (bytesRead=input.read(bytes, offset, bytes.length-offset)) >= 0) { - offset += bytesRead; - } - - input.close(); - return bytes; - } - - void embedFiles() { - // This where I would like to have a c++ style - // void embedFile(std::string & option) - - if (mResult.mPKCS12Filename!=null) { - File pkcs12file = findFileRaw(mResult.mPKCS12Filename); - if(pkcs12file!=null) { - mAliasName = pkcs12file.getName().replace(".p12", ""); - } else { - mAliasName = "Imported PKCS12"; - } - } - - - mResult.mCaFilename = embedFile(mResult.mCaFilename); - mResult.mClientCertFilename = embedFile(mResult.mClientCertFilename); - mResult.mClientKeyFilename = embedFile(mResult.mClientKeyFilename); - mResult.mTLSAuthFilename = embedFile(mResult.mTLSAuthFilename); - mResult.mPKCS12Filename = embedFile(mResult.mPKCS12Filename,true); - - - if(mResult.mUsername == null && mResult.mPassword != null ){ - String data =embedFile(mResult.mPassword); - ConfigParser.useEmbbedUserAuth(mResult, data); - } - } - - - @Override - protected void onStart() { - super.onStart(); - - mArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); - getListView().setAdapter(mArrayAdapter); - final android.content.Intent intent = getIntent (); - - if (intent != null) - { - final android.net.Uri data = intent.getData (); - if (data != null) - { - //log(R.string.import_experimental); - log(R.string.importing_config,data.toString()); - try { - if(data.getScheme().equals("file")) { - mPossibleName = data.getLastPathSegment(); - if(mPossibleName!=null){ - mPossibleName =mPossibleName.replace(".ovpn", ""); - mPossibleName =mPossibleName.replace(".conf", ""); - } - } - InputStream is = getContentResolver().openInputStream(data); - mPathsegments = data.getPathSegments(); - - doImport(is); - } catch (FileNotFoundException e) { - log(R.string.import_content_resolve_error); - } - } - } - - return; - } - - private void log(String logmessage) { - mArrayAdapter.add(logmessage); - } - - private void doImport(InputStream is) { - ConfigParser cp = new ConfigParser(); - try { - InputStreamReader isr = new InputStreamReader(is); - - cp.parseConfig(isr); - VpnProfile vp = cp.convertProfile(); - mResult = vp; - embedFiles(); - displayWarnings(); - log(R.string.import_done); - return; - - } catch (IOException e) { - log(R.string.error_reading_config_file); - log(e.getLocalizedMessage()); - } catch (ConfigParseError e) { - log(R.string.error_reading_config_file); - log(e.getLocalizedMessage()); - } - mResult=null; - - } - - private void displayWarnings() { - if(mResult.mUseCustomConfig) { - log(R.string.import_warning_custom_options); - String copt = mResult.mCustomConfigOptions; - if(copt.startsWith("#")) { - int until = copt.indexOf('\n'); - copt = copt.substring(until+1); - } - - log(copt); - } - - if(mResult.mAuthenticationType==VpnProfile.TYPE_KEYSTORE || - mResult.mAuthenticationType == VpnProfile.TYPE_USERPASS_KEYSTORE) { - findViewById(R.id.importpkcs12).setVisibility(View.VISIBLE); - } - - if (isOldCNFormat()) - findViewById(R.id.correcttls).setVisibility(View.VISIBLE); - } - - private boolean isOldCNFormat() { - return mResult.mCheckRemoteCN && mResult.mRemoteCN.contains("/") && ! mResult.mRemoteCN.contains("_"); - } - - private void log(int ressourceId, Object... formatArgs) { - log(getString(ressourceId,formatArgs)); - } -} diff --git a/src/se/leap/openvpn/ConfigParser.java b/src/se/leap/openvpn/ConfigParser.java index 36585d29..df4eae1b 100644 --- a/src/se/leap/openvpn/ConfigParser.java +++ b/src/se/leap/openvpn/ConfigParser.java @@ -357,7 +357,7 @@ public class ConfigParser { } // Parse remote config - Vector<String> location = getOption("location",1,2); + Vector<String> location = getOption("location",0,2); if(location != null && location.size() == 2){ np.mLocation = location.get(1).replace("__", ", "); } diff --git a/src/se/leap/openvpn/FaqFragment.java b/src/se/leap/openvpn/FaqFragment.java deleted file mode 100644 index dc498087..00000000 --- a/src/se/leap/openvpn/FaqFragment.java +++ /dev/null @@ -1,43 +0,0 @@ -package se.leap.openvpn; - -import android.app.Fragment; -import android.os.Bundle; -import android.text.Html; -import android.text.method.LinkMovementMethod; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; -import se.leap.bitmaskclient.R; - -public class FaqFragment extends Fragment { - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View v= inflater.inflate(R.layout.faq, container, false); - - insertHtmlEntry(v,R.id.broken_images_faq,R.string.broken_images_faq); - insertHtmlEntry(v,R.id.faq_howto,R.string.faq_howto); - insertHtmlEntry(v, R.id.baterry_consumption, R.string.baterry_consumption); - insertHtmlEntry(v, R.id.faq_tethering, R.string.faq_tethering); - - return v; - - - - } - - private void insertHtmlEntry (View v, int viewId, int stringId) { - TextView faqitem = (TextView) v.findViewById(viewId); - faqitem.setText(Html.fromHtml(getActivity().getString(stringId))); - faqitem.setMovementMethod(LinkMovementMethod.getInstance()); - } - -} diff --git a/src/se/leap/openvpn/FileProvider.java b/src/se/leap/openvpn/FileProvider.java deleted file mode 100644 index d2714b2c..00000000 --- a/src/se/leap/openvpn/FileProvider.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package se.leap.openvpn; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import android.content.ContentProvider; -import android.content.ContentProvider.PipeDataWriter; -import android.content.ContentValues; -import android.content.res.AssetFileDescriptor; -import android.database.Cursor; -import android.database.MatrixCursor; -import android.net.Uri; -import android.os.Bundle; -import android.os.ParcelFileDescriptor; -import android.provider.OpenableColumns; -import android.util.Log; - -/** - * A very simple content provider that can serve arbitrary asset files from - * our .apk. - */ -public class FileProvider extends ContentProvider -implements PipeDataWriter<InputStream> { - @Override - public boolean onCreate() { - return true; - } - - @Override - public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, - String sortOrder) { - try { - File dumpfile = getFileFromURI(uri); - - - MatrixCursor c = new MatrixCursor(projection); - - Object[] row = new Object[projection.length]; - int i=0; - for (String r:projection) { - if(r.equals(OpenableColumns.SIZE)) - row[i] = dumpfile.length(); - if(r.equals(OpenableColumns.DISPLAY_NAME)) - row[i] = dumpfile.getName(); - i++; - } - c.addRow(row); - return c; - } catch (FileNotFoundException e) { - e.printStackTrace(); - return null; - } - - - } - - @Override - public Uri insert(Uri uri, ContentValues values) { - // Don't support inserts. - return null; - } - - @Override - public int delete(Uri uri, String selection, String[] selectionArgs) { - // Don't support deletes. - return 0; - } - - @Override - public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { - // Don't support updates. - return 0; - } - - @Override - public String getType(Uri uri) { - // For this sample, assume all files are .apks. - return "application/octet-stream"; - } - - @Override - public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { - File dumpfile = getFileFromURI(uri); - - try { - - InputStream is = new FileInputStream(dumpfile); - // Start a new thread that pipes the stream data back to the caller. - return new AssetFileDescriptor( - openPipeHelper(uri, null, null, is, this), 0, - dumpfile.length()); - } catch (IOException e) { - FileNotFoundException fnf = new FileNotFoundException("Unable to open minidump " + uri); - throw fnf; - } - } - - private File getFileFromURI(Uri uri) throws FileNotFoundException { - // Try to open an asset with the given name. - String path = uri.getPath(); - if(path.startsWith("/")) - path = path.replaceFirst("/", ""); - - // I think this already random enough, no need for magic secure cookies - // 1f9563a4-a1f5-2165-255f2219-111823ef.dmp - if (!path.matches("^[0-9a-z-.]*(dmp|dmp.log)$")) - throw new FileNotFoundException("url not in expect format " + uri); - File cachedir = getContext().getCacheDir(); - File dumpfile = new File(cachedir,path); - return dumpfile; - } - - @Override - public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType, - Bundle opts, InputStream args) { - // Transfer data from the asset to the pipe the client is reading. - byte[] buffer = new byte[8192]; - int n; - FileOutputStream fout = new FileOutputStream(output.getFileDescriptor()); - try { - while ((n=args.read(buffer)) >= 0) { - fout.write(buffer, 0, n); - } - } catch (IOException e) { - Log.i("OpenVPNFileProvider", "Failed transferring", e); - } finally { - try { - args.close(); - } catch (IOException e) { - } - try { - fout.close(); - } catch (IOException e) { - } - } - } -} diff --git a/src/se/leap/openvpn/FileSelect.java b/src/se/leap/openvpn/FileSelect.java deleted file mode 100644 index 4b88e7a7..00000000 --- a/src/se/leap/openvpn/FileSelect.java +++ /dev/null @@ -1,209 +0,0 @@ -package se.leap.openvpn; - - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; - -import se.leap.bitmaskclient.R; - -import android.app.ActionBar; -import android.app.ActionBar.Tab; -import android.app.Activity; -import android.app.AlertDialog; -import android.app.AlertDialog.Builder; -import android.app.Fragment; -import android.app.FragmentTransaction; -import android.content.Intent; -import android.os.Bundle; -import android.os.Environment; -import android.util.Base64; - -public class FileSelect extends Activity { - public static final String RESULT_DATA = "RESULT_PATH"; - public static final String START_DATA = "START_DATA"; - public static final String WINDOW_TITLE = "WINDOW_TILE"; - public static final String NO_INLINE_SELECTION = "se.leap.openvpn.NO_INLINE_SELECTION"; - public static final String SHOW_CLEAR_BUTTON = "se.leap.openvpn.SHOW_CLEAR_BUTTON"; - public static final String DO_BASE64_ENCODE = "se.leap.openvpn.BASE64ENCODE"; - - private FileSelectionFragment mFSFragment; - private InlineFileTab mInlineFragment; - private String mData; - private Tab inlineFileTab; - private Tab fileExplorerTab; - private boolean mNoInline; - private boolean mShowClear; - private boolean mBase64Encode; - - - public void onCreate(Bundle savedInstanceState) - { - super.onCreate(savedInstanceState); - setContentView(R.layout.file_dialog); - - mData = getIntent().getStringExtra(START_DATA); - if(mData==null) - mData=Environment.getExternalStorageDirectory().getPath(); - - String title = getIntent().getStringExtra(WINDOW_TITLE); - int titleId = getIntent().getIntExtra(WINDOW_TITLE, 0); - if(titleId!=0) - title =getString(titleId); - if(title!=null) - setTitle(title); - - mNoInline = getIntent().getBooleanExtra(NO_INLINE_SELECTION, false); - mShowClear = getIntent().getBooleanExtra(SHOW_CLEAR_BUTTON, false); - mBase64Encode = getIntent().getBooleanExtra(DO_BASE64_ENCODE, false); - - ActionBar bar = getActionBar(); - bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); - fileExplorerTab = bar.newTab().setText(R.string.file_explorer_tab); - inlineFileTab = bar.newTab().setText(R.string.inline_file_tab); - - mFSFragment = new FileSelectionFragment(); - fileExplorerTab.setTabListener(new MyTabsListener<FileSelectionFragment>(this, mFSFragment)); - bar.addTab(fileExplorerTab); - - if(!mNoInline) { - mInlineFragment = new InlineFileTab(); - inlineFileTab.setTabListener(new MyTabsListener<InlineFileTab>(this, mInlineFragment)); - bar.addTab(inlineFileTab); - } else { - mFSFragment.setNoInLine(); - } - - - } - - protected boolean showClear() { - if(mData == null || mData.equals("")) - return false; - else - return mShowClear; - } - - protected class MyTabsListener<T extends Fragment> implements ActionBar.TabListener - { - private Fragment mFragment; - private boolean mAdded=false; - - public MyTabsListener( Activity activity, Fragment fragment){ - this.mFragment = fragment; - } - - public void onTabSelected(Tab tab, FragmentTransaction ft) { - // Check if the fragment is already initialized - if (!mAdded) { - // If not, instantiate and add it to the activity - ft.add(android.R.id.content, mFragment); - mAdded =true; - } else { - // If it exists, simply attach it in order to show it - ft.attach(mFragment); - } - } - - @Override - public void onTabUnselected(Tab tab, FragmentTransaction ft) { - ft.detach(mFragment); - } - - @Override - public void onTabReselected(Tab tab, FragmentTransaction ft) { - - } - } - - public void importFile(String path) { - File ifile = new File(path); - Exception fe = null; - try { - - String data =VpnProfile.INLINE_TAG; - - byte[] filedata = readBytesFromFile(ifile) ; - if(mBase64Encode) - data += Base64.encodeToString(filedata, Base64.DEFAULT); - else - data += new String(filedata); - - mData =data; - mInlineFragment.setData(data); - getActionBar().selectTab(inlineFileTab); - } catch (FileNotFoundException e) { - fe = e; - } catch (IOException e) { - fe =e; - } - if(fe!=null) { - Builder ab = new AlertDialog.Builder(this); - ab.setTitle(R.string.error_importing_file); - ab.setMessage(getString(R.string.import_error_message) + "\n" + fe.getLocalizedMessage()); - ab.setPositiveButton(android.R.string.ok, null); - ab.show(); - } - } - - private byte[] readBytesFromFile(File file) throws IOException { - InputStream input = new FileInputStream(file); - - long len= file.length(); - - - // Create the byte array to hold the data - byte[] bytes = new byte[(int) len]; - - // Read in the bytes - int offset = 0; - int bytesRead = 0; - while (offset < bytes.length - && (bytesRead=input.read(bytes, offset, bytes.length-offset)) >= 0) { - offset += bytesRead; - } - - input.close(); - return bytes; - } - - - public void setFile(String path) { - Intent intent = new Intent(); - intent.putExtra(RESULT_DATA, path); - setResult(Activity.RESULT_OK,intent); - finish(); - } - - public String getSelectPath() { - if(!mData.startsWith(VpnProfile.INLINE_TAG)) - return mData; - else - return Environment.getExternalStorageDirectory().getPath(); - } - - public CharSequence getInlineData() { - if(mData.startsWith(VpnProfile.INLINE_TAG)) - return mData.substring(VpnProfile.INLINE_TAG.length()); - else - return ""; - } - - public void clearData() { - Intent intent = new Intent(); - intent.putExtra(RESULT_DATA, (String)null); - setResult(Activity.RESULT_OK,intent); - finish(); - - } - - public void saveInlineData(String string) { - Intent intent = new Intent(); - intent.putExtra(RESULT_DATA, string); - setResult(Activity.RESULT_OK,intent); - finish(); - - } -} diff --git a/src/se/leap/openvpn/FileSelectLayout.java b/src/se/leap/openvpn/FileSelectLayout.java deleted file mode 100644 index ec5f3636..00000000 --- a/src/se/leap/openvpn/FileSelectLayout.java +++ /dev/null @@ -1,92 +0,0 @@ -package se.leap.openvpn; - -import android.app.Fragment; -import android.content.Context; -import android.content.Intent; -import android.content.res.TypedArray; -import android.util.AttributeSet; -import android.view.View; -import android.view.View.OnClickListener; -import android.widget.Button; -import android.widget.LinearLayout; -import android.widget.TextView; -import se.leap.bitmaskclient.R; - - -public class FileSelectLayout extends LinearLayout implements OnClickListener { - - private TextView mDataView; - private String mData; - private Fragment mFragment; - private int mTaskId; - private Button mSelectButton; - private boolean mBase64Encode; - private String mTitle; - private boolean mShowClear; - - public FileSelectLayout( Context context,AttributeSet attrset) { - super(context,attrset); - inflate(getContext(), R.layout.file_select, this); - - TypedArray ta = context.obtainStyledAttributes(attrset,R.styleable.FileSelectLayout); - - mTitle = ta.getString(R.styleable.FileSelectLayout_title); - - TextView tview = (TextView) findViewById(R.id.file_title); - tview.setText(mTitle); - - mDataView = (TextView) findViewById(R.id.file_selected_item); - mSelectButton = (Button) findViewById(R.id.file_select_button); - mSelectButton.setOnClickListener(this); - - } - - public void setFragment(Fragment fragment, int i) - { - mTaskId = i; - mFragment = fragment; - } - - public void getCertificateFileDialog() { - Intent startFC = new Intent(getContext(),FileSelect.class); - startFC.putExtra(FileSelect.START_DATA, mData); - startFC.putExtra(FileSelect.WINDOW_TITLE,mTitle); - if(mBase64Encode) - startFC.putExtra(FileSelect.DO_BASE64_ENCODE, true); - if(mShowClear) - startFC.putExtra(FileSelect.SHOW_CLEAR_BUTTON, true); - mFragment.startActivityForResult(startFC,mTaskId); - } - - - public String getData() { - return mData; - } - - public void setData(String data) { - mData = data; - if(data==null) - mDataView.setText(mFragment.getString(R.string.no_data)); - else if(mData.startsWith(VpnProfile.INLINE_TAG)) - mDataView.setText(R.string.inline_file_data); - else - mDataView.setText(data); - - } - - @Override - public void onClick(View v) { - if(v == mSelectButton) { - getCertificateFileDialog(); - } - } - - public void setBase64Encode() { - mBase64Encode =true; - } - - public void setShowClear() { - mShowClear=true; - } - -} diff --git a/src/se/leap/openvpn/FileSelectionFragment.java b/src/se/leap/openvpn/FileSelectionFragment.java deleted file mode 100644 index 80cb2c62..00000000 --- a/src/se/leap/openvpn/FileSelectionFragment.java +++ /dev/null @@ -1,266 +0,0 @@ -package se.leap.openvpn; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.TreeMap; - -import se.leap.bitmaskclient.R; - -import android.app.AlertDialog; -import android.app.ListFragment; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.ViewGroup; -import android.widget.Button; -import android.widget.ListView; -import android.widget.SimpleAdapter; -import android.widget.TextView; - -/** - * Activity para escolha de arquivos/diretorios. - * - * @author android - * - */ -public class FileSelectionFragment extends ListFragment { - - private static final String ITEM_KEY = "key"; - private static final String ITEM_IMAGE = "image"; - private static final String ROOT = "/"; - - - private List<String> path = null; - private TextView myPath; - private ArrayList<HashMap<String, Object>> mList; - - private Button selectButton; - - - private String parentPath; - private String currentPath = ROOT; - - - private String[] formatFilter = null; - - private File selectedFile; - private HashMap<String, Integer> lastPositions = new HashMap<String, Integer>(); - private String mStartPath; - private Button mImportFile; - private Button mClearButton; - private boolean mHideImport=false; - - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View v = inflater.inflate(R.layout.file_dialog_main, container,false); - - myPath = (TextView) v.findViewById(R.id.path); - - selectButton = (Button) v.findViewById(R.id.fdButtonSelect); - selectButton.setEnabled(false); - selectButton.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - if (selectedFile != null) { - ((FileSelect) getActivity()).setFile(selectedFile.getPath()); - - } - } - }); - - mClearButton = (Button) v.findViewById(R.id.fdClear); - mClearButton.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - ((FileSelect) getActivity()).clearData(); - } - }); - if(!((FileSelect) getActivity()).showClear()) { - mClearButton.setVisibility(View.GONE); - mClearButton.setEnabled(false); - } - - - mImportFile = (Button) v.findViewById(R.id.importfile); - mImportFile.setEnabled(false); - mImportFile.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - ((FileSelect) getActivity()).importFile(selectedFile.getPath()); - } - }); - - if(mHideImport== true) { - mImportFile.setVisibility(View.GONE); - } - - - - return v; - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - mStartPath = ((FileSelect) getActivity()).getSelectPath(); - getDir(mStartPath); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - } - - private void getDir(String dirPath) { - - boolean useAutoSelection = dirPath.length() < currentPath.length(); - - Integer position = lastPositions.get(parentPath); - - getDirImpl(dirPath); - - if (position != null && useAutoSelection) { - getListView().setSelection(position); - } - - } - - /** - * Monta a estrutura de arquivos e diretorios filhos do diretorio fornecido. - * - * @param dirPath - * Diretorio pai. - */ - private void getDirImpl(final String dirPath) { - - currentPath = dirPath; - - final List<String> item = new ArrayList<String>(); - path = new ArrayList<String>(); - mList = new ArrayList<HashMap<String, Object>>(); - - File f = new File(currentPath); - File[] files = f.listFiles(); - if (files == null) { - currentPath = ROOT; - f = new File(currentPath); - files = f.listFiles(); - } - - myPath.setText(getText(R.string.location) + ": " + currentPath); - - if (!currentPath.equals(ROOT)) { - - item.add(ROOT); - addItem(ROOT, R.drawable.folder); - path.add(ROOT); - - item.add("../"); - addItem("../", R.drawable.folder); - path.add(f.getParent()); - parentPath = f.getParent(); - - } - - TreeMap<String, String> dirsMap = new TreeMap<String, String>(); - TreeMap<String, String> dirsPathMap = new TreeMap<String, String>(); - TreeMap<String, String> filesMap = new TreeMap<String, String>(); - TreeMap<String, String> filesPathMap = new TreeMap<String, String>(); - for (File file : files) { - if (file.isDirectory()) { - String dirName = file.getName(); - dirsMap.put(dirName, dirName); - dirsPathMap.put(dirName, file.getPath()); - } else { - final String fileName = file.getName(); - final String fileNameLwr = fileName.toLowerCase(); - // se ha um filtro de formatos, utiliza-o - if (formatFilter != null) { - boolean contains = false; - for (int i = 0; i < formatFilter.length; i++) { - final String formatLwr = formatFilter[i].toLowerCase(); - if (fileNameLwr.endsWith(formatLwr)) { - contains = true; - break; - } - } - if (contains) { - filesMap.put(fileName, fileName); - filesPathMap.put(fileName, file.getPath()); - } - // senao, adiciona todos os arquivos - } else { - filesMap.put(fileName, fileName); - filesPathMap.put(fileName, file.getPath()); - } - } - } - item.addAll(dirsMap.tailMap("").values()); - item.addAll(filesMap.tailMap("").values()); - path.addAll(dirsPathMap.tailMap("").values()); - path.addAll(filesPathMap.tailMap("").values()); - - SimpleAdapter fileList = new SimpleAdapter(getActivity(), mList, R.layout.file_dialog_row, new String[] { - ITEM_KEY, ITEM_IMAGE }, new int[] { R.id.fdrowtext, R.id.fdrowimage }); - - for (String dir : dirsMap.tailMap("").values()) { - addItem(dir, R.drawable.folder); - } - - for (String file : filesMap.tailMap("").values()) { - addItem(file, R.drawable.file); - } - - fileList.notifyDataSetChanged(); - - setListAdapter(fileList); - - } - - private void addItem(String fileName, int imageId) { - HashMap<String, Object> item = new HashMap<String, Object>(); - item.put(ITEM_KEY, fileName); - item.put(ITEM_IMAGE, imageId); - mList.add(item); - } - - - @Override - public void onListItemClick(ListView l, View v, int position, long id) { - - File file = new File(path.get(position)); - - if (file.isDirectory()) { - selectButton.setEnabled(false); - mImportFile.setEnabled(false); - - if (file.canRead()) { - lastPositions.put(currentPath, position); - getDir(path.get(position)); - } else { - new AlertDialog.Builder(getActivity()).setIcon(R.drawable.icon) - .setTitle("[" + file.getName() + "] " + getText(R.string.cant_read_folder)) - .setPositiveButton("OK", null).show(); - } - } else { - selectedFile = file; - v.setSelected(true); - selectButton.setEnabled(true); - mImportFile.setEnabled(true); - } - } - - public void setNoInLine() { - mHideImport=true; - } - -} diff --git a/src/se/leap/openvpn/GeneralSettings.java b/src/se/leap/openvpn/GeneralSettings.java deleted file mode 100644 index 93e4818e..00000000 --- a/src/se/leap/openvpn/GeneralSettings.java +++ /dev/null @@ -1,32 +0,0 @@ -package se.leap.openvpn; -import java.io.File; - -import se.leap.bitmaskclient.R; - -import android.os.Bundle; -import android.preference.Preference; -import android.preference.PreferenceFragment; - -public class GeneralSettings extends PreferenceFragment { - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - - // Load the preferences from an XML resource - addPreferencesFromResource(R.xml.general_settings); - Preference loadtun = findPreference("loadTunModule"); - if(!isTunModuleAvailable()) - loadtun.setEnabled(false); - } - - private boolean isTunModuleAvailable() { - // Check if the tun module exists on the file system - if(new File("/system/lib/modules/tun.ko").length() > 10) - return true; - return false; - } - - - }
\ No newline at end of file diff --git a/src/se/leap/openvpn/InlineFileTab.java b/src/se/leap/openvpn/InlineFileTab.java deleted file mode 100644 index 9e8041c0..00000000 --- a/src/se/leap/openvpn/InlineFileTab.java +++ /dev/null @@ -1,66 +0,0 @@ -package se.leap.openvpn; - -import android.app.Fragment; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.EditText; -import se.leap.bitmaskclient.R; - -public class InlineFileTab extends Fragment -{ - - private static final int MENU_SAVE = 0; - private EditText mInlineData; - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - mInlineData.setText(((FileSelect)getActivity()).getInlineData()); - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) - { - - View v = inflater.inflate(R.layout.file_dialog_inline, container, false); - mInlineData =(EditText) v.findViewById(R.id.inlineFileData); - return v; - } - - public void setData(String data) { - if(mInlineData!=null) - mInlineData.setText(data); - - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setHasOptionsMenu(true); - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - menu.add(0, MENU_SAVE, 0, "Use inline data") - .setIcon(android.R.drawable.ic_menu_save) - .setAlphabeticShortcut('u') - .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM - | MenuItem.SHOW_AS_ACTION_WITH_TEXT); - } - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if(item.getItemId()==MENU_SAVE){ - ((FileSelect)getActivity()).saveInlineData(mInlineData.getText().toString()); - return true; - } - return super.onOptionsItemSelected(item); - } - -}
\ No newline at end of file diff --git a/src/se/leap/openvpn/LogWindow.java b/src/se/leap/openvpn/LogWindow.java index c3ce8424..b87c4999 100644 --- a/src/se/leap/openvpn/LogWindow.java +++ b/src/se/leap/openvpn/LogWindow.java @@ -82,7 +82,7 @@ public class LogWindow extends ListActivity implements StateListener { private void shareLog() { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_TEXT, getLogStr()); - shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.ics_openvpn_log_file)); + shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.bitmask_openvpn_log_file)); shareIntent.setType("text/plain"); startActivity(Intent.createChooser(shareIntent, "Send Logfile")); } @@ -227,18 +227,6 @@ public class LogWindow extends ListActivity implements StateListener { } else if(item.getItemId()==R.id.send) { ladapter.shareLog(); - } else if(item.getItemId()==R.id.edit_vpn) { - VpnProfile lastConnectedprofile = ProfileManager.getLastConnectedVpn(); - - if(lastConnectedprofile!=null) { - Intent vprefintent = new Intent(this,VPNPreferences.class) - .putExtra(VpnProfile.EXTRA_PROFILEUUID,lastConnectedprofile.getUUIDString()); - startActivityForResult(vprefintent,START_VPN_CONFIG); - } else { - Toast.makeText(this, R.string.log_no_last_vpn, Toast.LENGTH_LONG).show(); - } - - } return super.onOptionsItemSelected(item); diff --git a/src/se/leap/openvpn/MainActivity.java b/src/se/leap/openvpn/MainActivity.java deleted file mode 100644 index 0a769b4d..00000000 --- a/src/se/leap/openvpn/MainActivity.java +++ /dev/null @@ -1,45 +0,0 @@ -package se.leap.openvpn; - -import java.util.List; - -import se.leap.bitmaskclient.R; - -import android.content.Intent; -import android.preference.PreferenceActivity; - -public class MainActivity extends PreferenceActivity { - - @Override - public void onBuildHeaders(List<Header> target) { - loadHeadersFromResource(R.xml.main_headers, target); - - - String translatedby = getString(R.string.translationby); - if(!translatedby.equals("") && !translatedby.contains("Arne Schwabe")) { - Header translation = new Header(); - translation.title = getString(R.string.translation); - translation.summary = translatedby; - target.add(translation); - } - - if(SendDumpActivity.getLastestDump(this)!=null) { - Header sendDump = new Header(); - sendDump.titleRes = R.string.send_minidump; - sendDump.summaryRes = R.string.send_minidump_summary; - sendDump.intent = new Intent(this,SendDumpActivity.class); - target.add(sendDump); - } - - } - - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); - - System.out.println(data); - - - } - - -} diff --git a/src/se/leap/openvpn/OnBootReceiver.java b/src/se/leap/openvpn/OnBootReceiver.java deleted file mode 100644 index d97097c3..00000000 --- a/src/se/leap/openvpn/OnBootReceiver.java +++ /dev/null @@ -1,33 +0,0 @@ -package se.leap.openvpn; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; - - -public class OnBootReceiver extends BroadcastReceiver { - - // Debug: am broadcast -a android.intent.action.BOOT_COMPLETED - @Override - public void onReceive(Context context, Intent intent) { - - final String action = intent.getAction(); - - if(Intent.ACTION_BOOT_COMPLETED.equals(action)) { - VpnProfile bootProfile = ProfileManager.getOnBootProfile(context); - if(bootProfile != null) { - lauchVPN(bootProfile, context); - } - } - } - - void lauchVPN(VpnProfile profile,Context context) { - Intent startVpnIntent = new Intent(Intent.ACTION_MAIN); - startVpnIntent.setClass(context, LaunchVPN.class); - startVpnIntent.putExtra(LaunchVPN.EXTRA_KEY,profile.getUUIDString()); - startVpnIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startVpnIntent.putExtra(LaunchVPN.EXTRA_HIDELOG, true); - - context.startActivity(startVpnIntent); - } -} diff --git a/src/se/leap/openvpn/OpenVpnPreferencesFragment.java b/src/se/leap/openvpn/OpenVpnPreferencesFragment.java deleted file mode 100644 index 190a48fe..00000000 --- a/src/se/leap/openvpn/OpenVpnPreferencesFragment.java +++ /dev/null @@ -1,52 +0,0 @@ -package se.leap.openvpn;
-
-import android.os.Bundle;
-import android.preference.PreferenceFragment;
-import se.leap.bitmaskclient.R;
-
-public abstract class OpenVpnPreferencesFragment extends PreferenceFragment {
-
- protected VpnProfile mProfile;
-
- protected abstract void loadSettings();
- protected abstract void saveSettings();
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- String profileUUID = getArguments().getString(getActivity().getPackageName() + ".profileUUID");
- mProfile = ProfileManager.get(getActivity(),profileUUID);
- getActivity().setTitle(getString(R.string.edit_profile_title, mProfile.getName()));
-
- }
-
- @Override
- public void onPause() {
- super.onPause();
- saveSettings();
- }
-
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
- if(savedInstanceState!=null) {
- String profileUUID=savedInstanceState.getString(VpnProfile.EXTRA_PROFILEUUID);
- mProfile = ProfileManager.get(getActivity(),profileUUID);
- loadSettings();
- }
- }
-
- @Override
- public void onStop() {
- // TODO Auto-generated method stub
- super.onStop();
- }
-
- @Override
- public void onSaveInstanceState (Bundle outState) {
- super.onSaveInstanceState(outState);
- saveSettings();
- outState.putString(VpnProfile.EXTRA_PROFILEUUID, mProfile.getUUIDString());
- }
-}
diff --git a/src/se/leap/openvpn/SendDumpActivity.java b/src/se/leap/openvpn/SendDumpActivity.java deleted file mode 100644 index 20194db0..00000000 --- a/src/se/leap/openvpn/SendDumpActivity.java +++ /dev/null @@ -1,59 +0,0 @@ -package se.leap.openvpn; - -import java.io.File; -import java.util.ArrayList; -import android.app.Activity; -import android.content.Context; -import android.content.Intent; -import android.net.Uri; - -public class SendDumpActivity extends Activity { - - protected void onStart() { - super.onStart(); - emailMiniDumps(); - finish(); - }; - - public void emailMiniDumps() - { - //need to "send multiple" to get more than one attachment - final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE); - emailIntent.setType("*/*"); - emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, - new String[]{"Arne Schwabe <arne@rfc2549.org>"}); - emailIntent.putExtra(Intent.EXTRA_SUBJECT, "OpenVPN Minidump"); - - emailIntent.putExtra(Intent.EXTRA_TEXT, "Please describe the issue you have experienced"); - - ArrayList<Uri> uris = new ArrayList<Uri>(); - - File ldump = getLastestDump(this); - if(ldump==null) { - OpenVPN.logError("No Minidump found!"); - } - - uris.add(Uri.parse("content://se.leap.openvpn.FileProvider/" + ldump.getName())); - uris.add(Uri.parse("content://se.leap.openvpn.FileProvider/" + ldump.getName() + ".log")); - - emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); - emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); - startActivity(emailIntent); - } - - static public File getLastestDump(Context c) { - long newestDumpTime=0; - File newestDumpFile=null; - - for(File f:c.getCacheDir().listFiles()) { - if(!f.getName().endsWith(".dmp")) - continue; - - if (newestDumpTime < f.lastModified()) { - newestDumpTime = f.lastModified(); - newestDumpFile=f; - } - } - return newestDumpFile; - } -} diff --git a/src/se/leap/openvpn/Settings_Authentication.java b/src/se/leap/openvpn/Settings_Authentication.java deleted file mode 100644 index 7824d790..00000000 --- a/src/se/leap/openvpn/Settings_Authentication.java +++ /dev/null @@ -1,136 +0,0 @@ -package se.leap.openvpn; - -import android.app.Activity; -import android.content.Intent; -import android.os.Bundle; -import android.os.Environment; -import android.preference.CheckBoxPreference; -import android.preference.EditTextPreference; -import android.preference.ListPreference; -import android.preference.Preference; -import android.preference.Preference.OnPreferenceChangeListener; -import android.preference.Preference.OnPreferenceClickListener; -import android.preference.SwitchPreference; -import se.leap.bitmaskclient.R; - - -public class Settings_Authentication extends OpenVpnPreferencesFragment implements OnPreferenceChangeListener, OnPreferenceClickListener { - private static final int SELECT_TLS_FILE = 23223232; - private CheckBoxPreference mExpectTLSCert; - private CheckBoxPreference mCheckRemoteCN; - private EditTextPreference mRemoteCN; - private ListPreference mTLSAuthDirection; - private Preference mTLSAuthFile; - private SwitchPreference mUseTLSAuth; - private EditTextPreference mCipher; - private String mTlsAuthFileData; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - // Load the preferences from an XML resource - addPreferencesFromResource(R.xml.vpn_authentification); - - mExpectTLSCert = (CheckBoxPreference) findPreference("remoteServerTLS"); - mCheckRemoteCN = (CheckBoxPreference) findPreference("checkRemoteCN"); - mRemoteCN = (EditTextPreference) findPreference("remotecn"); - mRemoteCN.setOnPreferenceChangeListener(this); - - mUseTLSAuth = (SwitchPreference) findPreference("useTLSAuth" ); - mTLSAuthFile = findPreference("tlsAuthFile"); - mTLSAuthDirection = (ListPreference) findPreference("tls_direction"); - - - mTLSAuthFile.setOnPreferenceClickListener(this); - - mCipher =(EditTextPreference) findPreference("cipher"); - mCipher.setOnPreferenceChangeListener(this); - - loadSettings(); - - } - - @Override - protected void loadSettings() { - - mExpectTLSCert.setChecked(mProfile.mExpectTLSCert); - mCheckRemoteCN.setChecked(mProfile.mCheckRemoteCN); - mRemoteCN.setText(mProfile.mRemoteCN); - onPreferenceChange(mRemoteCN, mProfile.mRemoteCN); - - mUseTLSAuth.setChecked(mProfile.mUseTLSAuth); - mTlsAuthFileData= mProfile.mTLSAuthFilename; - setTlsAuthSummary(mTlsAuthFileData); - mTLSAuthDirection.setValue(mProfile.mTLSAuthDirection); - mCipher.setText(mProfile.mCipher); - onPreferenceChange(mCipher, mProfile.mCipher); - } - - @Override - protected void saveSettings() { - mProfile.mExpectTLSCert=mExpectTLSCert.isChecked(); - mProfile.mCheckRemoteCN=mCheckRemoteCN.isChecked(); - mProfile.mRemoteCN=mRemoteCN.getText(); - - mProfile.mUseTLSAuth = mUseTLSAuth.isChecked(); - mProfile.mTLSAuthFilename = mTlsAuthFileData; - - if(mTLSAuthDirection.getValue()==null) - mProfile.mTLSAuthDirection=null; - else - mProfile.mTLSAuthDirection = mTLSAuthDirection.getValue().toString(); - - if(mCipher.getText()==null) - mProfile.mCipher=null; - else - mProfile.mCipher = mCipher.getText(); - - } - - - - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - if(preference==mRemoteCN) { - if ("".equals(newValue)) - preference.setSummary(mProfile.mServerName); - else - preference.setSummary((String)newValue); - } else if (preference == mCipher) { - preference.setSummary((CharSequence) newValue); - } - return true; - } - void startFileDialog() { - Intent startFC = new Intent(getActivity(),FileSelect.class); - startFC.putExtra(FileSelect.START_DATA, Environment.getExternalStorageDirectory().getPath()); - - startActivityForResult(startFC,SELECT_TLS_FILE); - } - @Override - public boolean onPreferenceClick(Preference preference) { - startFileDialog(); - return true; - - } - - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); - if(requestCode==SELECT_TLS_FILE && resultCode == Activity.RESULT_OK){ - String result = data.getStringExtra(FileSelect.RESULT_DATA); - mTlsAuthFileData=result; - setTlsAuthSummary(result); - - } - } - - private void setTlsAuthSummary(String result) { - if(result==null) result = getString(R.string.no_certificate); - if(result.startsWith(VpnProfile.INLINE_TAG)) - mTLSAuthFile.setSummary(R.string.inline_file_data); - else - mTLSAuthFile.setSummary(result); - } -}
\ No newline at end of file diff --git a/src/se/leap/openvpn/Settings_Basic.java b/src/se/leap/openvpn/Settings_Basic.java deleted file mode 100644 index 014c71a1..00000000 --- a/src/se/leap/openvpn/Settings_Basic.java +++ /dev/null @@ -1,347 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package se.leap.openvpn; - -import android.app.Activity; -import android.app.AlertDialog; -import android.app.AlertDialog.Builder; -import android.app.Fragment; -import android.content.ActivityNotFoundException; -import android.content.Intent; -import android.os.Bundle; -import android.os.Handler; -import android.os.Handler.Callback; -import android.os.Message; -import android.security.KeyChain; -import android.security.KeyChainAliasCallback; -import android.util.SparseArray; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.AdapterView.OnItemSelectedListener; -import android.widget.CheckBox; -import android.widget.EditText; -import android.widget.Spinner; -import android.widget.TextView; -import android.widget.ToggleButton; -import se.leap.bitmaskclient.R; -import se.leap.bitmaskclient.R.id; - -public class Settings_Basic extends Fragment implements View.OnClickListener, OnItemSelectedListener, Callback { - private static final int CHOOSE_FILE_OFFSET = 1000; - private static final int UPDATE_ALIAS = 20; - - - - private TextView mServerAddress; - private TextView mServerPort; - private FileSelectLayout mClientCert; - private FileSelectLayout mCaCert; - private FileSelectLayout mClientKey; - private TextView mAliasName; - private CheckBox mUseLzo; - private ToggleButton mTcpUdp; - private Spinner mType; - private FileSelectLayout mpkcs12; - private TextView mPKCS12Password; - - private Handler mHandler; - - - - - - private SparseArray<FileSelectLayout> fileselects = new SparseArray<FileSelectLayout>(); - - - private EditText mUserName; - - - private EditText mPassword; - - - private View mView; - - - private VpnProfile mProfile; - private EditText mProfileName; - private EditText mKeyPassword; - - - - private void addFileSelectLayout (FileSelectLayout fsl) { - int i = fileselects.size() + CHOOSE_FILE_OFFSET; - fileselects.put(i, fsl); - fsl.setFragment(this,i); - } - - - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - String profileuuid =getArguments().getString(getActivity().getPackageName() + ".profileUUID"); - mProfile=ProfileManager.get(profileuuid); - getActivity().setTitle(getString(R.string.edit_profile_title, mProfile.getName())); - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - - - mView = inflater.inflate(R.layout.basic_settings,container,false); - - mProfileName = (EditText) mView.findViewById(R.id.profilename); - mServerAddress = (TextView) mView.findViewById(R.id.address); - mServerPort = (TextView) mView.findViewById(R.id.port); - mClientCert = (FileSelectLayout) mView.findViewById(R.id.certselect); - mClientKey = (FileSelectLayout) mView.findViewById(R.id.keyselect); - mCaCert = (FileSelectLayout) mView.findViewById(R.id.caselect); - mpkcs12 = (FileSelectLayout) mView.findViewById(R.id.pkcs12select); - mUseLzo = (CheckBox) mView.findViewById(R.id.lzo); - mTcpUdp = (ToggleButton) mView.findViewById(id.tcpudp); - mType = (Spinner) mView.findViewById(R.id.type); - mPKCS12Password = (TextView) mView.findViewById(R.id.pkcs12password); - mAliasName = (TextView) mView.findViewById(R.id.aliasname); - - mUserName = (EditText) mView.findViewById(R.id.auth_username); - mPassword = (EditText) mView.findViewById(R.id.auth_password); - mKeyPassword = (EditText) mView.findViewById(R.id.key_password); - - - - addFileSelectLayout(mCaCert); - addFileSelectLayout(mClientCert); - addFileSelectLayout(mClientKey); - addFileSelectLayout(mpkcs12); - mpkcs12.setBase64Encode(); - mCaCert.setShowClear(); - - - mType.setOnItemSelectedListener(this); - - mView.findViewById(R.id.select_keystore_button).setOnClickListener(this); - - - if (mHandler == null) { - mHandler = new Handler(this); - } - - return mView; - } - - - @Override - public void onStart() { - super.onStart(); - String profileuuid =getArguments().getString(getActivity().getPackageName() + ".profileUUID"); - mProfile=ProfileManager.get(profileuuid); - loadPreferences(); - - } - - @Override - public void onActivityResult(int request, int result, Intent data) { - if (result == Activity.RESULT_OK && request >= CHOOSE_FILE_OFFSET) { - String filedata = data.getStringExtra(FileSelect.RESULT_DATA); - FileSelectLayout fsl = fileselects.get(request); - fsl.setData(filedata); - - savePreferences(); - - // Private key files may result in showing/hiding the private key password dialog - if(fsl==mClientKey) { - changeType(mType.getSelectedItemPosition()); - } - } - - } - - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - } - - @Override - public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { - if (parent == mType) { - changeType(position); - } - } - @Override - public void onPause() { - super.onPause(); - savePreferences(); - } - - - - private void changeType(int type){ - // hide everything - mView.findViewById(R.id.pkcs12).setVisibility(View.GONE); - mView.findViewById(R.id.certs).setVisibility(View.GONE); - mView.findViewById(R.id.statickeys).setVisibility(View.GONE); - mView.findViewById(R.id.keystore).setVisibility(View.GONE); - mView.findViewById(R.id.cacert).setVisibility(View.GONE); - mView.findViewById(R.id.userpassword).setVisibility(View.GONE); - mView.findViewById(R.id.key_password_layout).setVisibility(View.GONE); - - // Fall through are by design - switch(type) { - case VpnProfile.TYPE_USERPASS_CERTIFICATES: - mView.findViewById(R.id.userpassword).setVisibility(View.VISIBLE); - case VpnProfile.TYPE_CERTIFICATES: - mView.findViewById(R.id.certs).setVisibility(View.VISIBLE); - mView.findViewById(R.id.cacert).setVisibility(View.VISIBLE); - if(mProfile.requireTLSKeyPassword()) - mView.findViewById(R.id.key_password_layout).setVisibility(View.VISIBLE); - break; - - case VpnProfile.TYPE_USERPASS_PKCS12: - mView.findViewById(R.id.userpassword).setVisibility(View.VISIBLE); - case VpnProfile.TYPE_PKCS12: - mView.findViewById(R.id.pkcs12).setVisibility(View.VISIBLE); - break; - - case VpnProfile.TYPE_STATICKEYS: - mView.findViewById(R.id.statickeys).setVisibility(View.VISIBLE); - break; - - case VpnProfile.TYPE_USERPASS_KEYSTORE: - mView.findViewById(R.id.userpassword).setVisibility(View.VISIBLE); - case VpnProfile.TYPE_KEYSTORE: - mView.findViewById(R.id.keystore).setVisibility(View.VISIBLE); - mView.findViewById(R.id.cacert).setVisibility(View.VISIBLE); - break; - - case VpnProfile.TYPE_USERPASS: - mView.findViewById(R.id.userpassword).setVisibility(View.VISIBLE); - mView.findViewById(R.id.cacert).setVisibility(View.VISIBLE); - break; - } - - - } - - private void loadPreferences() { - mProfileName.setText(mProfile.mName); - mClientCert.setData(mProfile.mClientCertFilename); - mClientKey.setData(mProfile.mClientKeyFilename); - mCaCert.setData(mProfile.mCaFilename); - - mUseLzo.setChecked(mProfile.mUseLzo); - mServerPort.setText(mProfile.mServerPort); - mServerAddress.setText(mProfile.mServerName); - mTcpUdp.setChecked(mProfile.mUseUdp); - mType.setSelection(mProfile.mAuthenticationType); - mpkcs12.setData(mProfile.mPKCS12Filename); - mPKCS12Password.setText(mProfile.mPKCS12Password); - mUserName.setText(mProfile.mUsername); - mPassword.setText(mProfile.mPassword); - mKeyPassword.setText(mProfile.mKeyPassword); - - setAlias(); - - } - - void savePreferences() { - - mProfile.mName = mProfileName.getText().toString(); - mProfile.mCaFilename = mCaCert.getData(); - mProfile.mClientCertFilename = mClientCert.getData(); - mProfile.mClientKeyFilename = mClientKey.getData(); - - mProfile.mUseLzo = mUseLzo.isChecked(); - mProfile.mServerPort =mServerPort.getText().toString(); - mProfile.mServerName = mServerAddress.getText().toString(); - mProfile.mUseUdp = mTcpUdp.isChecked(); - - mProfile.mAuthenticationType = mType.getSelectedItemPosition(); - mProfile.mPKCS12Filename = mpkcs12.getData(); - mProfile.mPKCS12Password = mPKCS12Password.getText().toString(); - - mProfile.mPassword = mPassword.getText().toString(); - mProfile.mUsername = mUserName.getText().toString(); - mProfile.mKeyPassword = mKeyPassword.getText().toString(); - - } - - - private void setAlias() { - if(mProfile.mAlias == null) { - mAliasName.setText(R.string.client_no_certificate); - } else { - mAliasName.setText(mProfile.mAlias); - } - } - - public void showCertDialog () { - try { - KeyChain.choosePrivateKeyAlias(getActivity(), - new KeyChainAliasCallback() { - - public void alias(String alias) { - // Credential alias selected. Remember the alias selection for future use. - mProfile.mAlias=alias; - mHandler.sendEmptyMessage(UPDATE_ALIAS); - } - - - }, - new String[] {"RSA"}, // List of acceptable key types. null for any - null, // issuer, null for any - mProfile.mServerName, // host name of server requesting the cert, null if unavailable - -1, // port of server requesting the cert, -1 if unavailable - mProfile.mAlias); // alias to preselect, null if unavailable - } catch (ActivityNotFoundException anf) { - Builder ab = new AlertDialog.Builder(getActivity()); - ab.setTitle(R.string.broken_image_cert_title); - ab.setMessage(R.string.broken_image_cert); - ab.setPositiveButton(android.R.string.ok, null); - ab.show(); - } - } - - @Override - public void onClick(View v) { - if (v == mView.findViewById(R.id.select_keystore_button)) { - showCertDialog(); - } - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - savePreferences(); - if(mProfile!=null) { - outState.putString(getActivity().getPackageName() + "profileUUID", mProfile.getUUID().toString()); - } - } - - @Override - public void onNothingSelected(AdapterView<?> parent) { - } - - - @Override - public boolean handleMessage(Message msg) { - setAlias(); - return true; - } - - -} diff --git a/src/se/leap/openvpn/Settings_IP.java b/src/se/leap/openvpn/Settings_IP.java deleted file mode 100644 index bb605937..00000000 --- a/src/se/leap/openvpn/Settings_IP.java +++ /dev/null @@ -1,129 +0,0 @@ -package se.leap.openvpn; -import android.os.Bundle; -import android.preference.CheckBoxPreference; -import android.preference.EditTextPreference; -import android.preference.Preference; -import android.preference.Preference.OnPreferenceChangeListener; -import android.preference.PreferenceManager; -import android.preference.SwitchPreference; -import se.leap.bitmaskclient.R; - -public class Settings_IP extends OpenVpnPreferencesFragment implements OnPreferenceChangeListener { - private EditTextPreference mIPv4; - private EditTextPreference mIPv6; - private SwitchPreference mUsePull; - private CheckBoxPreference mOverrideDNS; - private EditTextPreference mSearchdomain; - private EditTextPreference mDNS1; - private EditTextPreference mDNS2; - private CheckBoxPreference mNobind; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - - // Make sure default values are applied. In a real app, you would - // want this in a shared function that is used to retrieve the - // SharedPreferences wherever they are needed. - PreferenceManager.setDefaultValues(getActivity(), - R.xml.vpn_ipsettings, false); - - // Load the preferences from an XML resource - addPreferencesFromResource(R.xml.vpn_ipsettings); - mIPv4 = (EditTextPreference) findPreference("ipv4_address"); - mIPv6 = (EditTextPreference) findPreference("ipv6_address"); - mUsePull = (SwitchPreference) findPreference("usePull"); - mOverrideDNS = (CheckBoxPreference) findPreference("overrideDNS"); - mSearchdomain =(EditTextPreference) findPreference("searchdomain"); - mDNS1 = (EditTextPreference) findPreference("dns1"); - mDNS2 = (EditTextPreference) findPreference("dns2"); - mNobind = (CheckBoxPreference) findPreference("nobind"); - - mIPv4.setOnPreferenceChangeListener(this); - mIPv6.setOnPreferenceChangeListener(this); - mDNS1.setOnPreferenceChangeListener(this); - mDNS2.setOnPreferenceChangeListener(this); - mUsePull.setOnPreferenceChangeListener(this); - mOverrideDNS.setOnPreferenceChangeListener(this); - mSearchdomain.setOnPreferenceChangeListener(this); - - loadSettings(); - } - - @Override - protected void loadSettings() { - - mUsePull.setChecked(mProfile.mUsePull); - mIPv4.setText(mProfile.mIPv4Address); - mIPv6.setText(mProfile.mIPv6Address); - mDNS1.setText(mProfile.mDNS1); - mDNS2.setText(mProfile.mDNS2); - mOverrideDNS.setChecked(mProfile.mOverrideDNS); - mSearchdomain.setText(mProfile.mSearchDomain); - mNobind.setChecked(mProfile.mNobind); - - // Sets Summary - onPreferenceChange(mIPv4, mIPv4.getText()); - onPreferenceChange(mIPv6, mIPv6.getText()); - onPreferenceChange(mDNS1, mDNS1.getText()); - onPreferenceChange(mDNS2, mDNS2.getText()); - onPreferenceChange(mSearchdomain, mSearchdomain.getText()); - - setDNSState(); - } - - - @Override - protected void saveSettings() { - mProfile.mUsePull = mUsePull.isChecked(); - mProfile.mIPv4Address = mIPv4.getText(); - mProfile.mIPv6Address = mIPv6.getText(); - mProfile.mDNS1 = mDNS1.getText(); - mProfile.mDNS2 = mDNS2.getText(); - mProfile.mOverrideDNS = mOverrideDNS.isChecked(); - mProfile.mSearchDomain = mSearchdomain.getText(); - mProfile.mNobind = mNobind.isChecked(); - - } - - @Override - public boolean onPreferenceChange(Preference preference, - Object newValue) { - if(preference==mIPv4 || preference == mIPv6 - || preference==mDNS1 || preference == mDNS2 - || preference == mSearchdomain - ) - - preference.setSummary((String)newValue); - - if(preference== mUsePull || preference == mOverrideDNS) - if(preference==mOverrideDNS) { - // Set so the function gets the right value - mOverrideDNS.setChecked((Boolean) newValue); - } - setDNSState(); - - saveSettings(); - return true; - } - - private void setDNSState() { - boolean enabled; - mOverrideDNS.setEnabled(mUsePull.isChecked()); - if(!mUsePull.isChecked()) - enabled =true; - else if (mOverrideDNS.isChecked()) - enabled = true; - else - enabled = false; - - mDNS1.setEnabled(enabled); - mDNS2.setEnabled(enabled); - mSearchdomain.setEnabled(enabled); - - - } - - - }
\ No newline at end of file diff --git a/src/se/leap/openvpn/Settings_Obscure.java b/src/se/leap/openvpn/Settings_Obscure.java deleted file mode 100644 index 6ba98606..00000000 --- a/src/se/leap/openvpn/Settings_Obscure.java +++ /dev/null @@ -1,116 +0,0 @@ -package se.leap.openvpn; - -import android.os.Bundle; -import android.preference.CheckBoxPreference; -import android.preference.EditTextPreference; -import android.preference.ListPreference; -import android.preference.Preference; -import android.preference.Preference.OnPreferenceChangeListener; -import se.leap.bitmaskclient.R; - -public class Settings_Obscure extends OpenVpnPreferencesFragment implements OnPreferenceChangeListener { - private CheckBoxPreference mUseRandomHostName; - private CheckBoxPreference mUseFloat; - private CheckBoxPreference mUseCustomConfig; - private EditTextPreference mCustomConfig; - private ListPreference mLogverbosity; - private CheckBoxPreference mPersistent; - private ListPreference mConnectretrymax; - private EditTextPreference mConnectretry; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - // Load the preferences from an XML resource - addPreferencesFromResource(R.xml.vpn_obscure); - - - mUseRandomHostName = (CheckBoxPreference) findPreference("useRandomHostname"); - mUseFloat = (CheckBoxPreference) findPreference("useFloat"); - mUseCustomConfig = (CheckBoxPreference) findPreference("enableCustomOptions"); - mCustomConfig = (EditTextPreference) findPreference("customOptions"); - mLogverbosity = (ListPreference) findPreference("verblevel"); - mPersistent = (CheckBoxPreference) findPreference("usePersistTun"); - mConnectretrymax = (ListPreference) findPreference("connectretrymax"); - mConnectretry = (EditTextPreference) findPreference("connectretry"); - - mLogverbosity.setOnPreferenceChangeListener(this); - mLogverbosity.setSummary("%s"); - - mConnectretrymax.setOnPreferenceChangeListener(this); - mConnectretrymax.setSummary("%s"); - - mConnectretry.setOnPreferenceChangeListener(this); - - - loadSettings(); - - } - - protected void loadSettings() { - mUseRandomHostName.setChecked(mProfile.mUseRandomHostname); - mUseFloat.setChecked(mProfile.mUseFloat); - mUseCustomConfig.setChecked(mProfile.mUseCustomConfig); - mCustomConfig.setText(mProfile.mCustomConfigOptions); - mPersistent.setChecked(mProfile.mPersistTun); - - mLogverbosity.setValue(mProfile.mVerb); - onPreferenceChange(mLogverbosity, mProfile.mVerb); - - mConnectretrymax.setValue(mProfile.mConnectRetryMax); - onPreferenceChange(mConnectretrymax, mProfile.mConnectRetryMax); - - mConnectretry.setText(mProfile.mConnectRetry); - onPreferenceChange(mConnectretry, mProfile.mConnectRetry); - } - - - protected void saveSettings() { - mProfile.mUseRandomHostname = mUseRandomHostName.isChecked(); - mProfile.mUseFloat = mUseFloat.isChecked(); - mProfile.mUseCustomConfig = mUseCustomConfig.isChecked(); - mProfile.mCustomConfigOptions = mCustomConfig.getText(); - mProfile.mVerb = mLogverbosity.getValue(); - mProfile.mConnectRetryMax = mConnectretrymax.getValue(); - mProfile.mPersistTun = mPersistent.isChecked(); - mProfile.mConnectRetry = mConnectretry.getText(); - } - - - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - if(preference==mLogverbosity) { - // Catch old version problem - if(newValue==null){ - newValue="1"; - } - mLogverbosity.setDefaultValue(newValue); - //This is idiotic. - int i =Integer.parseInt((String) newValue); - - // verb >= 5 is not supported by the chooser - if(i < mLogverbosity.getEntries().length ) - mLogverbosity.setSummary(mLogverbosity.getEntries()[i]); - else - mLogverbosity.setSummary(String.format("debug verbosity: %d",i)); - } else if (preference == mConnectretrymax) { - if(newValue==null) { - newValue="5"; - } - mConnectretrymax.setDefaultValue(newValue); - - for(int i=0;i<mConnectretrymax.getEntryValues().length;i++){ - if(mConnectretrymax.getEntryValues().equals(newValue)) - mConnectretrymax.setSummary(mConnectretrymax.getEntries()[i]); - } - - } else if (preference == mConnectretry) { - if(newValue==null || newValue=="") - newValue="5"; - mConnectretry.setSummary(String.format("%s s" , newValue)); - } - - return true; - } - -}
\ No newline at end of file diff --git a/src/se/leap/openvpn/Settings_Routing.java b/src/se/leap/openvpn/Settings_Routing.java deleted file mode 100644 index 3cbdac0f..00000000 --- a/src/se/leap/openvpn/Settings_Routing.java +++ /dev/null @@ -1,73 +0,0 @@ -package se.leap.openvpn; -import android.os.Bundle; -import android.preference.CheckBoxPreference; -import android.preference.EditTextPreference; -import android.preference.Preference; -import android.preference.Preference.OnPreferenceChangeListener; -import se.leap.bitmaskclient.R; - - -public class Settings_Routing extends OpenVpnPreferencesFragment implements OnPreferenceChangeListener { - private EditTextPreference mCustomRoutes; - private CheckBoxPreference mUseDefaultRoute; - private EditTextPreference mCustomRoutesv6; - private CheckBoxPreference mUseDefaultRoutev6; - private CheckBoxPreference mRouteNoPull; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - // Load the preferences from an XML resource - addPreferencesFromResource(R.xml.vpn_routing); - mCustomRoutes = (EditTextPreference) findPreference("customRoutes"); - mUseDefaultRoute = (CheckBoxPreference) findPreference("useDefaultRoute"); - mCustomRoutesv6 = (EditTextPreference) findPreference("customRoutesv6"); - mUseDefaultRoutev6 = (CheckBoxPreference) findPreference("useDefaultRoutev6"); - mRouteNoPull = (CheckBoxPreference) findPreference("routenopull"); - - mCustomRoutes.setOnPreferenceChangeListener(this); - mCustomRoutesv6.setOnPreferenceChangeListener(this); - - loadSettings(); - } - - @Override - protected void loadSettings() { - - mUseDefaultRoute.setChecked(mProfile.mUseDefaultRoute); - mUseDefaultRoutev6.setChecked(mProfile.mUseDefaultRoutev6); - - mCustomRoutes.setText(mProfile.mCustomRoutes); - mCustomRoutesv6.setText(mProfile.mCustomRoutesv6); - - mRouteNoPull.setChecked(mProfile.mRoutenopull); - - // Sets Summary - onPreferenceChange(mCustomRoutes, mCustomRoutes.getText()); - onPreferenceChange(mCustomRoutesv6, mCustomRoutesv6.getText()); - mRouteNoPull.setEnabled(mProfile.mUsePull); - } - - - @Override - protected void saveSettings() { - mProfile.mUseDefaultRoute = mUseDefaultRoute.isChecked(); - mProfile.mUseDefaultRoutev6 = mUseDefaultRoutev6.isChecked(); - mProfile.mCustomRoutes = mCustomRoutes.getText(); - mProfile.mCustomRoutesv6 = mCustomRoutesv6.getText(); - mProfile.mRoutenopull = mRouteNoPull.isChecked(); - } - - @Override - public boolean onPreferenceChange(Preference preference, - Object newValue) { - if( preference == mCustomRoutes || preference == mCustomRoutesv6 ) - preference.setSummary((String)newValue); - - saveSettings(); - return true; - } - - -}
\ No newline at end of file diff --git a/src/se/leap/openvpn/ShowConfigFragment.java b/src/se/leap/openvpn/ShowConfigFragment.java deleted file mode 100644 index 194f87d4..00000000 --- a/src/se/leap/openvpn/ShowConfigFragment.java +++ /dev/null @@ -1,67 +0,0 @@ -package se.leap.openvpn; - -import android.app.Fragment; -import android.content.Intent; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; -import se.leap.bitmaskclient.R; - - -public class ShowConfigFragment extends Fragment { - private String configtext; - public android.view.View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { - String profileUUID = getArguments().getString(getActivity().getPackageName() + ".profileUUID"); - VpnProfile vp = ProfileManager.get(profileUUID); - View v=inflater.inflate(R.layout.viewconfig, container,false); - TextView cv = (TextView) v.findViewById(R.id.configview); - - int check=vp.checkProfile(getActivity()); - if(check!=R.string.no_error_found) { - cv.setText(check); - configtext = getString(check); - } - else { - String cfg=vp.getConfigFile(getActivity()); - configtext= cfg; - cv.setText(cfg); - } - return v; - }; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setHasOptionsMenu(true); - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - inflater.inflate(R.menu.configmenu, menu); - } - - private void shareConfig() { - Intent shareIntent = new Intent(Intent.ACTION_SEND); - shareIntent.putExtra(Intent.EXTRA_TEXT, configtext); - shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.export_config_title)); - shareIntent.setType("text/plain"); - startActivity(Intent.createChooser(shareIntent, "Export Configfile")); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - final int itemId = item.getItemId(); - if (itemId == R.id.sendConfig) { - shareConfig(); - return true; - } else { - return super.onOptionsItemSelected(item); - } - } -} diff --git a/src/se/leap/openvpn/VPNPreferences.java b/src/se/leap/openvpn/VPNPreferences.java deleted file mode 100644 index e3052050..00000000 --- a/src/se/leap/openvpn/VPNPreferences.java +++ /dev/null @@ -1,139 +0,0 @@ -package se.leap.openvpn; - -import java.util.List; - -import se.leap.bitmaskclient.R; - -import android.app.AlertDialog; -import android.content.DialogInterface; -import android.content.Intent; -import android.os.Bundle; -import android.preference.PreferenceActivity; -import android.view.Menu; -import android.view.MenuItem; - - -public class VPNPreferences extends PreferenceActivity { - - private String mProfileUUID; - private VpnProfile mProfile; - - public VPNPreferences() { - super(); - - } - - - - - @Override - protected void onStop() { - super.onStop(); - }; - - @Override - protected void onSaveInstanceState(Bundle outState) { - outState.putString(getIntent().getStringExtra(getPackageName() + ".profileUUID"),mProfileUUID); - super.onSaveInstanceState(outState); - } - - @Override - protected void onResume() { - super.onResume(); - Intent intent = getIntent(); - - - if(intent!=null) { - String profileUUID = intent.getStringExtra(getPackageName() + ".profileUUID"); - if(profileUUID==null) { - Bundle initialArguments = getIntent().getBundleExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS); - profileUUID = initialArguments.getString(getPackageName() + ".profileUUID"); - } - if(profileUUID!=null){ - - mProfileUUID = profileUUID; - mProfile = ProfileManager.get(this,mProfileUUID); - - } - } - // When a profile is deleted from a category fragment in hadset mod we need to finish - // this activity as well when returning - if (mProfile==null || mProfile.profileDleted) { - setResult(VPNProfileList.RESULT_VPN_DELETED); - finish(); - } - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - mProfileUUID = getIntent().getStringExtra(getPackageName() + ".profileUUID"); - if(savedInstanceState!=null){ - String savedUUID = savedInstanceState.getString(getPackageName() + ".profileUUID"); - if(savedUUID!=null) - mProfileUUID=savedUUID; - } - - mProfile = ProfileManager.get(this,mProfileUUID); - if(mProfile!=null) { - setTitle(getString(R.string.edit_profile_title, mProfile.getName())); - } - super.onCreate(savedInstanceState); - } - - - @Override - public void onBuildHeaders(List<Header> target) { - loadHeadersFromResource(R.xml.vpn_headers, target); - for (Header header : target) { - if(header.fragmentArguments==null) - header.fragmentArguments = new Bundle(); - header.fragmentArguments.putString(getPackageName() + ".profileUUID",mProfileUUID); - } - } - - @Override - public void onBackPressed() { - setResult(RESULT_OK, getIntent()); - super.onBackPressed(); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if(item.getItemId() == R.id.remove_vpn) - askProfileRemoval(); - return super.onOptionsItemSelected(item); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - - getMenuInflater().inflate(R.menu.vpnpreferences_menu, menu); - - return super.onCreateOptionsMenu(menu); - } - - private void askProfileRemoval() { - AlertDialog.Builder dialog = new AlertDialog.Builder(this); - dialog.setTitle("Confirm deletion"); - dialog.setMessage(getString(R.string.remove_vpn_query, mProfile.mName)); - - dialog.setPositiveButton(android.R.string.yes, - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - removeProfile(mProfile); - } - - }); - dialog.setNegativeButton(android.R.string.no,null); - dialog.create().show(); - } - - protected void removeProfile(VpnProfile profile) { - ProfileManager.getInstance(this).removeProfile(this,profile); - setResult(VPNProfileList.RESULT_VPN_DELETED); - finish(); - - } -} - diff --git a/src/se/leap/openvpn/VPNProfileList.java b/src/se/leap/openvpn/VPNProfileList.java deleted file mode 100644 index 0ef611df..00000000 --- a/src/se/leap/openvpn/VPNProfileList.java +++ /dev/null @@ -1,318 +0,0 @@ -package se.leap.openvpn; - -import java.util.Collection; -import java.util.Comparator; -import java.util.TreeSet; - -import se.leap.bitmaskclient.R; - -import android.app.Activity; -import android.app.AlertDialog; -import android.app.ListFragment; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.graphics.drawable.Drawable; -import android.net.Uri; -import android.os.Bundle; -import android.text.Html; -import android.text.Html.ImageGetter; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.ViewGroup; -import android.widget.ArrayAdapter; -import android.widget.EditText; -import android.widget.TextView; -import android.widget.Toast; - -public class VPNProfileList extends ListFragment { - - final static int RESULT_VPN_DELETED = Activity.RESULT_FIRST_USER; - - private static final int MENU_ADD_PROFILE = Menu.FIRST; - - private static final int START_VPN_CONFIG = 92; - private static final int SELECT_PROFILE = 43; - private static final int IMPORT_PROFILE = 231; - - private static final int MENU_IMPORT_PROFILE = Menu.FIRST +1; - - class VPNArrayAdapter extends ArrayAdapter<VpnProfile> { - - public VPNArrayAdapter(Context context, int resource, - int textViewResourceId) { - super(context, resource, textViewResourceId); - } - - @Override - public View getView(final int position, View convertView, ViewGroup parent) { - View v = super.getView(position, convertView, parent); - - View titleview = v.findViewById(R.id.vpn_list_item_left); - titleview.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - VpnProfile profile =(VpnProfile) getListAdapter().getItem(position); - startVPN(profile); - } - }); - - View settingsview = v.findViewById(R.id.quickedit_settings); - settingsview.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - mEditProfile =(VpnProfile) getListAdapter().getItem(position); - editVPN(mEditProfile); - - } - }); - - return v; - } - } - - - - - - - - - private ArrayAdapter<VpnProfile> mArrayadapter; - - protected VpnProfile mEditProfile=null; - - - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setHasOptionsMenu(true); - - // Debug load JNI - //OpenVPN.foo(); - } - - - class MiniImageGetter implements ImageGetter { - - - @Override - public Drawable getDrawable(String source) { - Drawable d=null; - if ("ic_menu_add".equals(source)) - d = getActivity().getResources().getDrawable(android.R.drawable.ic_menu_add); - else if("ic_menu_archive".equals(source)) - d = getActivity().getResources().getDrawable(R.drawable.ic_menu_archive); - - - - if(d!=null) { - d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); - return d; - }else{ - return null; - } - } - } - - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View v = inflater.inflate(R.layout.vpn_profile_list, container,false); - - TextView newvpntext = (TextView) v.findViewById(R.id.add_new_vpn_hint); - TextView importvpntext = (TextView) v.findViewById(R.id.import_vpn_hint); - - - - newvpntext.setText(Html.fromHtml(getString(R.string.add_new_vpn_hint),new MiniImageGetter(),null)); - importvpntext.setText(Html.fromHtml(getString(R.string.vpn_import_hint),new MiniImageGetter(),null)); - - - - return v; - - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - setListAdapter(); - } - - class VpnProfileNameComperator implements Comparator<VpnProfile> { - - @Override - public int compare(VpnProfile lhs, VpnProfile rhs) { - return lhs.mName.compareTo(rhs.mName); - } - - } - - private void setListAdapter() { - mArrayadapter = new VPNArrayAdapter(getActivity(),R.layout.vpn_list_item,R.id.vpn_item_title); - Collection<VpnProfile> allvpn = getPM().getProfiles(); - - TreeSet<VpnProfile> sortedset = new TreeSet<VpnProfile>(new VpnProfileNameComperator()); - sortedset.addAll(allvpn); - mArrayadapter.addAll(sortedset); - - setListAdapter(mArrayadapter); - } - - - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - menu.add(0, MENU_ADD_PROFILE, 0, R.string.menu_add_profile) - .setIcon(android.R.drawable.ic_menu_add) - .setAlphabeticShortcut('a') - .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM - | MenuItem.SHOW_AS_ACTION_WITH_TEXT); - - menu.add(0, MENU_IMPORT_PROFILE, 0, R.string.menu_import) - .setIcon(R.drawable.ic_menu_archive) - .setAlphabeticShortcut('i') - .setTitleCondensed(getActivity().getString(R.string.menu_import_short)) - .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM - | MenuItem.SHOW_AS_ACTION_WITH_TEXT ); - } - - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - final int itemId = item.getItemId(); - if (itemId == MENU_ADD_PROFILE) { - onAddProfileClicked(); - return true; - } else if (itemId == MENU_IMPORT_PROFILE) { - startImportConfig(); - return true; - } else { - return super.onOptionsItemSelected(item); - } - } - - private void startImportConfig() { - Intent intent = new Intent(getActivity(),FileSelect.class); - intent.putExtra(FileSelect.NO_INLINE_SELECTION, true); - intent.putExtra(FileSelect.WINDOW_TITLE, R.string.import_configuration_file); - startActivityForResult(intent, SELECT_PROFILE); - } - - - - - - private void onAddProfileClicked() { - Context context = getActivity(); - if (context != null) { - final EditText entry = new EditText(context); - entry.setSingleLine(); - - AlertDialog.Builder dialog = new AlertDialog.Builder(context); - dialog.setTitle(R.string.menu_add_profile); - dialog.setMessage(R.string.add_profile_name_prompt); - dialog.setView(entry); - - - dialog.setPositiveButton(android.R.string.ok, - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - String name = entry.getText().toString(); - if (getPM().getProfileByName(name)==null) { - VpnProfile profile = new VpnProfile(name); - addProfile(profile); - } else { - Toast.makeText(getActivity(), R.string.duplicate_profile_name, Toast.LENGTH_LONG).show(); - } - } - - - }); - dialog.setNegativeButton(android.R.string.cancel, null); - dialog.create().show(); - } - - } - - - private void addProfile(VpnProfile profile) { - getPM().addProfile(profile); - getPM().saveProfileList(getActivity()); - getPM().saveProfile(getActivity(),profile); - mArrayadapter.add(profile); - } - - - - - - private ProfileManager getPM() { - return ProfileManager.getInstance(getActivity()); - } - - - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); - - if(resultCode == RESULT_VPN_DELETED){ - if(mArrayadapter != null && mEditProfile !=null) - mArrayadapter.remove(mEditProfile); - } - - if(resultCode != Activity.RESULT_OK) - return; - - if (requestCode == START_VPN_CONFIG) { - String configuredVPN = data.getStringExtra(VpnProfile.EXTRA_PROFILEUUID); - - VpnProfile profile = ProfileManager.get(configuredVPN); - getPM().saveProfile(getActivity(), profile); - // Name could be modified, reset List adapter - setListAdapter(); - - } else if(requestCode== SELECT_PROFILE) { - String filedata = data.getStringExtra(FileSelect.RESULT_DATA); - Intent startImport = new Intent(getActivity(),ConfigConverter.class); - startImport.setAction(ConfigConverter.IMPORT_PROFILE); - Uri uri = new Uri.Builder().path(filedata).scheme("file").build(); - startImport.setData(uri); - startActivityForResult(startImport, IMPORT_PROFILE); - } else if(requestCode == IMPORT_PROFILE) { - String profileUUID = data.getStringExtra(VpnProfile.EXTRA_PROFILEUUID); - mArrayadapter.add(ProfileManager.get(profileUUID)); - } - - } - - - private void editVPN(VpnProfile profile) { - - Intent vprefintent = new Intent(getActivity(),VPNPreferences.class) - .putExtra(getActivity().getPackageName() + ".profileUUID", profile.getUUID().toString()); - - startActivityForResult(vprefintent,START_VPN_CONFIG); - } - - private void startVPN(VpnProfile profile) { - - getPM().saveProfile(getActivity(), profile); - - Intent intent = new Intent(getActivity(),LaunchVPN.class); - intent.putExtra(LaunchVPN.EXTRA_KEY, profile.getUUID().toString()); - intent.setAction(Intent.ACTION_MAIN); - startActivity(intent); - - getActivity().finish(); - } -} diff --git a/src/se/leap/openvpn/VpnProfile.java b/src/se/leap/openvpn/VpnProfile.java index 99e1c676..481819ad 100644 --- a/src/se/leap/openvpn/VpnProfile.java +++ b/src/se/leap/openvpn/VpnProfile.java @@ -22,6 +22,7 @@ import org.spongycastle.util.io.pem.PemObject; import org.spongycastle.util.io.pem.PemWriter; import se.leap.bitmaskclient.ConfigHelper; +import se.leap.bitmaskclient.Dashboard; import se.leap.bitmaskclient.EIP; import se.leap.bitmaskclient.Provider; import se.leap.bitmaskclient.R; @@ -249,9 +250,10 @@ public class VpnProfile implements Serializable{ cfg+=insertFileData("cert",mClientCertFilename); */ // FIXME This is all we need...The whole switch statement can go... - cfg+="<ca>\n"+ConfigHelper.getStringFromSharedPref(Provider.CA_CERT)+"\n</ca>\n"; - cfg+="<key>\n"+ConfigHelper.getStringFromSharedPref(EIP.PRIVATE_KEY)+"\n</key>\n"; - cfg+="<cert>\n"+ConfigHelper.getStringFromSharedPref(EIP.CERTIFICATE)+"\n</cert>\n"; + SharedPreferences preferences = context.getSharedPreferences(Dashboard.SHARED_PREFERENCES, context.MODE_PRIVATE); + cfg+="<ca>\n"+preferences.getString(Provider.CA_CERT, "")+"\n</ca>\n"; + cfg+="<key>\n"+preferences.getString(EIP.PRIVATE_KEY, "")+"\n</key>\n"; + cfg+="<cert>\n"+preferences.getString(EIP.CERTIFICATE, "")+"\n</cert>\n"; break; case VpnProfile.TYPE_USERPASS_PKCS12: |