commit 21b75b4c566ed90d2e422245cf85ab4f8316b89f Author: SandroB supp.sandrob@gmail.com Date: Tue Jan 20 15:47:24 2015 +0100
vpn changes --- .project | 16 + AndroidManifest.KITKAT_AND_LOWER.xml | 98 +- AndroidManifest.LOLLIPOP.xml | 96 +- AndroidManifest.xml | 106 +- bcdroid.manifest | 6 +- external/Makefile | 4 +- external/appcompat/.classpath | 4 +- jni/Android.mk | 2 +- res/menu/main.xml | 4 +- res/values/strings.xml | 2 +- src/org/torproject/android/Orbot.java | 1478 ++++--- .../android/OrbotDiagnosticsActivity.java | 1 + .../android/service/TorResourceInstaller.java | 482 +-- src/org/torproject/android/service/TorService.java | 4263 ++++++++++---------- .../torproject/android/settings/AppManager.java | 5 +- .../android/settings/SettingsPreferences.java | 2 +- .../torproject/android/vpn/OrbotVpnService.java | 369 +- src/org/torproject/android/vpn/Tun2Socks.java | 49 +- .../android/wizard/ChooseLocaleWizardActivity.java | 164 +- .../android/wizard/ConfigureTransProxy.java | 6 +- src/org/torproject/android/wizard/LotsaText.java | 2 +- src/org/torproject/android/wizard/Permissions.java | 300 +- .../torproject/android/wizard/TipsAndTricks.java | 336 +- 23 files changed, 3903 insertions(+), 3892 deletions(-)
diff --git a/.project b/.project index 3c3e6b9..2db7e21 100644 --- a/.project +++ b/.project @@ -6,6 +6,12 @@ </projects> <buildSpec> <buildCommand> + <name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name> + <triggers>clean,full,incremental,</triggers> + <arguments> + </arguments> + </buildCommand> + <buildCommand> <name>org.eclipse.wst.jsdt.core.javascriptValidator</name> <arguments> </arguments> @@ -30,10 +36,20 @@ <arguments> </arguments> </buildCommand> + <buildCommand> + <name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name> + <triggers>full,incremental,</triggers> + <arguments> + </arguments> + </buildCommand> </buildSpec> <natures> <nature>com.android.ide.eclipse.adt.AndroidNature</nature> <nature>org.eclipse.jdt.core.javanature</nature> <nature>org.eclipse.wst.jsdt.core.jsNature</nature> + <nature>org.eclipse.cdt.core.cnature</nature> + <nature>org.eclipse.cdt.core.ccnature</nature> + <nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature> + <nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature> </natures> </projectDescription> diff --git a/AndroidManifest.KITKAT_AND_LOWER.xml b/AndroidManifest.KITKAT_AND_LOWER.xml index 2e9aa21..5ba968d 100644 --- a/AndroidManifest.KITKAT_AND_LOWER.xml +++ b/AndroidManifest.KITKAT_AND_LOWER.xml @@ -3,17 +3,17 @@ package="org.torproject.android" android:versionName="14.1.4-noPIE" android:versionCode="132" - android:installLocation="auto" + android:installLocation="auto" > - + <uses-sdk android:minSdkVersion="9" android:maxSdkVersion="20" android:targetSdkVersion="19"/> - <permission android:name="org.torproject.android.MANAGE_TOR" android:label="@string/permission_manage_tor_label" android:description="@string/permission_manage_tor_description" android:protectionLevel="signature"></permission> + <permission android:name="org.torproject.android.MANAGE_TOR" android:label="@string/permission_manage_tor_label" android:description="@string/permission_manage_tor_description" android:protectionLevel="signature"></permission>
<uses-permission android:name="android.permission.INTERNET" /> - <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> + <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> - <uses-permission android:name="android.permission.ACCESS_SUPERUSER"/> - <uses-permission android:name="org.torproject.android.MANAGE_TOR"/> + <uses-permission android:name="android.permission.ACCESS_SUPERUSER"/> + <uses-permission android:name="org.torproject.android.MANAGE_TOR"/>
<application android:name=".OrbotApp" android:icon="@drawable/ic_launcher" android:label="@string/app_name" @@ -52,11 +52,11 @@
<intent-filter> <category android:name="android.intent.category.DEFAULT" /> - <action android:name="org.torproject.android.REQUEST_HS_PORT" /> + <action android:name="org.torproject.android.REQUEST_HS_PORT" /> </intent-filter> <intent-filter> <category android:name="android.intent.category.DEFAULT" /> - <action android:name="org.torproject.android.START_TOR" /> + <action android:name="org.torproject.android.START_TOR" /> </intent-filter>
<!-- @@ -76,56 +76,56 @@ <!-- <activity android:name=".OrbotDiagnosticsActivity" android:label="OrbotDiag"/> --> - <activity - android:name=".service.DummyActivity" - android:theme="@android:style/Theme.NoDisplay" - android:enabled="true" - android:allowTaskReparenting="true" - android:noHistory="true" - android:excludeFromRecents="true" - android:alwaysRetainTaskState="false" - android:stateNotNeeded="true" - android:clearTaskOnLaunch="true" - android:finishOnTaskLaunch="true" - /> - - - <activity android:name=".wizard.LotsaText" android:exported="false"/> - <activity android:name=".wizard.Permissions" android:exported="false"/> - <activity android:name=".wizard.TipsAndTricks" android:exported="false"/> - <activity android:name=".wizard.ConfigureTransProxy" android:exported="false"/> - <activity android:name=".wizard.ChooseLocaleWizardActivity" android:exported="false"/> - - <activity android:name=".settings.SettingsPreferences" android:label="@string/app_name"/> + <activity + android:name=".service.DummyActivity" + android:theme="@android:style/Theme.NoDisplay" + android:enabled="true" + android:allowTaskReparenting="true" + android:noHistory="true" + android:excludeFromRecents="true" + android:alwaysRetainTaskState="false" + android:stateNotNeeded="true" + android:clearTaskOnLaunch="true" + android:finishOnTaskLaunch="true" + /> + + + <activity android:name=".wizard.LotsaText" android:exported="false"/> + <activity android:name=".wizard.Permissions" android:exported="false"/> + <activity android:name=".wizard.TipsAndTricks" android:exported="false"/> + <activity android:name=".wizard.ConfigureTransProxy" android:exported="false"/> + <activity android:name=".wizard.ChooseLocaleWizardActivity" android:exported="false"/> + + <activity android:name=".settings.SettingsPreferences" android:label="@string/app_name"/> <activity android:name=".settings.AppManager" android:label="@string/app_name"/>
- <service android:enabled="true" - android:name=".service.TorService" - android:permission="org.torproject.android.MANAGE_TOR" - android:stopWithTask="false" - > - <intent-filter> - <action android:name="org.torproject.android.service.ITorService" /> - <action android:name="org.torproject.android.service.TOR_SERVICE" /> + <service android:enabled="true" + android:name=".service.TorService" + android:permission="org.torproject.android.MANAGE_TOR" + android:stopWithTask="false" + > + <intent-filter> + <action android:name="org.torproject.android.service.ITorService" /> + <action android:name="org.torproject.android.service.TOR_SERVICE" /> </intent-filter> - </service> - - <receiver android:name=".OnBootReceiver"> - <intent-filter> - <action android:name="android.intent.action.BOOT_COMPLETED" /> - <action android:name="android.intent.action.QUICKBOOT_POWERON" /> - <action android:name="android.intent.action.MEDIA_MOUNTED"/> - </intent-filter> - </receiver> - - + </service> + + <receiver android:name=".OnBootReceiver"> + <intent-filter> + <action android:name="android.intent.action.BOOT_COMPLETED" /> + <action android:name="android.intent.action.QUICKBOOT_POWERON" /> + <action android:name="android.intent.action.MEDIA_MOUNTED"/> + </intent-filter> + </receiver> + + <service android:name="org.torproject.android.vpn.OrbotVpnService" android:permission="android.permission.BIND_VPN_SERVICE"> <intent-filter> <action android:name="android.net.VpnService"/> </intent-filter> </service> - + </application>
diff --git a/AndroidManifest.LOLLIPOP.xml b/AndroidManifest.LOLLIPOP.xml index 302aeeb..70841f4 100644 --- a/AndroidManifest.LOLLIPOP.xml +++ b/AndroidManifest.LOLLIPOP.xml @@ -3,17 +3,17 @@ package="org.torproject.android" android:versionName="14.1.4-PIE" android:versionCode="133" - android:installLocation="auto" + android:installLocation="auto" > - + <uses-sdk android:minSdkVersion="21" android:maxSdkVersion="21" android:targetSdkVersion="21"/> <permission android:name="org.torproject.android.MANAGE_TOR" android:label="@string/permission_manage_tor_label" android:description="@string/permission_manage_tor_description" android:protectionLevel="signature"></permission>
<uses-permission android:name="android.permission.INTERNET" /> - <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> + <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> - <uses-permission android:name="android.permission.ACCESS_SUPERUSER"/> - <uses-permission android:name="org.torproject.android.MANAGE_TOR"/> + <uses-permission android:name="android.permission.ACCESS_SUPERUSER"/> + <uses-permission android:name="org.torproject.android.MANAGE_TOR"/>
<application android:name=".OrbotApp" android:icon="@drawable/ic_launcher" android:label="@string/app_name" @@ -52,11 +52,11 @@
<intent-filter> <category android:name="android.intent.category.DEFAULT" /> - <action android:name="org.torproject.android.REQUEST_HS_PORT" /> + <action android:name="org.torproject.android.REQUEST_HS_PORT" /> </intent-filter> <intent-filter> <category android:name="android.intent.category.DEFAULT" /> - <action android:name="org.torproject.android.START_TOR" /> + <action android:name="org.torproject.android.START_TOR" /> </intent-filter>
<!-- @@ -76,56 +76,56 @@ <!-- <activity android:name=".OrbotDiagnosticsActivity" android:label="OrbotDiag"/> --> - <activity - android:name=".service.DummyActivity" - android:theme="@android:style/Theme.NoDisplay" - android:enabled="true" - android:allowTaskReparenting="true" - android:noHistory="true" - android:excludeFromRecents="true" - android:alwaysRetainTaskState="false" - android:stateNotNeeded="true" - android:clearTaskOnLaunch="true" - android:finishOnTaskLaunch="true" - /> - - - <activity android:name=".wizard.LotsaText" android:exported="false"/> - <activity android:name=".wizard.Permissions" android:exported="false"/> - <activity android:name=".wizard.TipsAndTricks" android:exported="false"/> - <activity android:name=".wizard.ConfigureTransProxy" android:exported="false"/> - <activity android:name=".wizard.ChooseLocaleWizardActivity" android:exported="false"/> - - <activity android:name=".settings.SettingsPreferences" android:label="@string/app_name"/> + <activity + android:name=".service.DummyActivity" + android:theme="@android:style/Theme.NoDisplay" + android:enabled="true" + android:allowTaskReparenting="true" + android:noHistory="true" + android:excludeFromRecents="true" + android:alwaysRetainTaskState="false" + android:stateNotNeeded="true" + android:clearTaskOnLaunch="true" + android:finishOnTaskLaunch="true" + /> + + + <activity android:name=".wizard.LotsaText" android:exported="false"/> + <activity android:name=".wizard.Permissions" android:exported="false"/> + <activity android:name=".wizard.TipsAndTricks" android:exported="false"/> + <activity android:name=".wizard.ConfigureTransProxy" android:exported="false"/> + <activity android:name=".wizard.ChooseLocaleWizardActivity" android:exported="false"/> + + <activity android:name=".settings.SettingsPreferences" android:label="@string/app_name"/> <activity android:name=".settings.AppManager" android:label="@string/app_name"/>
- <service android:enabled="true" - android:name=".service.TorService" - android:permission="org.torproject.android.MANAGE_TOR" - android:stopWithTask="false" - > - <intent-filter> - <action android:name="org.torproject.android.service.ITorService" /> - <action android:name="org.torproject.android.service.TOR_SERVICE" /> + <service android:enabled="true" + android:name=".service.TorService" + android:permission="org.torproject.android.MANAGE_TOR" + android:stopWithTask="false" + > + <intent-filter> + <action android:name="org.torproject.android.service.ITorService" /> + <action android:name="org.torproject.android.service.TOR_SERVICE" /> </intent-filter> - </service> - - <receiver android:name=".OnBootReceiver"> - <intent-filter> - <action android:name="android.intent.action.BOOT_COMPLETED" /> - <action android:name="android.intent.action.QUICKBOOT_POWERON" /> - <action android:name="android.intent.action.MEDIA_MOUNTED"/> - </intent-filter> - </receiver> - - + </service> + + <receiver android:name=".OnBootReceiver"> + <intent-filter> + <action android:name="android.intent.action.BOOT_COMPLETED" /> + <action android:name="android.intent.action.QUICKBOOT_POWERON" /> + <action android:name="android.intent.action.MEDIA_MOUNTED"/> + </intent-filter> + </receiver> + + <service android:name="org.torproject.android.vpn.OrbotVpnService" android:permission="android.permission.BIND_VPN_SERVICE"> <intent-filter> <action android:name="android.net.VpnService"/> </intent-filter> </service> - + </application>
diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 2e9aa21..c8cc1f4 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -1,21 +1,21 @@ <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" - package="org.torproject.android" + package="org.sandroproxy.ony" android:versionName="14.1.4-noPIE" android:versionCode="132" - android:installLocation="auto" + android:installLocation="auto" > - + <uses-sdk android:minSdkVersion="9" android:maxSdkVersion="20" android:targetSdkVersion="19"/> - <permission android:name="org.torproject.android.MANAGE_TOR" android:label="@string/permission_manage_tor_label" android:description="@string/permission_manage_tor_description" android:protectionLevel="signature"></permission> + <permission android:name="org.torproject.android.MANAGE_TOR" android:label="@string/permission_manage_tor_label" android:description="@string/permission_manage_tor_description" android:protectionLevel="signature"></permission>
<uses-permission android:name="android.permission.INTERNET" /> - <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> + <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> - <uses-permission android:name="android.permission.ACCESS_SUPERUSER"/> - <uses-permission android:name="org.torproject.android.MANAGE_TOR"/> + <uses-permission android:name="android.permission.ACCESS_SUPERUSER"/> + <uses-permission android:name="org.torproject.android.MANAGE_TOR"/>
- <application android:name=".OrbotApp" android:icon="@drawable/ic_launcher" + <application android:name="org.sandroproxy.ony.OrbotApp" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:description="@string/app_description" android:configChanges="locale|orientation|screenSize" @@ -27,7 +27,7 @@ android:largeHeap="false" >
- <activity android:name=".Orbot" + <activity android:name="org.torproject.android.Orbot" android:configChanges="orientation|screenSize" android:excludeFromRecents="true" android:launchMode="singleTop" @@ -52,11 +52,11 @@
<intent-filter> <category android:name="android.intent.category.DEFAULT" /> - <action android:name="org.torproject.android.REQUEST_HS_PORT" /> + <action android:name="org.torproject.android.REQUEST_HS_PORT" /> </intent-filter> <intent-filter> <category android:name="android.intent.category.DEFAULT" /> - <action android:name="org.torproject.android.START_TOR" /> + <action android:name="org.torproject.android.START_TOR" /> </intent-filter>
<!-- @@ -76,56 +76,56 @@ <!-- <activity android:name=".OrbotDiagnosticsActivity" android:label="OrbotDiag"/> --> - <activity - android:name=".service.DummyActivity" - android:theme="@android:style/Theme.NoDisplay" - android:enabled="true" - android:allowTaskReparenting="true" - android:noHistory="true" - android:excludeFromRecents="true" - android:alwaysRetainTaskState="false" - android:stateNotNeeded="true" - android:clearTaskOnLaunch="true" - android:finishOnTaskLaunch="true" - /> - - - <activity android:name=".wizard.LotsaText" android:exported="false"/> - <activity android:name=".wizard.Permissions" android:exported="false"/> - <activity android:name=".wizard.TipsAndTricks" android:exported="false"/> - <activity android:name=".wizard.ConfigureTransProxy" android:exported="false"/> - <activity android:name=".wizard.ChooseLocaleWizardActivity" android:exported="false"/> - - <activity android:name=".settings.SettingsPreferences" android:label="@string/app_name"/> - <activity android:name=".settings.AppManager" android:label="@string/app_name"/> + <activity + android:name="org.torproject.android.service.DummyActivity" + android:theme="@android:style/Theme.NoDisplay" + android:enabled="true" + android:allowTaskReparenting="true" + android:noHistory="true" + android:excludeFromRecents="true" + android:alwaysRetainTaskState="false" + android:stateNotNeeded="true" + android:clearTaskOnLaunch="true" + android:finishOnTaskLaunch="true" + /> + + + <activity android:name="org.torproject.android.wizard.LotsaText" android:exported="false"/> + <activity android:name="org.torproject.android.wizard.Permissions" android:exported="false"/> + <activity android:name="org.torproject.android.wizard.TipsAndTricks" android:exported="false"/> + <activity android:name="org.torproject.android.wizard.ConfigureTransProxy" android:exported="false"/> + <activity android:name="org.torproject.android.wizard.ChooseLocaleWizardActivity" android:exported="false"/> + + <activity android:name="org.torproject.android.settings.SettingsPreferences" android:label="@string/app_name"/> + <activity android:name="org.torproject.android.settings.AppManager" android:label="@string/app_name"/>
- <service android:enabled="true" - android:name=".service.TorService" - android:permission="org.torproject.android.MANAGE_TOR" - android:stopWithTask="false" - > - <intent-filter> - <action android:name="org.torproject.android.service.ITorService" /> - <action android:name="org.torproject.android.service.TOR_SERVICE" /> + <service android:enabled="true" + android:name="org.torproject.android.service.TorService" + android:permission="org.torproject.android.MANAGE_TOR" + android:stopWithTask="false" + > + <intent-filter> + <action android:name="org.torproject.android.service.ITorService" /> + <action android:name="org.torproject.android.service.TOR_SERVICE" /> </intent-filter> - </service> - - <receiver android:name=".OnBootReceiver"> - <intent-filter> - <action android:name="android.intent.action.BOOT_COMPLETED" /> - <action android:name="android.intent.action.QUICKBOOT_POWERON" /> - <action android:name="android.intent.action.MEDIA_MOUNTED"/> - </intent-filter> - </receiver> - - + </service> + + <receiver android:name="org.torproject.android.OnBootReceiver"> + <intent-filter> + <action android:name="android.intent.action.BOOT_COMPLETED" /> + <action android:name="android.intent.action.QUICKBOOT_POWERON" /> + <action android:name="android.intent.action.MEDIA_MOUNTED"/> + </intent-filter> + </receiver> + + <service android:name="org.torproject.android.vpn.OrbotVpnService" android:permission="android.permission.BIND_VPN_SERVICE"> <intent-filter> <action android:name="android.net.VpnService"/> </intent-filter> </service> - + </application>
diff --git a/bcdroid.manifest b/bcdroid.manifest index e3467bb..b6b37f4 100644 --- a/bcdroid.manifest +++ b/bcdroid.manifest @@ -1,3 +1,3 @@ -Manifest-Version: 1.0 -Sealed: true - +Manifest-Version: 1.0 +Sealed: true + diff --git a/external/Makefile b/external/Makefile index 999c24d..df7de72 100644 --- a/external/Makefile +++ b/external/Makefile @@ -16,14 +16,14 @@ EXTERNAL_ROOT := $(shell pwd) # user building this will have to manually set NDK_PROCESSOR or NDK_TOOLCHAIN. CPU := $(shell uname -m) ifeq ($(CPU),x86_64) - NDK_PROCESSOR=x86_64 + NDK_PROCESSOR=x86 else NDK_PROCESSOR=x86 endif
# Android NDK setup NDK_BASE ?= /opt/android-ndk -NDK_PLATFORM_LEVEL ?= 9 +NDK_PLATFORM_LEVEL ?= 19 NDK_ABI ?= arm NDK_TOOLCHAIN_VERSION=4.8 NDK_SYSROOT=$(NDK_BASE)/platforms/android-$(NDK_PLATFORM_LEVEL)/arch-$(NDK_ABI) diff --git a/external/appcompat/.classpath b/external/appcompat/.classpath index 2566cbd..fb2265b 100644 --- a/external/appcompat/.classpath +++ b/external/appcompat/.classpath @@ -2,10 +2,10 @@ <classpath> <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/> <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/> - <classpathentry kind="src" path="src"/> - <classpathentry kind="src" path="gen"/> <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/> <classpathentry exported="true" kind="lib" path="libs/android-support-v4.jar"/> <classpathentry exported="true" kind="lib" path="libs/android-support-v7-appcompat.jar"/> + <classpathentry kind="src" path="src"/> + <classpathentry kind="src" path="gen"/> <classpathentry kind="output" path="bin/classes"/> </classpath> diff --git a/jni/Android.mk b/jni/Android.mk index edd247b..4eb1e78 100644 --- a/jni/Android.mk +++ b/jni/Android.mk @@ -1,3 +1,3 @@ ##include ../OriginalDest/Android.mk -##include ../external/badvpn/Android.mk +include ./external/badvpn/Android.mk ##include ../kalium-jni/jni/Android.mk diff --git a/res/menu/main.xml b/res/menu/main.xml index 3c592b2..8ac6bde 100644 --- a/res/menu/main.xml +++ b/res/menu/main.xml @@ -36,7 +36,7 @@ android:id="@+id/menu_verify_list" android:title="@string/menu_verify" android:icon="@drawable/ic_action_browse" - yourapp:showAsAction="always" + yourapp:showAsAction="always" > <menu> <item android:id="@+id/menu_verify" @@ -65,11 +65,9 @@ yourapp:showAsAction="never"
/> - <!-- <item android:id="@+id/menu_vpn" android:title="@string/menu_vpn" yourapp:showAsAction="never"/> - -->
<item android:id="@+id/menu_exit" android:title="@string/menu_exit" diff --git a/res/values/strings.xml b/res/values/strings.xml index f699314..5e05b94 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -1,6 +1,6 @@ <?xml version='1.0' encoding='UTF-8'?> <resources> - <string name="app_name">Orbot</string> + <string name="app_name">Ony</string> <string name="app_description">Orbot is a free proxy app that empowers other apps to use the internet more securely. Orbot uses Tor to encrypt your Internet traffic and then hides it by bouncing through a series of computers around the world. Tor is free software and an open network that helps you defend against a form of network surveillance that threatens personal freedom and privacy, confidential business activities and relationships, and state security known as traffic analysis.</string> <string name="internal_web_url">http://orbot/</string> <string name="default_web_url">http://check.torproject.org</string> diff --git a/src/org/torproject/android/Orbot.java b/src/org/torproject/android/Orbot.java index d57eacf..9f6eb6d 100644 --- a/src/org/torproject/android/Orbot.java +++ b/src/org/torproject/android/Orbot.java @@ -8,6 +8,7 @@ import static org.torproject.android.TorConstants.TAG; import java.net.URLDecoder; import java.util.Locale;
+import org.sandroproxy.ony.R; import org.torproject.android.service.TorService; import org.torproject.android.service.TorServiceConstants; import org.torproject.android.service.TorServiceUtils; @@ -64,11 +65,11 @@ import android.widget.Toast;
public class Orbot extends ActionBarActivity implements TorConstants, OnLongClickListener, OnTouchListener, OnSharedPreferenceChangeListener { - /* Useful UI bits */ - private TextView lblStatus = null; //the main text display widget - private ImageProgressView imgStatus = null; //the main touchable image for activating Orbot + /* Useful UI bits */ + private TextView lblStatus = null; //the main text display widget + private ImageProgressView imgStatus = null; //the main touchable image for activating Orbot
- private MenuItem mItemOnOff = null; + private MenuItem mItemOnOff = null; private TextView downloadText = null; private TextView uploadText = null; private TextView mTxtOrbotLog = null; @@ -76,191 +77,191 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic private boolean mDrawerOpen = false; private View mViewMain = null;
- /* Some tracking bits */ - private int torStatus = TorServiceConstants.STATUS_OFF; //latest status reported from the tor service - - private SharedPreferences mPrefs = null; + /* Some tracking bits */ + private int torStatus = TorServiceConstants.STATUS_OFF; //latest status reported from the tor service + + private SharedPreferences mPrefs = null;
- private boolean autoStartFromIntent = false; - - private final static long INIT_DELAY = 100; + private boolean autoStartFromIntent = false; + + private final static long INIT_DELAY = 100;
/** Called when the activity is first created. */ - public void onCreate(Bundle savedInstanceState) { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
mPrefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); mPrefs.registerOnSharedPreferenceChangeListener(this); - + setLocale();
- doLayout(); - - appConflictChecker (); - - - // Register to receive messages. - // We are registering an observer (mMessageReceiver) to receive Intents - // with actions named "custom-event-name". - LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, - new IntentFilter("status")); - - LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, - new IntentFilter("log")); - - mHandler.postDelayed(new Runnable () - { - - public void run () - { - startService(TorServiceConstants.CMD_INIT); - } - },INIT_DELAY); - - } - - // Our handler for received Intents. This will be called whenever an Intent - // with an action named "custom-event-name" is broadcasted. - private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { - - - - @Override - public void onReceive(Context context, Intent intent) { - // Get extra data included in the Intent - - if (intent.hasExtra("log")) - { - String log = intent.getStringExtra("log"); - updateStatus(log); - } - else if (intent.hasExtra("up")) - { - long upload = intent.getLongExtra("up",0); - long download = intent.getLongExtra("down",0); - long written = intent.getLongExtra("written",0); - long read = intent.getLongExtra("read",0); - - Message msg = mHandler.obtainMessage(TorServiceConstants.MESSAGE_TRAFFIC_COUNT); - msg.getData().putLong("download", download); - msg.getData().putLong("upload", upload); - msg.getData().putLong("readTotal", read); - msg.getData().putLong("writeTotal", written); - mHandler.sendMessage(msg); - - } - else if (intent.hasExtra("status")) - { - torStatus = intent.getIntExtra("status", TorServiceConstants.STATUS_OFF); - updateStatus(""); - } - - } - }; - - ProgressDialog mProgressDialog; - - private void startService (String action) - { - - Intent torService = new Intent(this, TorService.class); - torService.setAction(action); - startService(torService); - - } - - private void stopService () - { - - Intent torService = new Intent(this, TorService.class); - stopService(torService); - - } - - private void doLayout () - { - setContentView(R.layout.layout_main); - - mViewMain = findViewById(R.id.viewMain); - lblStatus = (TextView)findViewById(R.id.lblStatus); - lblStatus.setOnLongClickListener(this); - imgStatus = (ImageProgressView)findViewById(R.id.imgStatus); - imgStatus.setOnLongClickListener(this); - imgStatus.setOnTouchListener(this); - - lblStatus.setText("Initializing the application..."); - - downloadText = (TextView)findViewById(R.id.trafficDown); + doLayout(); + + appConflictChecker (); + + + // Register to receive messages. + // We are registering an observer (mMessageReceiver) to receive Intents + // with actions named "custom-event-name". + LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, + new IntentFilter("status")); + + LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, + new IntentFilter("log")); + + mHandler.postDelayed(new Runnable () + { + + public void run () + { + startService(TorServiceConstants.CMD_INIT); + } + },INIT_DELAY); + + } + + // Our handler for received Intents. This will be called whenever an Intent + // with an action named "custom-event-name" is broadcasted. + private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { + + + + @Override + public void onReceive(Context context, Intent intent) { + // Get extra data included in the Intent + + if (intent.hasExtra("log")) + { + String log = intent.getStringExtra("log"); + updateStatus(log); + } + else if (intent.hasExtra("up")) + { + long upload = intent.getLongExtra("up",0); + long download = intent.getLongExtra("down",0); + long written = intent.getLongExtra("written",0); + long read = intent.getLongExtra("read",0); + + Message msg = mHandler.obtainMessage(TorServiceConstants.MESSAGE_TRAFFIC_COUNT); + msg.getData().putLong("download", download); + msg.getData().putLong("upload", upload); + msg.getData().putLong("readTotal", read); + msg.getData().putLong("writeTotal", written); + mHandler.sendMessage(msg); + + } + else if (intent.hasExtra("status")) + { + torStatus = intent.getIntExtra("status", TorServiceConstants.STATUS_OFF); + updateStatus(""); + } + + } + }; + + ProgressDialog mProgressDialog; + + private void startService (String action) + { + + Intent torService = new Intent(this, TorService.class); + torService.setAction(action); + startService(torService); + + } + + private void stopService () + { + + Intent torService = new Intent(this, TorService.class); + stopService(torService); + + } + + private void doLayout () + { + setContentView(R.layout.layout_main); + + mViewMain = findViewById(R.id.viewMain); + lblStatus = (TextView)findViewById(R.id.lblStatus); + lblStatus.setOnLongClickListener(this); + imgStatus = (ImageProgressView)findViewById(R.id.imgStatus); + imgStatus.setOnLongClickListener(this); + imgStatus.setOnTouchListener(this); + + lblStatus.setText("Initializing the application..."); + + downloadText = (TextView)findViewById(R.id.trafficDown); uploadText = (TextView)findViewById(R.id.trafficUp); mTxtOrbotLog = (TextView)findViewById(R.id.orbotLog);
mDrawer = ((SlidingDrawer)findViewById(R.id.SlidingDrawer)); - Button slideButton = (Button)findViewById(R.id.slideButton); - if (slideButton != null) - { - slideButton.setOnTouchListener(new OnTouchListener (){ - - @Override - public boolean onTouch(View v, MotionEvent event) { - - if (event.equals(MotionEvent.ACTION_DOWN)) - { - mDrawerOpen = !mDrawerOpen; - mTxtOrbotLog.setEnabled(mDrawerOpen); - } - return false; - } - - }); - } - - ScrollingMovementMethod smm = new ScrollingMovementMethod(); - + Button slideButton = (Button)findViewById(R.id.slideButton); + if (slideButton != null) + { + slideButton.setOnTouchListener(new OnTouchListener (){ + + @Override + public boolean onTouch(View v, MotionEvent event) { + + if (event.equals(MotionEvent.ACTION_DOWN)) + { + mDrawerOpen = !mDrawerOpen; + mTxtOrbotLog.setEnabled(mDrawerOpen); + } + return false; + } + + }); + } + + ScrollingMovementMethod smm = new ScrollingMovementMethod(); + mTxtOrbotLog.setMovementMethod(smm); mTxtOrbotLog.setOnLongClickListener(new View.OnLongClickListener() {
- @Override - public boolean onLongClick(View v) { - ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE); - cm.setText(mTxtOrbotLog.getText()); - Toast.makeText(Orbot.this, "LOG COPIED TO CLIPBOARD", Toast.LENGTH_SHORT).show(); - return true; - } + @Override + public boolean onLongClick(View v) { + ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE); + cm.setText(mTxtOrbotLog.getText()); + Toast.makeText(Orbot.this, "LOG COPIED TO CLIPBOARD", Toast.LENGTH_SHORT).show(); + return true; + } });
- downloadText.setText(formatCount(0) + " / " + formatTotal(0)); - uploadText.setText(formatCount(0) + " / " + formatTotal(0)); - + downloadText.setText(formatCount(0) + " / " + formatTotal(0)); + uploadText.setText(formatCount(0) + " / " + formatTotal(0)); + // Gesture detection - mGestureDetector = new GestureDetector(this, new MyGestureDetector()); - + mGestureDetector = new GestureDetector(this, new MyGestureDetector()); +
} - - GestureDetector mGestureDetector; + + GestureDetector mGestureDetector;
- @Override - public boolean onTouch(View v, MotionEvent event) { - return mGestureDetector.onTouchEvent(event); + @Override + public boolean onTouch(View v, MotionEvent event) { + return mGestureDetector.onTouchEvent(event);
- } - + } + private void appendLogTextAndScroll(String text) { if(mTxtOrbotLog != null && text != null && text.length() > 0){ - - if (mTxtOrbotLog.getText().length() > MAX_LOG_LENGTH) - mTxtOrbotLog.setText(""); - - mTxtOrbotLog.append(text + "\n"); + + if (mTxtOrbotLog.getText().length() > MAX_LOG_LENGTH) + mTxtOrbotLog.setText(""); + + mTxtOrbotLog.append(text + "\n"); final Layout layout = mTxtOrbotLog.getLayout(); if(layout != null){ int scrollDelta = layout.getLineBottom(mTxtOrbotLog.getLineCount() - 1) - mTxtOrbotLog.getScrollY() - mTxtOrbotLog.getHeight(); if(scrollDelta > 0) - mTxtOrbotLog.scrollBy(0, scrollDelta); + mTxtOrbotLog.scrollBy(0, scrollDelta); } } } @@ -283,29 +284,29 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
private void appConflictChecker () { - SharedPreferences sprefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); - - boolean showAppConflict = true;//sprefs.getBoolean("pref_show_conflict",true); - - String[] badApps = {"com.sec.msc.nts.android.proxy:com.sec.msc.nts.android.proxy","com.sec.pcw:Samsung Link"}; - - for (String badApp : badApps) - { - String[] badAppParts = badApp.split(":"); - - if (appInstalledOrNot(badAppParts[0])) - { - String msg = getString(R.string.please_disable_this_app_in_android_settings_apps_if_you_are_having_problems_with_orbot_) + badAppParts[1]; - - if (showAppConflict) - showAlert(getString(R.string.app_conflict),msg,true); - - appendLogTextAndScroll(msg); - } - } - - sprefs.edit().putBoolean("pref_show_conflict", false).commit(); - + SharedPreferences sprefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); + + boolean showAppConflict = true;//sprefs.getBoolean("pref_show_conflict",true); + + String[] badApps = {"com.sec.msc.nts.android.proxy:com.sec.msc.nts.android.proxy","com.sec.pcw:Samsung Link"}; + + for (String badApp : badApps) + { + String[] badAppParts = badApp.split(":"); + + if (appInstalledOrNot(badAppParts[0])) + { + String msg = getString(R.string.please_disable_this_app_in_android_settings_apps_if_you_are_having_problems_with_orbot_) + badAppParts[1]; + + if (showAppConflict) + showAlert(getString(R.string.app_conflict),msg,true); + + appendLogTextAndScroll(msg); + } + } + + sprefs.edit().putBoolean("pref_show_conflict", false).commit(); + }
@@ -314,27 +315,27 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic private void showAbout () {
- LayoutInflater li = LayoutInflater.from(this); - View view = li.inflate(R.layout.layout_about, null); - - String version = ""; - - try { - version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName + " (Tor " + TorServiceConstants.BINARY_TOR_VERSION + ")"; - } catch (NameNotFoundException e) { - version = "Version Not Found"; - } - - TextView versionName = (TextView)view.findViewById(R.id.versionName); - versionName.setText(version); - - new AlertDialog.Builder(this) - .setTitle(getString(R.string.button_about)) - .setView(view) - .show(); + LayoutInflater li = LayoutInflater.from(this); + View view = li.inflate(R.layout.layout_about, null); + + String version = ""; + + try { + version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName + " (Tor " + TorServiceConstants.BINARY_TOR_VERSION + ")"; + } catch (NameNotFoundException e) { + version = "Version Not Found"; + } + + TextView versionName = (TextView)view.findViewById(R.id.versionName); + versionName.setText(version); + + new AlertDialog.Builder(this) + .setTitle(getString(R.string.button_about)) + .setView(view) + .show(); }
- @Override + @Override public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item); @@ -374,7 +375,7 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic } else if (item.getItemId() == R.id.menu_wizard) { - startActivity(new Intent(this, ChooseLocaleWizardActivity.class)); + startActivity(new Intent(this, ChooseLocaleWizardActivity.class));
} else if (item.getItemId() == R.id.menu_verify) @@ -394,12 +395,10 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
} - /** - * remove for now... VPN is not ready yet else if (item.getItemId() == R.id.menu_vpn) { - this.startVpnService(); - }*/ + this.startVpnService(); + }
return true; } @@ -412,7 +411,7 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic private void doExit () { try { - + //one of the confusing things about all of this code is the multiple //places where things like "stopTor" are called, both in the Activity and the Service //not something to tackle in your first iteration, but i thin we can talk about fixing @@ -432,307 +431,307 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic }
/* (non-Javadoc) - * @see android.app.Activity#onPause() - */ - protected void onPause() { - try - { - super.onPause(); - - if (aDialog != null) - aDialog.dismiss(); - } - catch (IllegalStateException ise) - { - //can happen on exit/shutdown - } - } - - private void doTorCheck () - { - - DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { - - public void onClick(DialogInterface dialog, int which) { - switch (which){ - case DialogInterface.BUTTON_POSITIVE: - - openBrowser(URL_TOR_CHECK); - - - - break; - - case DialogInterface.BUTTON_NEGATIVE: - - //do nothing - break; - } - } - }; - - AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setMessage(R.string.tor_check).setPositiveButton(R.string.btn_okay, dialogClickListener) - .setNegativeButton(R.string.btn_cancel, dialogClickListener).show(); - - } - - private void enableHiddenServicePort (int hsPort) - { - - Editor pEdit = mPrefs.edit(); - - String hsPortString = mPrefs.getString("pref_hs_ports", ""); - - if (hsPortString.length() > 0 && hsPortString.indexOf(hsPort+"")==-1) - hsPortString += ',' + hsPort; - else - hsPortString = hsPort + ""; - - pEdit.putString("pref_hs_ports", hsPortString); - pEdit.putBoolean("pref_hs_enable", true); - - pEdit.commit(); - - String onionHostname = mPrefs.getString("pref_hs_hostname",""); - - while (onionHostname.length() == 0) - { - //we need to stop and start Tor - try { - stopTor(); - - Thread.sleep(3000); //wait three seconds - - startTor(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - onionHostname = mPrefs.getString("pref_hs_hostname",""); - } - - Intent nResult = new Intent(); - nResult.putExtra("hs_host", onionHostname); - setResult(RESULT_OK, nResult); - - } - - - private synchronized void handleIntents () - { - if (getIntent() == null) - return; - - // Get intent, action and MIME type - Intent intent = getIntent(); - String action = intent.getAction(); - String type = intent.getType(); - - if (action == null) - return; - - if (action.equals("org.torproject.android.REQUEST_HS_PORT")) - { - - DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { - - public void onClick(DialogInterface dialog, int which) { - switch (which){ - case DialogInterface.BUTTON_POSITIVE: - - int hsPort = getIntent().getIntExtra("hs_port", -1); - - enableHiddenServicePort (hsPort); - - finish(); - - - break; - - case DialogInterface.BUTTON_NEGATIVE: - //No button clicked - finish(); - break; - } - } - }; - - int hsPort = getIntent().getIntExtra("hs_port", -1); - - String requestMsg = getString(R.string.hidden_service_request, hsPort); - AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setMessage(requestMsg).setPositiveButton("Allow", dialogClickListener) - .setNegativeButton("Deny", dialogClickListener).show(); - - - } - else if (action.equals("org.torproject.android.START_TOR")) - { - autoStartFromIntent = true; - - try { - startTor(); - - Intent nResult = new Intent(); - - //nResult.putExtra("socks", ); //TODO respond with socks, transport, dns, etc - - setResult(RESULT_OK,nResult); - - } catch (RemoteException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - else if (action.equals(Intent.ACTION_VIEW)) - { - String urlString = intent.getDataString(); - - if (urlString != null) - { - - if (urlString.toLowerCase().startsWith("bridge://")) - - { - String newBridgeValue = urlString.substring(9); //remove the bridge protocol piece - newBridgeValue = URLDecoder.decode(newBridgeValue); //decode the value here - - showAlert("Bridges Updated","Restart Orbot to use this bridge: " + newBridgeValue,false); - - String bridges = mPrefs.getString(TorConstants.PREF_BRIDGES_LIST, null); - - Editor pEdit = mPrefs.edit(); - - if (bridges != null && bridges.trim().length() > 0) - { - if (bridges.indexOf('\n')!=-1) - bridges += '\n' + newBridgeValue; - else - bridges += ',' + newBridgeValue; - } - else - bridges = newBridgeValue; - - pEdit.putString(TorConstants.PREF_BRIDGES_LIST,bridges); //set the string to a preference - pEdit.putBoolean(TorConstants.PREF_BRIDGES_ENABLED,true); - - pEdit.commit(); - - setResult(RESULT_OK); - } - } - } - else - { - - showWizard = mPrefs.getBoolean("show_wizard",showWizard); - - if (showWizard) - { - Editor pEdit = mPrefs.edit(); - pEdit.putBoolean("show_wizard",false); - pEdit.commit(); - showWizard = false; - - startActivity(new Intent(this, ChooseLocaleWizardActivity.class)); - - } - - } - - setIntent(null); - - updateStatus (""); - - } - - private boolean showWizard = true; - - - @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - - doLayout(); - updateStatus(""); - } - - - /* - * Launch the system activity for Uri viewing with the provided url - */ - private void openBrowser(final String browserLaunchUrl) - { - boolean isOrwebInstalled = appInstalledOrNot("info.guardianproject.browser"); - boolean isTransProxy = mPrefs.getBoolean("pref_transparent", false); - - if (isOrwebInstalled) - { - startIntent("info.guardianproject.browser",Intent.ACTION_VIEW,Uri.parse(browserLaunchUrl)); - } - else if (isTransProxy) - { - Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(browserLaunchUrl)); - intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - else - { - AlertDialog aDialog = new AlertDialog.Builder(Orbot.this) + * @see android.app.Activity#onPause() + */ + protected void onPause() { + try + { + super.onPause(); + + if (aDialog != null) + aDialog.dismiss(); + } + catch (IllegalStateException ise) + { + //can happen on exit/shutdown + } + } + + private void doTorCheck () + { + + DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { + + public void onClick(DialogInterface dialog, int which) { + switch (which){ + case DialogInterface.BUTTON_POSITIVE: + + openBrowser(URL_TOR_CHECK); + + + + break; + + case DialogInterface.BUTTON_NEGATIVE: + + //do nothing + break; + } + } + }; + + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setMessage(R.string.tor_check).setPositiveButton(R.string.btn_okay, dialogClickListener) + .setNegativeButton(R.string.btn_cancel, dialogClickListener).show(); + + } + + private void enableHiddenServicePort (int hsPort) + { + + Editor pEdit = mPrefs.edit(); + + String hsPortString = mPrefs.getString("pref_hs_ports", ""); + + if (hsPortString.length() > 0 && hsPortString.indexOf(hsPort+"")==-1) + hsPortString += ',' + hsPort; + else + hsPortString = hsPort + ""; + + pEdit.putString("pref_hs_ports", hsPortString); + pEdit.putBoolean("pref_hs_enable", true); + + pEdit.commit(); + + String onionHostname = mPrefs.getString("pref_hs_hostname",""); + + while (onionHostname.length() == 0) + { + //we need to stop and start Tor + try { + stopTor(); + + Thread.sleep(3000); //wait three seconds + + startTor(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + onionHostname = mPrefs.getString("pref_hs_hostname",""); + } + + Intent nResult = new Intent(); + nResult.putExtra("hs_host", onionHostname); + setResult(RESULT_OK, nResult); + + } + + + private synchronized void handleIntents () + { + if (getIntent() == null) + return; + + // Get intent, action and MIME type + Intent intent = getIntent(); + String action = intent.getAction(); + String type = intent.getType(); + + if (action == null) + return; + + if (action.equals("org.torproject.android.REQUEST_HS_PORT")) + { + + DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { + + public void onClick(DialogInterface dialog, int which) { + switch (which){ + case DialogInterface.BUTTON_POSITIVE: + + int hsPort = getIntent().getIntExtra("hs_port", -1); + + enableHiddenServicePort (hsPort); + + finish(); + + + break; + + case DialogInterface.BUTTON_NEGATIVE: + //No button clicked + finish(); + break; + } + } + }; + + int hsPort = getIntent().getIntExtra("hs_port", -1); + + String requestMsg = getString(R.string.hidden_service_request, hsPort); + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setMessage(requestMsg).setPositiveButton("Allow", dialogClickListener) + .setNegativeButton("Deny", dialogClickListener).show(); + + + } + else if (action.equals("org.torproject.android.START_TOR")) + { + autoStartFromIntent = true; + + try { + startTor(); + + Intent nResult = new Intent(); + + //nResult.putExtra("socks", ); //TODO respond with socks, transport, dns, etc + + setResult(RESULT_OK,nResult); + + } catch (RemoteException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + else if (action.equals(Intent.ACTION_VIEW)) + { + String urlString = intent.getDataString(); + + if (urlString != null) + { + + if (urlString.toLowerCase().startsWith("bridge://")) + + { + String newBridgeValue = urlString.substring(9); //remove the bridge protocol piece + newBridgeValue = URLDecoder.decode(newBridgeValue); //decode the value here + + showAlert("Bridges Updated","Restart Orbot to use this bridge: " + newBridgeValue,false); + + String bridges = mPrefs.getString(TorConstants.PREF_BRIDGES_LIST, null); + + Editor pEdit = mPrefs.edit(); + + if (bridges != null && bridges.trim().length() > 0) + { + if (bridges.indexOf('\n')!=-1) + bridges += '\n' + newBridgeValue; + else + bridges += ',' + newBridgeValue; + } + else + bridges = newBridgeValue; + + pEdit.putString(TorConstants.PREF_BRIDGES_LIST,bridges); //set the string to a preference + pEdit.putBoolean(TorConstants.PREF_BRIDGES_ENABLED,true); + + pEdit.commit(); + + setResult(RESULT_OK); + } + } + } + else + { + + showWizard = mPrefs.getBoolean("show_wizard",showWizard); + + if (showWizard) + { + Editor pEdit = mPrefs.edit(); + pEdit.putBoolean("show_wizard",false); + pEdit.commit(); + showWizard = false; + + startActivity(new Intent(this, ChooseLocaleWizardActivity.class)); + + } + + } + + setIntent(null); + + updateStatus (""); + + } + + private boolean showWizard = true; + + + @Override + public void onConfigurationChanged(Configuration newConfig) { + super.onConfigurationChanged(newConfig); + + doLayout(); + updateStatus(""); + } + + + /* + * Launch the system activity for Uri viewing with the provided url + */ + private void openBrowser(final String browserLaunchUrl) + { + boolean isOrwebInstalled = appInstalledOrNot("info.guardianproject.browser"); + boolean isTransProxy = mPrefs.getBoolean("pref_transparent", false); + + if (isOrwebInstalled) + { + startIntent("info.guardianproject.browser",Intent.ACTION_VIEW,Uri.parse(browserLaunchUrl)); + } + else if (isTransProxy) + { + Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(browserLaunchUrl)); + intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(intent); + } + else + { + AlertDialog aDialog = new AlertDialog.Builder(Orbot.this) .setIcon(R.drawable.onion32) - .setTitle(R.string.install_apps_) - .setMessage(R.string.it_doesn_t_seem_like_you_have_orweb_installed_want_help_with_that_or_should_we_just_open_the_browser_) - .setPositiveButton(android.R.string.ok, new OnClickListener () - { - - @Override - public void onClick(DialogInterface dialog, int which) { - - //prompt to install Orweb - Intent intent = new Intent(Orbot.this,TipsAndTricks.class); - startActivity(intent); - - } - - }) - .setNegativeButton(android.R.string.no, new OnClickListener () - { - - @Override - public void onClick(DialogInterface dialog, int which) { - Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(browserLaunchUrl)); - intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - - } - - }) - .show(); - - } - - } - - private void startIntent (String pkg, String action, Uri data) - { - Intent i; - PackageManager manager = getPackageManager(); - try { - i = manager.getLaunchIntentForPackage(pkg); - if (i == null) - throw new PackageManager.NameNotFoundException(); - i.setAction(action); - i.setData(data); - startActivity(i); - } catch (PackageManager.NameNotFoundException e) { - - } - } - - private boolean appInstalledOrNot(String uri) + .setTitle(R.string.install_apps_) + .setMessage(R.string.it_doesn_t_seem_like_you_have_orweb_installed_want_help_with_that_or_should_we_just_open_the_browser_) + .setPositiveButton(android.R.string.ok, new OnClickListener () + { + + @Override + public void onClick(DialogInterface dialog, int which) { + + //prompt to install Orweb + Intent intent = new Intent(Orbot.this,TipsAndTricks.class); + startActivity(intent); + + } + + }) + .setNegativeButton(android.R.string.no, new OnClickListener () + { + + @Override + public void onClick(DialogInterface dialog, int which) { + Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(browserLaunchUrl)); + intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(intent); + + } + + }) + .show(); + + } + + } + + private void startIntent (String pkg, String action, Uri data) + { + Intent i; + PackageManager manager = getPackageManager(); + try { + i = manager.getLaunchIntentForPackage(pkg); + if (i == null) + throw new PackageManager.NameNotFoundException(); + i.setAction(action); + i.setData(data); + startActivity(i); + } catch (PackageManager.NameNotFoundException e) { + + } + } + + private boolean appInstalledOrNot(String uri) { PackageManager pm = getPackageManager(); try @@ -745,7 +744,7 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic return false; } } - + /* * Load the basic settings application to display torrc */ @@ -757,95 +756,95 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
@Override - protected void onActivityResult(int request, int response, Intent data) { - super.onActivityResult(request, response, data); - - - if (request == 1 && response == RESULT_OK) - { - if (data != null && data.getBooleanExtra("transproxywipe", false)) - { - - boolean result = flushTransProxy(); - - if (result) - { - - Toast.makeText(this, R.string.transparent_proxy_rules_flushed_, Toast.LENGTH_SHORT).show(); - - } - else - { - - Toast.makeText(this, R.string.you_do_not_have_root_access_enabled, Toast.LENGTH_SHORT).show(); - - } - - } - else if (torStatus == TorServiceConstants.STATUS_ON) - { - updateSettings(); - Toast.makeText(this, R.string.you_may_need_to_stop_and_start_orbot_for_settings_change_to_be_enabled_, Toast.LENGTH_SHORT).show(); - - } - } - else if (request == REQUEST_VPN && response == RESULT_OK) - { - startService(TorServiceConstants.CMD_VPN); - } - - } + protected void onActivityResult(int request, int response, Intent data) { + super.onActivityResult(request, response, data); + + + if (request == 1 && response == RESULT_OK) + { + if (data != null && data.getBooleanExtra("transproxywipe", false)) + { + + boolean result = flushTransProxy(); + + if (result) + { + + Toast.makeText(this, R.string.transparent_proxy_rules_flushed_, Toast.LENGTH_SHORT).show(); + + } + else + { + + Toast.makeText(this, R.string.you_do_not_have_root_access_enabled, Toast.LENGTH_SHORT).show(); + + } + + } + else if (torStatus == TorServiceConstants.STATUS_ON) + { + updateSettings(); + Toast.makeText(this, R.string.you_may_need_to_stop_and_start_orbot_for_settings_change_to_be_enabled_, Toast.LENGTH_SHORT).show(); + + } + } + else if (request == REQUEST_VPN && response == RESULT_OK) + { + startService(TorServiceConstants.CMD_VPN); + } + + }
private final static int REQUEST_VPN = 8888;
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) - public void startVpnService () + public void startVpnService () { - Intent intent = VpnService.prepare(this); - if (intent != null) { - startActivityForResult(intent,REQUEST_VPN); - } - else - { - startService(TorServiceConstants.CMD_VPN); - - } + Intent intent = VpnService.prepare(this); + if (intent != null) { + startActivityForResult(intent,REQUEST_VPN); + } + else + { + startService(TorServiceConstants.CMD_VPN); + + } }
private boolean flushTransProxy () { - startService(TorServiceConstants.CMD_FLUSH); - return true; + startService(TorServiceConstants.CMD_FLUSH); + return true; }
private boolean updateSettings () { - //todo send service command - startService(TorServiceConstants.CMD_UPDATE); - return true; + //todo send service command + startService(TorServiceConstants.CMD_UPDATE); + return true; }
- @Override - protected void onResume() { - super.onResume(); + @Override + protected void onResume() { + super.onResume();
- mHandler.postDelayed(new Runnable () - { - public void run () - { + mHandler.postDelayed(new Runnable () + { + public void run () + {
- setLocale(); - - handleIntents(); + setLocale(); + + handleIntents();
- } - } - , 500); - - - } + } + } + , 500); + + + }
- AlertDialog aDialog = null; + AlertDialog aDialog = null;
//general alert dialog for mostly Tor warning messages //sometimes this can go haywire or crazy with too many error @@ -881,7 +880,7 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic aDialog.setCanceledOnTouchOutside(true); }
- private void updateStatus (String torServiceMsg) + private void updateStatus (String torServiceMsg) {
//now update the layout_main UI based on the status @@ -890,9 +889,9 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
if (torStatus == TorServiceConstants.STATUS_ON) { - + imgStatus.setImageResource(R.drawable.toron); - + String lblMsg = getString(R.string.status_activated); lblStatus.setText(lblMsg);
@@ -902,7 +901,7 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
if (torServiceMsg != null && torServiceMsg.length() > 0) { - appendLogTextAndScroll(torServiceMsg); + appendLogTextAndScroll(torServiceMsg); }
boolean showFirstTime = mPrefs.getBoolean("connect_first_time",true); @@ -923,23 +922,23 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
if (autoStartFromIntent) { - setResult(RESULT_OK); - finish(); + setResult(RESULT_OK); + finish(); }
} else if (torStatus == TorServiceConstants.STATUS_CONNECTING) { - + imgStatus.setImageResource(R.drawable.torstarting);
if (mItemOnOff != null) mItemOnOff.setTitle(R.string.menu_stop); - - + + if (lblStatus != null && torServiceMsg != null) - if (torServiceMsg.indexOf('%')!=-1) - lblStatus.setText(torServiceMsg); + if (torServiceMsg.indexOf('%')!=-1) + lblStatus.setText(torServiceMsg);
appendLogTextAndScroll(torServiceMsg);
@@ -958,7 +957,7 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
} - +
// guess what? this start's Tor! actually no it just requests via the local ITorService to the remote TorService instance @@ -967,10 +966,10 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic {
- startService (TorServiceConstants.CMD_START); - torStatus = TorServiceConstants.STATUS_CONNECTING; - - mTxtOrbotLog.setText(""); + startService (TorServiceConstants.CMD_START); + torStatus = TorServiceConstants.STATUS_CONNECTING; + + mTxtOrbotLog.setText("");
//here we update the UI which is a bit sloppy and mixed up code wise //might be best to just call updateStatus() instead of directly manipulating UI in this method - yep makes sense @@ -983,21 +982,21 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic mHandler.sendMessage(msg);
- + }
//now we stop Tor! amazing! private void stopTor () throws RemoteException { - - startService (TorServiceConstants.CMD_STOP); - torStatus = TorServiceConstants.STATUS_OFF; + + startService (TorServiceConstants.CMD_STOP); + torStatus = TorServiceConstants.STATUS_OFF;
- Message msg = mHandler.obtainMessage(TorServiceConstants.DISABLE_TOR_MSG); - mHandler.sendMessage(msg); - + Message msg = mHandler.obtainMessage(TorServiceConstants.DISABLE_TOR_MSG); + mHandler.sendMessage(msg); +
- + }
/* @@ -1006,48 +1005,48 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic */ public boolean onLongClick(View view) {
- if (!mDrawerOpen) - { - try - { - - if (torStatus == TorServiceConstants.STATUS_OFF) - { - - startTor(); - } - else - { - - stopTor(); - stopService (); - - } - - return true; - - } - catch (Exception e) - { - Log.d(TAG,"error onclick",e); - } - - } - + if (!mDrawerOpen) + { + try + { + + if (torStatus == TorServiceConstants.STATUS_OFF) + { + + startTor(); + } + else + { + + stopTor(); + stopService (); + + } + + return true; + + } + catch (Exception e) + { + Log.d(TAG,"error onclick",e); + } + + } + return false;
}
- +
// this is what takes messages or values from the callback threads or other non-mainUI threads //and passes them back into the main UI thread for display to the user private Handler mHandler = new Handler() { - - private String lastServiceMsg = null; - + + private String lastServiceMsg = null; + public void handleMessage(Message msg) { switch (msg.what) { case TorServiceConstants.STATUS_MSG: @@ -1057,9 +1056,9 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
if (lastServiceMsg == null || !lastServiceMsg.equals(torServiceMsg)) { - updateStatus(torServiceMsg); + updateStatus(torServiceMsg);
- lastServiceMsg = torServiceMsg; + lastServiceMsg = torServiceMsg; }
break; @@ -1070,28 +1069,28 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
break; case TorServiceConstants.DISABLE_TOR_MSG: - - updateStatus((String)msg.getData().getString(HANDLER_TOR_MSG)); - - break; - + + updateStatus((String)msg.getData().getString(HANDLER_TOR_MSG)); + + break; +
- case TorServiceConstants.MESSAGE_TRAFFIC_COUNT : + case TorServiceConstants.MESSAGE_TRAFFIC_COUNT : + + Bundle data = msg.getData(); + DataCount datacount = new DataCount(data.getLong("upload"),data.getLong("download"));
- Bundle data = msg.getData(); - DataCount datacount = new DataCount(data.getLong("upload"),data.getLong("download")); - - long totalRead = data.getLong("readTotal"); - long totalWrite = data.getLong("writeTotal"); - - downloadText.setText(formatCount(datacount.Download) + " / " + formatTotal(totalRead)); - uploadText.setText(formatCount(datacount.Upload) + " / " + formatTotal(totalWrite)); + long totalRead = data.getLong("readTotal"); + long totalWrite = data.getLong("writeTotal"); + + downloadText.setText(formatCount(datacount.Download) + " / " + formatTotal(totalRead)); + uploadText.setText(formatCount(datacount.Upload) + " / " + formatTotal(totalWrite));
- if (torStatus != TorServiceConstants.STATUS_ON) - { - updateStatus(""); - } - + if (torStatus != TorServiceConstants.STATUS_ON) + { + updateStatus(""); + } + default: super.handleMessage(msg); } @@ -1111,107 +1110,104 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
private void setLocale () { - +
Configuration config = getResources().getConfiguration(); String lang = mPrefs.getString(PREF_DEFAULT_LOCALE, "");
if (! "".equals(lang) && ! config.locale.getLanguage().equals(lang)) { - Locale locale = new Locale(lang); + Locale locale = new Locale(lang); Locale.setDefault(locale); config.locale = locale; getResources().updateConfiguration(config, getResources().getDisplayMetrics()); } }
- @Override - protected void onDestroy() { - super.onDestroy(); - LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver); - - } - - public class DataCount { - // data uploaded - public long Upload; - // data downloaded - public long Download; - - DataCount(long Upload, long Download){ - this.Upload = Upload; - this.Download = Download; - } - } - - private String formatCount(long count) { - // Converts the supplied argument into a string. - // Under 2Mb, returns "xxx.xKb" - // Over 2Mb, returns "xxx.xxMb" - if (count < 1e6) - return ((float)((int)(count*10/1024))/10 + "kbps"); - return ((float)((int)(count*100/1024/1024))/100 + "mbps"); - - //return count+" kB"; - } - - private String formatTotal(long count) { - // Converts the supplied argument into a string. - // Under 2Mb, returns "xxx.xKb" - // Over 2Mb, returns "xxx.xxMb" - if (count < 1e6) - return ((float)((int)(count*10/1024))/10 + "KB"); - return ((float)((int)(count*100/1024/1024))/100 + "MB"); - - //return count+" kB"; - } - - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, - String key) { - - - } - - private static final float ROTATE_FROM = 0.0f; - private static final float ROTATE_TO = 360.0f*4f;// 3.141592654f * 32.0f; - - public void spinOrbot (float direction) - { - startService (TorServiceConstants.CMD_NEWNYM); - - - Toast.makeText(this, R.string.newnym, Toast.LENGTH_SHORT).show(); - - // Rotate3dAnimation rotation = new Rotate3dAnimation(ROTATE_FROM, ROTATE_TO*direction, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); - Rotate3dAnimation rotation = new Rotate3dAnimation(ROTATE_FROM, ROTATE_TO*direction, imgStatus.getWidth()/2f,imgStatus.getWidth()/2f,20f,false); - rotation.setFillAfter(true); - rotation.setInterpolator(new AccelerateInterpolator()); - rotation.setDuration((long) 2*1000); - rotation.setRepeatCount(0); - imgStatus.startAnimation(rotation); - - - } - - class MyGestureDetector extends SimpleOnGestureListener { - @Override - public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { - try { - if (torStatus == TorServiceConstants.STATUS_ON) - { - float direction = 1f; - if (velocityX < 0) - direction = -1f; - spinOrbot (direction); - } - } catch (Exception e) { - // nothing - } - return false; - } - - } + @Override + protected void onDestroy() { + super.onDestroy(); + LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
+ }
+ public class DataCount { + // data uploaded + public long Upload; + // data downloaded + public long Download; + + DataCount(long Upload, long Download){ + this.Upload = Upload; + this.Download = Download; + } + } + + private String formatCount(long count) { + // Converts the supplied argument into a string. + // Under 2Mb, returns "xxx.xKb" + // Over 2Mb, returns "xxx.xxMb" + if (count < 1e6) + return ((float)((int)(count*10/1024))/10 + "kbps"); + return ((float)((int)(count*100/1024/1024))/100 + "mbps"); + + //return count+" kB"; + } + + private String formatTotal(long count) { + // Converts the supplied argument into a string. + // Under 2Mb, returns "xxx.xKb" + // Over 2Mb, returns "xxx.xxMb" + if (count < 1e6) + return ((float)((int)(count*10/1024))/10 + "KB"); + return ((float)((int)(count*100/1024/1024))/100 + "MB"); + + //return count+" kB"; + } + + @Override + public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, + String key) { + + + } + + private static final float ROTATE_FROM = 0.0f; + private static final float ROTATE_TO = 360.0f*4f;// 3.141592654f * 32.0f; + + public void spinOrbot (float direction) + { + startService (TorServiceConstants.CMD_NEWNYM); + + + Toast.makeText(this, R.string.newnym, Toast.LENGTH_SHORT).show(); + + // Rotate3dAnimation rotation = new Rotate3dAnimation(ROTATE_FROM, ROTATE_TO*direction, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); + Rotate3dAnimation rotation = new Rotate3dAnimation(ROTATE_FROM, ROTATE_TO*direction, imgStatus.getWidth()/2f,imgStatus.getWidth()/2f,20f,false); + rotation.setFillAfter(true); + rotation.setInterpolator(new AccelerateInterpolator()); + rotation.setDuration((long) 2*1000); + rotation.setRepeatCount(0); + imgStatus.startAnimation(rotation); + + + } + + class MyGestureDetector extends SimpleOnGestureListener { + @Override + public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { + try { + if (torStatus == TorServiceConstants.STATUS_ON) + { + float direction = 1f; + if (velocityX < 0) + direction = -1f; + spinOrbot (direction); + } + } catch (Exception e) { + // nothing + } + return false; + } + } } diff --git a/src/org/torproject/android/OrbotDiagnosticsActivity.java b/src/org/torproject/android/OrbotDiagnosticsActivity.java index b639d82..995e99a 100644 --- a/src/org/torproject/android/OrbotDiagnosticsActivity.java +++ b/src/org/torproject/android/OrbotDiagnosticsActivity.java @@ -7,6 +7,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList;
+import org.sandroproxy.ony.R; import org.sufficientlysecure.rootcommands.Shell; import org.sufficientlysecure.rootcommands.command.SimpleCommand; import org.torproject.android.service.TorResourceInstaller; diff --git a/src/org/torproject/android/service/TorResourceInstaller.java b/src/org/torproject/android/service/TorResourceInstaller.java index e4b0ba4..d10ccdb 100644 --- a/src/org/torproject/android/service/TorResourceInstaller.java +++ b/src/org/torproject/android/service/TorResourceInstaller.java @@ -17,9 +17,9 @@ import java.util.concurrent.TimeoutException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream;
+import org.sandroproxy.ony.R; import org.sufficientlysecure.rootcommands.Shell; import org.sufficientlysecure.rootcommands.command.SimpleCommand; -import org.torproject.android.R; import org.torproject.android.TorConstants;
import android.content.Context; @@ -28,44 +28,44 @@ import android.util.Log;
public class TorResourceInstaller implements TorServiceConstants {
- - File installFolder; - Context context; - - public TorResourceInstaller (Context context, File installFolder) - { - this.installFolder = installFolder; - - this.context = context; - } - - public void deleteDirectory(File file) { - if( file.exists() ) { - if (file.isDirectory()) { - File[] files = file.listFiles(); - for(int i=0; i<files.length; i++) { - if(files[i].isDirectory()) { - deleteDirectory(files[i]); - } - else { - files[i].delete(); - } - } - } - file.delete(); - } - } - - private final static String COMMAND_RM_FORCE = "rm -f "; - - // - /* - * Extract the Tor resources from the APK file using ZIP - */ - public boolean installResources () throws IOException, FileNotFoundException, TimeoutException - { - - InputStream is; + + File installFolder; + Context context; + + public TorResourceInstaller (Context context, File installFolder) + { + this.installFolder = installFolder; + + this.context = context; + } + + public void deleteDirectory(File file) { + if( file.exists() ) { + if (file.isDirectory()) { + File[] files = file.listFiles(); + for(int i=0; i<files.length; i++) { + if(files[i].isDirectory()) { + deleteDirectory(files[i]); + } + else { + files[i].delete(); + } + } + } + file.delete(); + } + } + + private final static String COMMAND_RM_FORCE = "rm -f "; + + // + /* + * Extract the Tor resources from the APK file using ZIP + */ + public boolean installResources () throws IOException, FileNotFoundException, TimeoutException + { + + InputStream is; File outFile;
deleteDirectory(installFolder); @@ -74,129 +74,129 @@ public class TorResourceInstaller implements TorServiceConstants {
Shell shell = Shell.startShell(new ArrayList<String>(),installFolder.getAbsolutePath());
- is = context.getResources().openRawResource(R.raw.torrc); - outFile = new File(installFolder, TORRC_ASSET_KEY); - shell.add(new SimpleCommand(COMMAND_RM_FORCE + outFile.getAbsolutePath())).waitForFinish(); - streamToFile(is,outFile, false, false); - - is = context.getResources().openRawResource(R.raw.torpolipo); - outFile = new File(installFolder, POLIPOCONFIG_ASSET_KEY); - shell.add(new SimpleCommand(COMMAND_RM_FORCE + outFile.getAbsolutePath())).waitForFinish(); - streamToFile(is,outFile, false, false); - - - is = context.getResources().openRawResource(R.raw.tor); - outFile = new File(installFolder, TOR_ASSET_KEY); - shell.add(new SimpleCommand(COMMAND_RM_FORCE + outFile.getAbsolutePath())).waitForFinish(); - streamToFile(is,outFile, false, true); - - is = context.getResources().openRawResource(R.raw.polipo); - outFile = new File(installFolder, POLIPO_ASSET_KEY); - shell.add(new SimpleCommand(COMMAND_RM_FORCE + outFile.getAbsolutePath())).waitForFinish(); - streamToFile(is,outFile, false, true); - - is = context.getResources().openRawResource(R.raw.obfsclient); - outFile = new File(installFolder, OBFSCLIENT_ASSET_KEY); - shell.add(new SimpleCommand(COMMAND_RM_FORCE + outFile.getAbsolutePath())).waitForFinish(); - streamToFile(is,outFile, false, true); - - is = context.getResources().openRawResource(R.raw.xtables); - outFile = new File(installFolder, IPTABLES_ASSET_KEY); - shell.add(new SimpleCommand(COMMAND_RM_FORCE + outFile.getAbsolutePath())).waitForFinish(); - streamToFile(is,outFile, false, true); + is = context.getResources().openRawResource(R.raw.torrc); + outFile = new File(installFolder, TORRC_ASSET_KEY); + shell.add(new SimpleCommand(COMMAND_RM_FORCE + outFile.getAbsolutePath())).waitForFinish(); + streamToFile(is,outFile, false, false); + + is = context.getResources().openRawResource(R.raw.torpolipo); + outFile = new File(installFolder, POLIPOCONFIG_ASSET_KEY); + shell.add(new SimpleCommand(COMMAND_RM_FORCE + outFile.getAbsolutePath())).waitForFinish(); + streamToFile(is,outFile, false, false); + + + is = context.getResources().openRawResource(R.raw.tor); + outFile = new File(installFolder, TOR_ASSET_KEY); + shell.add(new SimpleCommand(COMMAND_RM_FORCE + outFile.getAbsolutePath())).waitForFinish(); + streamToFile(is,outFile, false, true); + + is = context.getResources().openRawResource(R.raw.polipo); + outFile = new File(installFolder, POLIPO_ASSET_KEY); + shell.add(new SimpleCommand(COMMAND_RM_FORCE + outFile.getAbsolutePath())).waitForFinish(); + streamToFile(is,outFile, false, true); + + is = context.getResources().openRawResource(R.raw.obfsclient); + outFile = new File(installFolder, OBFSCLIENT_ASSET_KEY); + shell.add(new SimpleCommand(COMMAND_RM_FORCE + outFile.getAbsolutePath())).waitForFinish(); + streamToFile(is,outFile, false, true); + + is = context.getResources().openRawResource(R.raw.xtables); + outFile = new File(installFolder, IPTABLES_ASSET_KEY); + shell.add(new SimpleCommand(COMMAND_RM_FORCE + outFile.getAbsolutePath())).waitForFinish(); + streamToFile(is,outFile, false, true); +
- - return true; - } - - public boolean updateTorConfigCustom (File fileTorRcCustom, String extraLines) throws IOException, FileNotFoundException, TimeoutException - { - + return true; + } + + public boolean updateTorConfigCustom (File fileTorRcCustom, String extraLines) throws IOException, FileNotFoundException, TimeoutException + { +
- StringBufferInputStream sbis = new StringBufferInputStream(extraLines + '\n'); - streamToFile(sbis,fileTorRcCustom,false,false); - - return true; - } - - public boolean updatePolipoConfig (File filePolipo, String extraLines) throws IOException, FileNotFoundException, TimeoutException - { - - InputStream is; + StringBufferInputStream sbis = new StringBufferInputStream(extraLines + '\n'); + streamToFile(sbis,fileTorRcCustom,false,false); + + return true; + } + + public boolean updatePolipoConfig (File filePolipo, String extraLines) throws IOException, FileNotFoundException, TimeoutException + { + + InputStream is;
Shell shell = Shell.startShell(new ArrayList<String>(),installFolder.getAbsolutePath());
- is = context.getResources().openRawResource(R.raw.torpolipo); - shell.add(new SimpleCommand(COMMAND_RM_FORCE + filePolipo.getAbsolutePath())).waitForFinish(); - streamToFile(is,filePolipo, false, false); + is = context.getResources().openRawResource(R.raw.torpolipo); + shell.add(new SimpleCommand(COMMAND_RM_FORCE + filePolipo.getAbsolutePath())).waitForFinish(); + streamToFile(is,filePolipo, false, false);
- if (extraLines != null && extraLines.length() > 0) - { - StringBufferInputStream sbis = new StringBufferInputStream('\n' + extraLines + '\n'); - streamToFile(sbis,filePolipo,true,false); - } - - shell.close(); - - return true; - } - - public boolean installPolipoConf () throws IOException, FileNotFoundException, TimeoutException - { - - InputStream is; + if (extraLines != null && extraLines.length() > 0) + { + StringBufferInputStream sbis = new StringBufferInputStream('\n' + extraLines + '\n'); + streamToFile(sbis,filePolipo,true,false); + } + + shell.close(); + + return true; + } + + public boolean installPolipoConf () throws IOException, FileNotFoundException, TimeoutException + { + + InputStream is; File outFile;
Shell shell = Shell.startShell(new ArrayList<String>(),installFolder.getAbsolutePath());
is = context.getResources().openRawResource(R.raw.torpolipo); - outFile = new File(installFolder, POLIPOCONFIG_ASSET_KEY); - shell.add(new SimpleCommand(COMMAND_RM_FORCE + outFile.getAbsolutePath())).waitForFinish(); - streamToFile(is,outFile, false, false); - - return true; - } - - /* - * Extract the Tor binary from the APK file using ZIP - */ - - public boolean installGeoIP () throws IOException, FileNotFoundException - { - - InputStream is; + outFile = new File(installFolder, POLIPOCONFIG_ASSET_KEY); + shell.add(new SimpleCommand(COMMAND_RM_FORCE + outFile.getAbsolutePath())).waitForFinish(); + streamToFile(is,outFile, false, false); + + return true; + } + + /* + * Extract the Tor binary from the APK file using ZIP + */ + + public boolean installGeoIP () throws IOException, FileNotFoundException + { + + InputStream is; File outFile;
- is = context.getResources().openRawResource(R.raw.geoip); - outFile = new File(installFolder, GEOIP_ASSET_KEY); - streamToFile(is, outFile, false, true); - - is = context.getResources().openRawResource(R.raw.geoip6); - outFile = new File(installFolder, GEOIP6_ASSET_KEY); - streamToFile(is, outFile, false, true); - - return true; - } - - /* - private static void copyAssetFile(Context ctx, String asset, File file) throws IOException, InterruptedException - { - - DataOutputStream out = new DataOutputStream(new FileOutputStream(file)); - InputStream is = new GZIPInputStream(ctx.getAssets().open(asset)); - - byte buf[] = new byte[8172]; - int len; - while ((len = is.read(buf)) > 0) { - out.write(buf, 0, len); - } - out.close(); - is.close(); - }*/ - - /* - * Write the inputstream contents to the file - */ + is = context.getResources().openRawResource(R.raw.geoip); + outFile = new File(installFolder, GEOIP_ASSET_KEY); + streamToFile(is, outFile, false, true); + + is = context.getResources().openRawResource(R.raw.geoip6); + outFile = new File(installFolder, GEOIP6_ASSET_KEY); + streamToFile(is, outFile, false, true); + + return true; + } + + /* + private static void copyAssetFile(Context ctx, String asset, File file) throws IOException, InterruptedException + { + + DataOutputStream out = new DataOutputStream(new FileOutputStream(file)); + InputStream is = new GZIPInputStream(ctx.getAssets().open(asset)); + + byte buf[] = new byte[8172]; + int len; + while ((len = is.read(buf)) > 0) { + out.write(buf, 0, len); + } + out.close(); + is.close(); + }*/ + + /* + * Write the inputstream contents to the file + */ public static boolean streamToFile(InputStream stm, File outFile, boolean append, boolean zip) throws IOException
{ @@ -204,17 +204,17 @@ public class TorResourceInstaller implements TorServiceConstants {
int bytecount;
- OutputStream stmOut = new FileOutputStream(outFile.getAbsolutePath(), append); - ZipInputStream zis = null; - - if (zip) - { - zis = new ZipInputStream(stm); - ZipEntry ze = zis.getNextEntry(); - stm = zis; - - } - + OutputStream stmOut = new FileOutputStream(outFile.getAbsolutePath(), append); + ZipInputStream zis = null; + + if (zip) + { + zis = new ZipInputStream(stm); + ZipEntry ze = zis.getNextEntry(); + stm = zis; + + } + while ((bytecount = stm.read(buffer)) > 0) {
@@ -226,97 +226,97 @@ public class TorResourceInstaller implements TorServiceConstants { stm.close();
if (zis != null) - zis.close(); + zis.close();
return true;
} - + //copy the file from inputstream to File output - alternative impl - public static void copyFile (InputStream is, File outputFile) - { - - try { - outputFile.createNewFile(); - DataOutputStream out = new DataOutputStream(new FileOutputStream(outputFile)); - DataInputStream in = new DataInputStream(is); - - int b = -1; - byte[] data = new byte[1024]; - - while ((b = in.read(data)) != -1) { - out.write(data); - } - - if (b == -1); //rejoice - - // - out.flush(); - out.close(); - in.close(); - // chmod? - - - - } catch (IOException ex) { - Log.e(TorConstants.TAG, "error copying binary", ex); - } + public static void copyFile (InputStream is, File outputFile) + { + + try { + outputFile.createNewFile(); + DataOutputStream out = new DataOutputStream(new FileOutputStream(outputFile)); + DataInputStream in = new DataInputStream(is); + + int b = -1; + byte[] data = new byte[1024]; + + while ((b = in.read(data)) != -1) { + out.write(data); + } + + if (b == -1); //rejoice + + // + out.flush(); + out.close(); + in.close(); + // chmod? + + + + } catch (IOException ex) { + Log.e(TorConstants.TAG, "error copying binary", ex); + }
- } - - + } + +
- /** - * Copies a raw resource file, given its ID to the given location - * @param ctx context - * @param resid resource id - * @param file destination file - * @param mode file permissions (E.g.: "755") - * @throws IOException on error - * @throws InterruptedException when interrupted - */ - public static void copyRawFile(Context ctx, int resid, File file, String mode, boolean isZipd) throws IOException, InterruptedException - { - final String abspath = file.getAbsolutePath(); - // Write the iptables binary - final FileOutputStream out = new FileOutputStream(file); - InputStream is = ctx.getResources().openRawResource(resid); - - if (isZipd) - { - ZipInputStream zis = new ZipInputStream(is); - ZipEntry ze = zis.getNextEntry(); - is = zis; - } - - byte buf[] = new byte[1024]; - int len; - while ((len = is.read(buf)) > 0) { - out.write(buf, 0, len); - } - out.close(); - is.close(); - // Change the permissions - Runtime.getRuntime().exec("chmod "+mode+" "+abspath).waitFor(); - } /** - * Asserts that the binary files are installed in the bin directory. - * @param ctx context + * Copies a raw resource file, given its ID to the given location + * @param ctx context + * @param resid resource id + * @param file destination file + * @param mode file permissions (E.g.: "755") + * @throws IOException on error + * @throws InterruptedException when interrupted + */ + public static void copyRawFile(Context ctx, int resid, File file, String mode, boolean isZipd) throws IOException, InterruptedException + { + final String abspath = file.getAbsolutePath(); + // Write the iptables binary + final FileOutputStream out = new FileOutputStream(file); + InputStream is = ctx.getResources().openRawResource(resid); + + if (isZipd) + { + ZipInputStream zis = new ZipInputStream(is); + ZipEntry ze = zis.getNextEntry(); + is = zis; + } + + byte buf[] = new byte[1024]; + int len; + while ((len = is.read(buf)) > 0) { + out.write(buf, 0, len); + } + out.close(); + is.close(); + // Change the permissions + Runtime.getRuntime().exec("chmod "+mode+" "+abspath).waitFor(); + } + /** + * Asserts that the binary files are installed in the bin directory. + * @param ctx context * @param showErrors indicates if errors should be alerted - * @return false if the binary files could not be installed - */ - /* - public static boolean assertIpTablesBinaries(Context ctx, boolean showErrors) throws Exception { - boolean changed = false; - - // Check iptables_g1 - File file = new File(ctx.getDir("bin",0), "iptables"); - copyRawFile(ctx, R.raw.iptables, file, CHMOD_EXEC, false); - - return true; - }*/ - + * @return false if the binary files could not be installed + */ + /* + public static boolean assertIpTablesBinaries(Context ctx, boolean showErrors) throws Exception { + boolean changed = false; + + // Check iptables_g1 + File file = new File(ctx.getDir("bin",0), "iptables"); + copyRawFile(ctx, R.raw.iptables, file, CHMOD_EXEC, false); + + return true; + }*/ +
} diff --git a/src/org/torproject/android/service/TorService.java b/src/org/torproject/android/service/TorService.java index 63bf0d5..251137f 100644 --- a/src/org/torproject/android/service/TorService.java +++ b/src/org/torproject/android/service/TorService.java @@ -45,10 +45,10 @@ import net.freehaven.tor.control.TorControlConnection;
import org.json.JSONArray; import org.json.JSONObject; +import org.sandroproxy.ony.R; import org.sufficientlysecure.rootcommands.Shell; import org.sufficientlysecure.rootcommands.command.SimpleCommand; import org.torproject.android.Orbot; -import org.torproject.android.R; import org.torproject.android.TorConstants; import org.torproject.android.Utils; import org.torproject.android.settings.AppManager; @@ -82,30 +82,30 @@ import android.widget.RemoteViews;
public class TorService extends Service implements TorServiceConstants, TorConstants, EventHandler { - - public static boolean ENABLE_DEBUG_LOG = false; - - private int mCurrentStatus = STATUS_OFF; - - private final static int CONTROL_SOCKET_TIMEOUT = 0; - - private TorControlConnection conn = null; - private Socket torConnSocket = null; - private int mLastProcessId = -1; - - - private int mPortHTTP = 8118; - private int mPortSOCKS = 9050; - - - private static final int NOTIFY_ID = 1; - private static final int TRANSPROXY_NOTIFY_ID = 2; - private static final int ERROR_NOTIFY_ID = 3; - private static final int HS_NOTIFY_ID = 4; - - private boolean prefPersistNotifications = true; - - private static final int MAX_START_TRIES = 3; + + public static boolean ENABLE_DEBUG_LOG = false; + + private int mCurrentStatus = STATUS_OFF; + + private final static int CONTROL_SOCKET_TIMEOUT = 0; + + private TorControlConnection conn = null; + private Socket torConnSocket = null; + private int mLastProcessId = -1; + + + private int mPortHTTP = 8118; + private int mPortSOCKS = 9050; + + + private static final int NOTIFY_ID = 1; + private static final int TRANSPROXY_NOTIFY_ID = 2; + private static final int ERROR_NOTIFY_ID = 3; + private static final int HS_NOTIFY_ID = 4; + + private boolean prefPersistNotifications = true; + + private static final int MAX_START_TRIES = 3;
private ArrayList<String> configBuffer = null; private ArrayList<String> resetBuffer = null; @@ -124,18 +124,18 @@ public class TorService extends Service implements TorServiceConstants, TorConst
private TorTransProxy mTransProxy;
- private long mTotalTrafficWritten = 0; - private long mTotalTrafficRead = 0; - private boolean mConnectivity = true; + private long mTotalTrafficWritten = 0; + private long mTotalTrafficRead = 0; + private boolean mConnectivity = true;
- private long lastRead = -1; - private long lastWritten = -1; - - private NotificationManager mNotificationManager = null; - private Builder mNotifyBuilder; - private Notification mNotification; - private boolean mShowExpandedNotifications = false; - private boolean mNotificationShowing = false; + private long lastRead = -1; + private long lastWritten = -1; + + private NotificationManager mNotificationManager = null; + private Builder mNotifyBuilder; + private Notification mNotification; + private boolean mShowExpandedNotifications = false; + private boolean mNotificationShowing = false;
private boolean mHasRoot = false; private boolean mEnableTransparentProxy = false; @@ -147,1746 +147,1692 @@ public class TorService extends Service implements TorServiceConstants, TorConst
public void debug(String msg) { - if (ENABLE_DEBUG_LOG) - { - Log.d(TAG,msg); - sendCallbackLogMessage(msg); + if (ENABLE_DEBUG_LOG) + { + Log.d(TAG,msg); + sendCallbackLogMessage(msg);
- } + } }
public void logException(String msg, Exception e) { - if (ENABLE_DEBUG_LOG) - { - Log.e(TAG,msg,e); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - e.printStackTrace(new PrintStream(baos)); - - sendCallbackLogMessage(msg + '\n'+ new String(baos.toByteArray())); - - } - else - sendCallbackLogMessage(msg); - + if (ENABLE_DEBUG_LOG) + { + Log.e(TAG,msg,e); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(baos)); + + sendCallbackLogMessage(msg + '\n'+ new String(baos.toByteArray())); + + } + else + sendCallbackLogMessage(msg); +
}
private boolean findExistingProc () { - if (fileTor != null) - { - try - { - - mLastProcessId = initControlConnection(3,true); - - if (mLastProcessId != -1 && conn != null) - { - sendCallbackLogMessage (getString(R.string.found_existing_tor_process)); - - mCurrentStatus = STATUS_ON; - sendCallbackStatus(mCurrentStatus); - - return true; - } - - - return false; - } - catch (Exception e) - { - //Log.e(TAG,"error finding proc",e); - return false; - } - } - else - return false; + if (fileTor != null) + { + try + { + + mLastProcessId = initControlConnection(3,true); + + if (mLastProcessId != -1 && conn != null) + { + sendCallbackLogMessage (getString(R.string.found_existing_tor_process)); + + mCurrentStatus = STATUS_ON; + sendCallbackStatus(mCurrentStatus); + + return true; + } + + + return false; + } + catch (Exception e) + { + //Log.e(TAG,"error finding proc",e); + return false; + } + } + else + return false; }
/* (non-Javadoc) - * @see android.app.Service#onLowMemory() - */ + * @see android.app.Service#onLowMemory() + */ @Override - public void onLowMemory() { - super.onLowMemory(); - - logNotice( "Low Memory Warning!"); - - } + public void onLowMemory() { + super.onLowMemory(); + + logNotice( "Low Memory Warning!"); + + }
- public int getTorStatus () + public int getTorStatus () + { + + return mCurrentStatus; + + } + + private void clearNotifications () { - - return mCurrentStatus; - + if (mNotificationManager != null) + mNotificationManager.cancelAll(); + + + hmBuiltNodes.clear(); + mNotificationShowing = false; + } - - private void clearNotifications () - { - if (mNotificationManager != null) - mNotificationManager.cancelAll(); - - - hmBuiltNodes.clear(); - mNotificationShowing = false; - - } - - @SuppressLint("NewApi") - private void showToolbarNotification (String notifyMsg, int notifyType, int icon) - { - - //Reusable code. - Intent intent = new Intent(TorService.this, Orbot.class); - PendingIntent pendIntent = PendingIntent.getActivity(TorService.this, 0, intent, 0); + + @SuppressLint("NewApi") + private void showToolbarNotification (String notifyMsg, int notifyType, int icon) + { + + //Reusable code. + Intent intent = new Intent(TorService.this, Orbot.class); + PendingIntent pendIntent = PendingIntent.getActivity(TorService.this, 0, intent, 0);
- if (mNotifyBuilder == null) - { - - mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - - if (mNotifyBuilder == null) - { - mNotifyBuilder = new NotificationCompat.Builder(this) - .setContentTitle(getString(R.string.app_name)) - .setSmallIcon(R.drawable.ic_stat_tor); - - mNotifyBuilder.setContentIntent(pendIntent); - } - - } - - mNotifyBuilder.setContentText(notifyMsg); - mNotifyBuilder.setSmallIcon(icon); - - if (notifyType != NOTIFY_ID) - { - mNotifyBuilder.setTicker(notifyMsg); - // mNotifyBuilder.setLights(Color.GREEN, 1000, 1000); - } - else - { - mNotifyBuilder.setTicker(null); - } - - mNotifyBuilder.setOngoing(prefPersistNotifications); - - mNotification = mNotifyBuilder.build(); - - if (Build.VERSION.SDK_INT >= 16 && mShowExpandedNotifications) { - - - // Create remote view that needs to be set as bigContentView for the notification. - RemoteViews expandedView = new RemoteViews(this.getPackageName(), - R.layout.layout_notification_expanded); - - StringBuffer sbInfo = new StringBuffer(); - - - if (notifyType == NOTIFY_ID) - expandedView.setTextViewText(R.id.text, notifyMsg); - else - { - expandedView.setTextViewText(R.id.info, notifyMsg); - - } - - if (hmBuiltNodes.size() > 0) - { - //sbInfo.append(getString(R.string.your_tor_public_ips_) + '\n'); - - Set<String> itBuiltNodes = hmBuiltNodes.keySet(); - for (String key : itBuiltNodes) - { - Node node = hmBuiltNodes.get(key); - - if (node.ipAddress != null) - { - sbInfo.append(node.ipAddress); - - if (node.country != null) - sbInfo.append(' ').append(node.country); - - if (node.organization != null) - sbInfo.append(" (").append(node.organization).append(')'); - - sbInfo.append('\n'); - } - - } - - expandedView.setTextViewText(R.id.text2, sbInfo.toString()); - } - - expandedView.setTextViewText(R.id.title, getString(R.string.app_name)); - - expandedView.setImageViewResource(R.id.icon, icon); - mNotification.bigContentView = expandedView; - } - - if (prefPersistNotifications && (!mNotificationShowing)) - { - startForeground(NOTIFY_ID, mNotification); - logNotice("Set background service to FOREGROUND"); - } - else - { - mNotificationManager.notify(NOTIFY_ID, mNotification); - } - - mNotificationShowing = true; - } - - - /* (non-Javadoc) - * @see android.app.Service#onStart(android.content.Intent, int) - */ - public int onStartCommand(Intent intent, int flags, int startId) { - - new Thread (new TorStarter(intent)).start(); - - return START_REDELIVER_INTENT; - - } - - private class TorStarter implements Runnable - { - Intent mIntent; - - public TorStarter (Intent intent) - { - mIntent = intent; - } - - public void run () - { - try - { - - //if this is a start on boot launch turn tor on - if (mIntent != null) - { - String action = mIntent.getAction(); - - if (action!=null) - { - if(action.equals(Intent.ACTION_BOOT_COMPLETED)||action.equals(CMD_START)) - { - setTorProfile(STATUS_ON); - } - else if (action.equals(CMD_STOP)) - { - setTorProfile(STATUS_OFF); - } - else if (action.equals(CMD_INIT)) - { - initialize(); - sendCallbackStatus(mCurrentStatus); - } - else if (action.equals(CMD_NEWNYM)) - { - newIdentity(); - } - else if (action.equals(CMD_FLUSH)) - { - flushTransparentProxyRules(); - } - else if (action.equals(CMD_UPDATE)) - { - processSettings(); - } - else if (action.equals(CMD_VPN)) - { - startVpnService(); - } - } - } - else - { - Log.d(TAG, "Got null onStartCommand() intent"); - } - - } - catch (Exception e) - { - Log.e(TAG,"error onBind",e); - } - } - } - - @Override - public void onTaskRemoved(Intent rootIntent) { - Log.d(TAG,"task removed"); - - Intent intent = new Intent( this, DummyActivity.class ); - intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK ); - startActivity( intent ); - } + if (mNotifyBuilder == null) + { + + mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + + if (mNotifyBuilder == null) + { + mNotifyBuilder = new NotificationCompat.Builder(this) + .setContentTitle(getString(R.string.app_name)) + .setSmallIcon(R.drawable.ic_stat_tor); + + mNotifyBuilder.setContentIntent(pendIntent); + } + + } + + mNotifyBuilder.setContentText(notifyMsg); + mNotifyBuilder.setSmallIcon(icon); + + if (notifyType != NOTIFY_ID) + { + mNotifyBuilder.setTicker(notifyMsg); + // mNotifyBuilder.setLights(Color.GREEN, 1000, 1000); + } + else + { + mNotifyBuilder.setTicker(null); + } + + mNotifyBuilder.setOngoing(prefPersistNotifications); + + mNotification = mNotifyBuilder.build(); + + if (Build.VERSION.SDK_INT >= 16 && mShowExpandedNotifications) { + + + // Create remote view that needs to be set as bigContentView for the notification. + RemoteViews expandedView = new RemoteViews(this.getPackageName(), + R.layout.layout_notification_expanded); + + StringBuffer sbInfo = new StringBuffer(); + + + if (notifyType == NOTIFY_ID) + expandedView.setTextViewText(R.id.text, notifyMsg); + else + { + expandedView.setTextViewText(R.id.info, notifyMsg); + + } + + if (hmBuiltNodes.size() > 0) + { + //sbInfo.append(getString(R.string.your_tor_public_ips_) + '\n'); + + Set<String> itBuiltNodes = hmBuiltNodes.keySet(); + for (String key : itBuiltNodes) + { + Node node = hmBuiltNodes.get(key); + + if (node.ipAddress != null) + { + sbInfo.append(node.ipAddress); + + if (node.country != null) + sbInfo.append(' ').append(node.country); + + if (node.organization != null) + sbInfo.append(" (").append(node.organization).append(')'); + + sbInfo.append('\n'); + } + + } + + expandedView.setTextViewText(R.id.text2, sbInfo.toString()); + } + + expandedView.setTextViewText(R.id.title, getString(R.string.app_name)); + + expandedView.setImageViewResource(R.id.icon, icon); + mNotification.bigContentView = expandedView; + } + + if (prefPersistNotifications && (!mNotificationShowing)) + { + startForeground(NOTIFY_ID, mNotification); + logNotice("Set background service to FOREGROUND"); + } + else + { + mNotificationManager.notify(NOTIFY_ID, mNotification); + } + + mNotificationShowing = true; + } + + + /* (non-Javadoc) + * @see android.app.Service#onStart(android.content.Intent, int) + */ + public int onStartCommand(Intent intent, int flags, int startId) { + + new Thread (new TorStarter(intent)).start(); + + return START_REDELIVER_INTENT;
+ } + + private class TorStarter implements Runnable + { + Intent mIntent; + + public TorStarter (Intent intent) + { + mIntent = intent; + } + + public void run (){ + try{ + //if this is a start on boot launch turn tor on + if (mIntent != null){ + String action = mIntent.getAction(); + + if (action!=null){ + if(action.equals(Intent.ACTION_BOOT_COMPLETED)||action.equals(CMD_START)){ + setTorProfile(STATUS_ON); + }else if (action.equals(CMD_STOP)){ + setTorProfile(STATUS_OFF); + }else if (action.equals(CMD_INIT)){ + initialize(); + sendCallbackStatus(mCurrentStatus); + }else if (action.equals(CMD_NEWNYM)){ + newIdentity(); + }else if (action.equals(CMD_FLUSH)){ + flushTransparentProxyRules(); + }else if (action.equals(CMD_UPDATE)){ + processSettings(); + }else if (action.equals(CMD_VPN)){ + startVpnService(); + } + } + }else{ + Log.d(TAG, "Got null onStartCommand() intent"); + } + + }catch (Exception e){ + Log.e(TAG,"error onBind",e); + } + } + } + @Override - public boolean stopService(Intent name) { - - logNotice("TorService is being stopped: " + name); + public void onTaskRemoved(Intent rootIntent){ + Log.d(TAG,"task removed"); + Intent intent = new Intent( this, DummyActivity.class ); + intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK ); + startActivity( intent ); + }
- return super.stopService(name); - - } + @Override + public boolean stopService(Intent name) { + logNotice("TorService is being stopped: " + name); + return super.stopService(name); + }
- @Override + @Override public void onDestroy () { - String msg = ("TorService is being DESTROYED... shutting down!"); - - Log.d(TAG, msg); - sendCallbackLogMessage(msg); - - unregisterReceiver(mNetworkStateReceiver); - + String msg = ("TorService is being DESTROYED... shutting down!"); + Log.d(TAG, msg); + sendCallbackLogMessage(msg); + unregisterReceiver(mNetworkStateReceiver); clearNotifications (); - - super.onDestroy(); - + super.onDestroy(); }
private void stopTor () { - - try - { - Log.d(TAG,"Tor is stopping NOW"); - - shutdownTorProcess (); - - //stop the foreground priority and make sure to remove the persistant notification - stopForeground(true); - - mCurrentStatus = STATUS_OFF; - sendCallbackStatus(mCurrentStatus); - - if (mHasRoot && mEnableTransparentProxy) - disableTransparentProxy(Shell.startRootShell()); - - clearNotifications(); - - sendCallbackLogMessage(getString(R.string.status_disabled)); - - } - catch (Exception e) - { - Log.d(TAG, "An error occured stopping Tor",e); - logNotice("An error occured stopping Tor: " + e.getMessage()); - sendCallbackLogMessage(getString(R.string.something_bad_happened)); - - } + + try + { + Log.d(TAG,"Tor is stopping NOW"); + + shutdownTorProcess (); + + //stop the foreground priority and make sure to remove the persistant notification + stopForeground(true); + + mCurrentStatus = STATUS_OFF; + sendCallbackStatus(mCurrentStatus); + + if (mHasRoot && mEnableTransparentProxy) + disableTransparentProxy(Shell.startRootShell()); + + clearNotifications(); + + sendCallbackLogMessage(getString(R.string.status_disabled)); + + } + catch (Exception e) + { + Log.d(TAG, "An error occured stopping Tor",e); + logNotice("An error occured stopping Tor: " + e.getMessage()); + sendCallbackLogMessage(getString(R.string.something_bad_happened)); + + } }
- private String getHiddenServiceHostname () - { + private String getHiddenServiceHostname () + {
- SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); - + SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); + boolean enableHiddenServices = prefs.getBoolean("pref_hs_enable", false);
StringBuffer result = new StringBuffer(); - + if (enableHiddenServices) { - String hsPorts = prefs.getString("pref_hs_ports",""); - - StringTokenizer st = new StringTokenizer (hsPorts,","); - String hsPortConfig = null; - - while (st.hasMoreTokens()) - { - - int hsPort = Integer.parseInt(st.nextToken().split(" ")[0]);; - - File fileDir = new File(appCacheHome, "hs" + hsPort); - File file = new File(fileDir, "hostname"); - - - if (file.exists()) - { - try { - String onionHostname = Utils.readString(new FileInputStream(file)).trim(); - - if (result.length() > 0) - result.append(","); - - result.append(onionHostname); - - - } catch (FileNotFoundException e) { - logException("unable to read onion hostname file",e); - showToolbarNotification(getString(R.string.unable_to_read_hidden_service_name), HS_NOTIFY_ID, R.drawable.ic_stat_notifyerr); - return null; - } - } - else - { - showToolbarNotification(getString(R.string.unable_to_read_hidden_service_name), HS_NOTIFY_ID, R.drawable.ic_stat_notifyerr); - return null; - - } - } - - if (result.length() > 0) - { - String onionHostname = result.toString(); - - showToolbarNotification(getString(R.string.hidden_service_on) + ' ' + onionHostname, HS_NOTIFY_ID, R.drawable.ic_stat_tor); - Editor pEdit = prefs.edit(); - pEdit.putString("pref_hs_hostname",onionHostname); - pEdit.commit(); - - return onionHostname; - } - + String hsPorts = prefs.getString("pref_hs_ports",""); + + StringTokenizer st = new StringTokenizer (hsPorts,","); + String hsPortConfig = null; + + while (st.hasMoreTokens()) + { + + int hsPort = Integer.parseInt(st.nextToken().split(" ")[0]);; + + File fileDir = new File(appCacheHome, "hs" + hsPort); + File file = new File(fileDir, "hostname"); + + + if (file.exists()) + { + try { + String onionHostname = Utils.readString(new FileInputStream(file)).trim(); + + if (result.length() > 0) + result.append(","); + + result.append(onionHostname); + + + } catch (FileNotFoundException e) { + logException("unable to read onion hostname file",e); + showToolbarNotification(getString(R.string.unable_to_read_hidden_service_name), HS_NOTIFY_ID, R.drawable.ic_stat_notifyerr); + return null; + } + } + else + { + showToolbarNotification(getString(R.string.unable_to_read_hidden_service_name), HS_NOTIFY_ID, R.drawable.ic_stat_notifyerr); + return null; + + } + } + + if (result.length() > 0) + { + String onionHostname = result.toString(); + + showToolbarNotification(getString(R.string.hidden_service_on) + ' ' + onionHostname, HS_NOTIFY_ID, R.drawable.ic_stat_tor); + Editor pEdit = prefs.edit(); + pEdit.putString("pref_hs_hostname",onionHostname); + pEdit.commit(); + + return onionHostname; + } + }
return null; - } - - + } + + private void shutdownTorProcess () throws Exception {
- if (conn != null) - { - - logNotice("Using control port to shutdown Tor"); - - - try { - logNotice("sending HALT signal to Tor process"); - conn.shutdownTor("HALT"); - - } catch (Exception e) { - Log.d(TAG,"error shutting down Tor via connection",e); - } - - conn = null; - } - else - killProcess(fileTor); - - killProcess(filePolipo); - // killProcess(fileObfsclient); - + if (conn != null) + { + + logNotice("Using control port to shutdown Tor"); + + + try { + logNotice("sending HALT signal to Tor process"); + conn.shutdownTor("HALT"); + + } catch (Exception e) { + Log.d(TAG,"error shutting down Tor via connection",e); + } + + conn = null; + } + else + killProcess(fileTor); + + killProcess(filePolipo); + // killProcess(fileObfsclient); + }
private void killProcess (File fileProcBin) throws IOException { - int procId = -1; - Shell shell = Shell.startShell(); - - while ((procId = TorServiceUtils.findProcessId(fileProcBin.getCanonicalPath())) != -1) - { - - logNotice("Found " + fileProcBin.getName() + " PID=" + procId + " - killing now..."); - - SimpleCommand killCommand = new SimpleCommand("toolbox kill " + procId); - shell.add(killCommand); - killCommand = new SimpleCommand("kill " + procId); - shell.add(killCommand); - } - - shell.close(); + int procId = -1; + Shell shell = Shell.startShell(); + + while ((procId = TorServiceUtils.findProcessId(fileProcBin.getCanonicalPath())) != -1) + { + + logNotice("Found " + fileProcBin.getName() + " PID=" + procId + " - killing now..."); + + SimpleCommand killCommand = new SimpleCommand("toolbox kill " + procId); + shell.add(killCommand); + killCommand = new SimpleCommand("kill " + procId); + shell.add(killCommand); + } + + shell.close(); }
private void logNotice (String msg) { - if (msg != null && msg.trim().length() > 0) - { - if (ENABLE_DEBUG_LOG) - Log.d(TAG, msg); - - sendCallbackLogMessage(msg); - } + if (msg != null && msg.trim().length() > 0) + { + if (ENABLE_DEBUG_LOG) + Log.d(TAG, msg); + + sendCallbackLogMessage(msg); + } }
@Override - public void onCreate() { - super.onCreate(); - initialize(); + public void onCreate() { + super.onCreate(); + initialize(); + } + + private void initialize() + { + try + { + + if (mNotificationManager == null) + { + + IntentFilter mNetworkStateFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); + registerReceiver(mNetworkStateReceiver , mNetworkStateFilter); + + mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + + } + + + initBinariesAndDirectories(); + updateSettings(); + + new Thread(new Runnable () + { + public void run () + { + try + { + findExistingProc (); + } + catch (Exception e) + { + Log.e(TAG,"error onBind",e); + logNotice("error finding exiting process: " + e.toString()); + } + + } + }).start(); + + } + catch (Exception e) + { + //what error here + Log.e(TAG, "Error installing Orbot binaries",e); + logNotice("There was an error installing Orbot binaries"); + } + + + } + + private void initBinariesAndDirectories () throws Exception + { + + if (appBinHome == null) + appBinHome = getDir(DIRECTORY_TOR_BINARY,Application.MODE_PRIVATE); + + if (appCacheHome == null) + appCacheHome = getDir(DIRECTORY_TOR_DATA,Application.MODE_PRIVATE); + + fileTor= new File(appBinHome, TOR_ASSET_KEY); + + filePolipo = new File(appBinHome, POLIPO_ASSET_KEY); + + fileObfsclient = new File(appBinHome, OBFSCLIENT_ASSET_KEY); + + fileTorRc = new File(appBinHome, TORRC_ASSET_KEY); + + fileXtables = new File(appBinHome, IPTABLES_ASSET_KEY); + + SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); + String version = prefs.getString(PREF_BINARY_TOR_VERSION_INSTALLED,null); + + logNotice("checking binary version: " + version); + + TorResourceInstaller installer = new TorResourceInstaller(this, appBinHome); + + if (version == null || (!version.equals(BINARY_TOR_VERSION)) || (!fileTor.exists())) + { + logNotice("upgrading binaries to latest version: " + BINARY_TOR_VERSION); + + boolean success = installer.installResources(); + + if (success) + prefs.edit().putString(PREF_BINARY_TOR_VERSION_INSTALLED,BINARY_TOR_VERSION).commit(); + } + + updateTorConfigFile (); + + + } + + private boolean updateTorConfigFile () throws FileNotFoundException, IOException, TimeoutException + { + SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); + + TorResourceInstaller installer = new TorResourceInstaller(this, appBinHome); + + StringBuffer extraLines = new StringBuffer(); + + String TORRC_CONTROLPORT_FILE_KEY = "ControlPortWriteToFile"; + fileControlPort = new File(appBinHome,"control.txt"); + extraLines.append(TORRC_CONTROLPORT_FILE_KEY).append(' ').append(fileControlPort.getCanonicalPath()).append('\n'); + + if (mTransProxyTethering) + { + extraLines.append("TransListenAddress 0.0.0.0").append('\n'); + extraLines.append("DNSListenAddress 0.0.0.0").append('\n'); + + } + + extraLines.append("RunAsDaemon 1").append('\n'); + extraLines.append("AvoidDiskWrites 1").append('\n'); + + extraLines.append("SOCKSPort ").append("auto").append('\n'); + extraLines.append("SafeSocks 0").append('\n'); + extraLines.append("TestSocks 0").append('\n'); + extraLines.append("WarnUnsafeSocks 1").append('\n'); + + extraLines.append("TransPort ").append("auto").append('\n'); + extraLines.append("DNSPort ").append("auto").append('\n'); + extraLines.append("VirtualAddrNetwork 10.192.0.0/10").append('\n'); + extraLines.append("AutomapHostsOnResolve 1").append('\n'); + + + extraLines.append("CircuitStreamTimeout 60").append('\n'); + + + extraLines.append(prefs.getString("pref_custom_torrc", "")); + + logNotice("updating torrc custom configuration..."); + + debug("torrc.custom=" + extraLines.toString()); + + File fileTorRcCustom = new File(fileTorRc.getAbsolutePath() + ".custom"); + boolean success = installer.updateTorConfigCustom(fileTorRcCustom, extraLines.toString()); + + if (success) + { + logNotice ("success."); + } + + return success; + } + + private boolean enableBinExec (File fileBin) throws Exception + { + + logNotice(fileBin.getName() + ": PRE: Is binary exec? " + fileBin.canExecute()); + + if (!fileBin.canExecute()) + { + logNotice("(re)Setting permission on binary: " + fileBin.getCanonicalPath()); + + Shell shell = Shell.startShell(); + shell.add(new SimpleCommand("chmod " + CHMOD_EXE_VALUE + ' ' + fileBin.getCanonicalPath())).waitForFinish(); + + File fileTest = new File(fileBin.getCanonicalPath()); + logNotice(fileTest.getName() + ": POST: Is binary exec? " + fileTest.canExecute()); + + shell.close(); + } + + return fileBin.canExecute(); + } + + + private void updateSettings () throws TimeoutException, IOException + { + + SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); + + mHasRoot = prefs.getBoolean(PREF_HAS_ROOT,false); + + mEnableTransparentProxy = prefs.getBoolean("pref_transparent", false); + mTransProxyAll = prefs.getBoolean("pref_transparent_all", false); + mTransProxyTethering = prefs.getBoolean("pref_transparent_tethering", false); + mTransProxyNetworkRefresh = prefs.getBoolean("pref_transproxy_refresh", false); + + mShowExpandedNotifications = prefs.getBoolean("pref_expanded_notifications", false); + + ENABLE_DEBUG_LOG = prefs.getBoolean("pref_enable_logging",false); + Log.i(TAG,"debug logging:" + ENABLE_DEBUG_LOG); + + prefPersistNotifications = prefs.getBoolean(TorConstants.PREF_PERSIST_NOTIFICATIONS, true); + + } + + private void startTor () throws Exception + { + + mCurrentStatus = STATUS_CONNECTING; + sendCallbackStatus(mCurrentStatus); + + if (fileTor == null) + initBinariesAndDirectories(); + + enableBinExec(fileTor); + enableBinExec(filePolipo); + enableBinExec(fileObfsclient); + enableBinExec(fileXtables); + + updateSettings (); + + logNotice(getString(R.string.status_starting_up)); + sendCallbackLogMessage(getString(R.string.status_starting_up)); + + Shell shellUser = Shell.startShell(); + + boolean success = runTorShellCmd(shellUser); + + if (success) + { + if (mPortHTTP != -1) + runPolipoShellCmd(shellUser); + + if (mHasRoot && mEnableTransparentProxy) + { + Shell shellRoot = Shell.startRootShell(); + + disableTransparentProxy(shellRoot); + enableTransparentProxy(shellRoot); + + shellRoot.close(); + } + + getHiddenServiceHostname (); + } + else + { + showToolbarNotification(getString(R.string.unable_to_start_tor), ERROR_NOTIFY_ID, R.drawable.ic_stat_notifyerr); + + } + + shellUser.close(); + } + + private boolean flushTransparentProxyRules () throws Exception + { + + if (mHasRoot) + { + if (mTransProxy == null) + { + mTransProxy = new TorTransProxy(this, fileXtables); + + } + + mTransProxy.flushTransproxyRules(this); + + return true; + } + else + { + return false; + } + } + + /* + * activate means whether to apply the users preferences + * or clear them out + * + * the idea is that if Tor is off then transproxy is off + */ + private boolean enableTransparentProxy (Shell shell) throws Exception + { + + if (mTransProxy == null) + { + mTransProxy = new TorTransProxy(this, fileXtables); + + } + + + SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); + String transProxy = prefs.getString("pref_transport", TorServiceConstants.TOR_TRANSPROXY_PORT_DEFAULT+""); + String dnsPort = prefs.getString("pref_dnsport", TorServiceConstants.TOR_TRANSPROXY_PORT_DEFAULT+""); + + if (transProxy.indexOf(':')!=-1) //we just want the port for this + transProxy = transProxy.split(":")[1]; + + if (dnsPort.indexOf(':')!=-1) //we just want the port for this + dnsPort = dnsPort.split(":")[1]; + + mTransProxy.setTransProxyPort(Integer.parseInt(transProxy)); + mTransProxy.setDNSPort(Integer.parseInt(dnsPort)); + + int code = 0; // Default state is "okay" + + if(mTransProxyAll) + { + + code = mTransProxy.setTransparentProxyingAll(this, true, shell); + } + else + { + ArrayList<TorifiedApp> apps = AppManager.getApps(this, TorServiceUtils.getSharedPrefs(getApplicationContext())); + + code = mTransProxy.setTransparentProxyingByApp(this,apps, true, shell); + } + + debug ("TorTransProxy resp code: " + code); + + if (code == 0) + { + + if (mTransProxyTethering) + { + showToolbarNotification(getString(R.string.transproxy_enabled_for_tethering_), TRANSPROXY_NOTIFY_ID, R.drawable.ic_stat_tor); + + mTransProxy.enableTetheringRules(this, Shell.startRootShell()); + + } + else + { + showToolbarNotification(getString(R.string.transparent_proxying_enabled), TRANSPROXY_NOTIFY_ID, R.drawable.ic_stat_tor); + + } + } + else + { + showToolbarNotification(getString(R.string.warning_error_starting_transparent_proxying_), TRANSPROXY_NOTIFY_ID, R.drawable.ic_stat_tor); + + } + + return true; + } + + /* + * activate means whether to apply the users preferences + * or clear them out + * + * the idea is that if Tor is off then transproxy is off + */ + private boolean disableTransparentProxy (Shell shell) throws Exception + { + + debug ("Transparent Proxying: disabling..."); + + if (mTransProxy == null) + mTransProxy = new TorTransProxy(this, fileXtables); + + mTransProxy.setTransparentProxyingAll(this, false, shell); + ArrayList<TorifiedApp> apps = AppManager.getApps(this, TorServiceUtils.getSharedPrefs(getApplicationContext())); + mTransProxy.setTransparentProxyingByApp(this, apps, false, shell); + + return true; + } + + private boolean runTorShellCmd(Shell shell) throws Exception + { + + String torrcPath = new File(appBinHome, TORRC_ASSET_KEY).getCanonicalPath(); + + updateTorConfigFile(); + + sendCallbackLogMessage(getString(R.string.status_starting_up)); + + String torCmdString = fileTor.getCanonicalPath() + + " DataDirectory " + appCacheHome.getCanonicalPath() + + " --defaults-torrc " + torrcPath + + " -f " + torrcPath + ".custom"; + + debug(torCmdString); + + SimpleCommand shellTorCommand = new SimpleCommand(torCmdString + " --verify-config"); + shell.add(shellTorCommand).waitForFinish(); + + int exitCode = shellTorCommand.getExitCode(); + String output = shellTorCommand.getOutput(); + + if (exitCode != 0 && output != null && output.length() > 0) + { + logNotice("Tor (" + exitCode + "): " + output); + throw new Exception ("Torrc config did not verify"); + + } + + shellTorCommand = new SimpleCommand(torCmdString); + shell.add(shellTorCommand).waitForFinish(); + + exitCode = shellTorCommand.getExitCode(); + output = shellTorCommand.getOutput(); + + + if (exitCode != 0 && output != null && output.length() > 0) + { + logNotice("Tor (" + exitCode + "): " + output); + //throw new Exception ("unable to start"); + return false; + } + + //now try to connect + mLastProcessId = initControlConnection (100,false); + + if (mLastProcessId == -1) + { + logNotice(getString(R.string.couldn_t_start_tor_process_) + "; exit=" + shellTorCommand.getExitCode() + ": " + shellTorCommand.getOutput()); + sendCallbackLogMessage(getString(R.string.couldn_t_start_tor_process_)); + + throw new Exception ("Unable to start Tor"); + } + else + { + + logNotice("Tor started; process id=" + mLastProcessId); + + processSettingsImpl(); + + + } + + return true; + } + + private void updatePolipoConfig () throws FileNotFoundException, IOException + { + + + File file = new File(appBinHome, POLIPOCONFIG_ASSET_KEY); + + Properties props = new Properties(); + + props.load(new FileReader(file)); + + props.put("socksParentProxy", ""localhost:" + mPortSOCKS + """); + props.put("proxyPort",mPortHTTP+""); + + props.store(new FileWriter(file), "updated"); + + } + + + private void runPolipoShellCmd (Shell shell) throws Exception + { + + logNotice( "Starting polipo process"); + + int polipoProcId = TorServiceUtils.findProcessId(filePolipo.getCanonicalPath()); + + StringBuilder log = null; + + int attempts = 0; + + if (polipoProcId == -1) + { + log = new StringBuilder(); + + updatePolipoConfig(); + + String polipoConfigPath = new File(appBinHome, POLIPOCONFIG_ASSET_KEY).getCanonicalPath(); + SimpleCommand cmdPolipo = new SimpleCommand(filePolipo.getCanonicalPath() + " -c " + polipoConfigPath + " &"); + + shell.add(cmdPolipo); + + //wait one second to make sure it has started up + Thread.sleep(1000); + + while ((polipoProcId = TorServiceUtils.findProcessId(filePolipo.getCanonicalPath())) == -1 && attempts < MAX_START_TRIES) + { + logNotice("Couldn't find Polipo process... retrying...\n" + log); + Thread.sleep(3000); + attempts++; + } + + logNotice(log.toString()); + } + + sendCallbackLogMessage(getString(R.string.privoxy_is_running_on_port_) + PORT_HTTP); + + logNotice("Polipo process id=" + polipoProcId); + + } + + private int initControlConnection (int maxTries, boolean isReconnect) throws Exception, RuntimeException + { + int i = 0; + int controlPort = -1; + + int attempt = 0; + + + logNotice( "Waiting for control port..."); + + while (conn == null && attempt++ < maxTries) + { + try + { + + controlPort = getControlPort(); + + if (controlPort != -1) + { + logNotice( "Connecting to control port: " + controlPort); + + torConnSocket = new Socket(IP_LOCALHOST, controlPort); + torConnSocket.setSoTimeout(CONTROL_SOCKET_TIMEOUT); + + conn = new TorControlConnection(torConnSocket); + conn.launchThread(true);//is daemon + + break; + } + + } + catch (Exception ce) + { + conn = null; + // logException( "Error connecting to Tor local control port: " + ce.getMessage(),ce); + + } + + + try { + // logNotice("waiting..."); + Thread.sleep(1000); } + catch (Exception e){} + + + + } + + if (conn != null) + { + logNotice( "SUCCESS connected to Tor control port."); + + File fileCookie = new File(appCacheHome, TOR_CONTROL_COOKIE); + + if (fileCookie.exists()) + { + byte[] cookie = new byte[(int)fileCookie.length()]; + DataInputStream fis = new DataInputStream(new FileInputStream(fileCookie)); + fis.read(cookie); + fis.close(); + conn.authenticate(cookie); + + logNotice( "SUCCESS - authenticated to control port."); + + sendCallbackLogMessage(getString(R.string.tor_process_starting) + ' ' + getString(R.string.tor_process_complete)); + + addEventHandler(); + + String torProcId = conn.getInfo("process/pid"); + + //remove this for now until we can make a clean way to share logs from internal storage + /** + if (ENABLE_DEBUG_LOG) + { + File fileLog2 = new File(getFilesDir(),"orbot-tor-log.txt"); + fileLog2.setReadable(true); + conn.setConf("Log", "debug file " + fileLog2.getCanonicalPath()); + }*/ + + mCurrentStatus = STATUS_CONNECTING; + sendCallbackStatus(mCurrentStatus); + + String confSocks = conn.getInfo("net/listeners/socks"); + StringTokenizer st = new StringTokenizer(confSocks," "); + + confSocks = st.nextToken().split(":")[1]; + confSocks = confSocks.substring(0,confSocks.length()-1); + mPortSOCKS = Integer.parseInt(confSocks); + + if (!isReconnect) //if we are reconnected then we don't need to reset the ports + { + + SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); + + String socksPortPref = prefs.getString(TorConstants.PREF_SOCKS, TorServiceConstants.PORT_SOCKS_DEFAULT); + if (socksPortPref.indexOf(':')!=-1) + socksPortPref = socksPortPref.split(":")[1]; + + String transPort = prefs.getString("pref_transport", TorServiceConstants.TOR_TRANSPROXY_PORT_DEFAULT+""); + if (transPort.indexOf(':')!=-1) + transPort = transPort.split(":")[1]; + + String dnsPort = prefs.getString("pref_dnsport", TorServiceConstants.TOR_DNS_PORT_DEFAULT+""); + if (dnsPort.indexOf(':')!=-1) + dnsPort = dnsPort.split(":")[1]; + + try + { + int newSocksPort = Integer.parseInt(socksPortPref); + ServerSocket ss = new ServerSocket(newSocksPort); + ss.close(); + + ArrayList<String> socksLines = new ArrayList<String>(); + socksLines.add("SOCKSPort " + mPortSOCKS); + socksLines.add("SOCKSPort " + socksPortPref); + + conn.setConf(socksLines); + + mPortSOCKS = newSocksPort; + + sendCallbackLogMessage("Local SOCKS port: " + socksPortPref); + + } + catch (Exception e) + { + sendCallbackLogMessage("Error setting TransProxy port to: " + socksPortPref); + + + } + + try + { + int newPort = Integer.parseInt(transPort); + ServerSocket ss = new ServerSocket(newPort); + ss.close(); + + ArrayList<String> confLines = new ArrayList<String>(); + + confLines.add("TransPort " + transPort); + + conn.setConf(confLines); + + sendCallbackLogMessage("Local TransProxy port: " + transPort); + + } + catch (Exception e) + { + sendCallbackLogMessage("ERROR setting TransProxy port to: " + transPort); + + + + } + + try + { + int newPort = Integer.parseInt(dnsPort); + ServerSocket ss = new ServerSocket(newPort); + ss.close(); + + ArrayList<String> confLines = new ArrayList<String>(); + + confLines.add("DNSPort " + dnsPort); + + conn.setConf(confLines); + + sendCallbackLogMessage("Local DNSPort port: " + transPort); + + } + catch (Exception e) + { + sendCallbackLogMessage("ERROR setting DNSport to: " + dnsPort); + + + } + } + + return Integer.parseInt(torProcId); + + } + else + { + logNotice ("Tor authentication cookie does not exist yet"); + conn = null; + + } + } + + + return -1; + + } + + private int getControlPort () + { + int result = -1; + + try + { + if (fileControlPort.exists()) + { + debug("Reading control port config file: " + fileControlPort.getCanonicalPath()); + BufferedReader bufferedReader = new BufferedReader(new FileReader(fileControlPort)); + String line = bufferedReader.readLine(); + + if (line != null) + { + String[] lineParts = line.split(":"); + result = Integer.parseInt(lineParts[1]); + } + + + bufferedReader.close(); + + //store last valid control port + SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); + prefs.edit().putInt("controlport", result).commit(); + + } + else + { + debug("Control Port config file does not yet exist (waiting for tor): " + fileControlPort.getCanonicalPath()); + + } + + + } + catch (FileNotFoundException e) + { + debug("unable to get control port; file not found"); + } + catch (Exception e) + { + debug("unable to read control port config file"); + } + + return result; + } + + /* + private void getTorStatus () throws IOException + { + try + { + + if (conn != null) + { + // get a single value. + + // get several values + + if (mCurrentStatus == STATUS_CONNECTING) + { + //Map vals = conn.getInfo(Arrays.asList(new String[]{ + // "status/bootstrap-phase", "status","version"})); + + String bsPhase = conn.getInfo("status/bootstrap-phase"); + Log.d(TAG, "bootstrap-phase: " + bsPhase); + + + } + else + { + // String status = conn.getInfo("status/circuit-established"); + // Log.d(TAG, "status/circuit-established=" + status); + } + } + } + catch (Exception e) + { + Log.d(TAG, "Unable to get Tor status from control port"); + mCurrentStatus = STATUS_UNAVAILABLE; + } + + }*/ + + + public void addEventHandler () throws Exception + { + // We extend NullEventHandler so that we don't need to provide empty + // implementations for all the events we don't care about. + // ... + logNotice( "adding control port event handler"); + + conn.setEventHandler(this); + + conn.setEvents(Arrays.asList(new String[]{ + "ORCONN", "CIRC", "NOTICE", "WARN", "ERR","BW"})); + // conn.setEvents(Arrays.asList(new String[]{ + // "DEBUG", "INFO", "NOTICE", "WARN", "ERR"})); + + logNotice( "SUCCESS added control port event handler"); + + + + } + + /** + * Returns the port number that the HTTP proxy is running on + */ + public int getHTTPPort() throws RemoteException { + return mPortHTTP; + } + + + /** + * Returns the port number that the HTTP proxy is running on + */ + public int getSOCKSPort() throws RemoteException { + return mPortSOCKS; + } + + + public void setTorProfile(int newState) { + + if (newState == STATUS_ON) + { + + if (mCurrentStatus == STATUS_OFF) + { + sendCallbackLogMessage (getString(R.string.status_starting_up)); + + + try + { + + boolean found = findExistingProc (); + + if (!found) + { + killProcess(fileTor); + killProcess(filePolipo); + + startTor(); + } + } + catch (Exception e) + { + + logException("Unable to start Tor: " + e.toString(),e); + mCurrentStatus = STATUS_OFF; + sendCallbackStatus(mCurrentStatus); + + showToolbarNotification(getString(R.string.unable_to_start_tor) + ": " + e.getMessage(), ERROR_NOTIFY_ID, R.drawable.ic_stat_notifyerr); + stopTor(); + } + + } + } + else if (newState == STATUS_OFF) + { + if (mCurrentStatus == STATUS_ON) + { + sendCallbackLogMessage (getString(R.string.status_shutting_down)); + + stopTor(); + + mCurrentStatus = STATUS_OFF; + sendCallbackStatus(mCurrentStatus); + } + + } + } + + @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) + public void startVpnService () { + + SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); + Editor ePrefs = prefs.edit(); + + ePrefs.putString("pref_proxy_type", "socks5"); + ePrefs.putString("pref_proxy_host", "127.0.0.1"); + ePrefs.putString("pref_proxy_port", "9999"); + ePrefs.remove("pref_proxy_username"); + ePrefs.remove("pref_proxy_password"); + ePrefs.commit(); + processSettings(); + + Intent intent = new Intent(TorService.this, OrbotVpnService.class); + startService(intent); + + } + + public void stopVpnService () + { + SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); + Editor ePrefs = prefs.edit(); + + ePrefs.remove("pref_proxy_type"); + ePrefs.remove("pref_proxy_host"); + ePrefs.remove("pref_proxy_port"); + ePrefs.remove("pref_proxy_username"); + ePrefs.remove("pref_proxy_password"); + ePrefs.commit(); + processSettings(); + } + + + + public void message(String severity, String msg) { + + + logNotice(severity + ": " + msg); + + if (msg.indexOf(TOR_CONTROL_PORT_MSG_BOOTSTRAP_DONE)!=-1) + { + mCurrentStatus = STATUS_ON; + sendCallbackStatus(mCurrentStatus); + + + showToolbarNotification(getString(R.string.status_activated), NOTIFY_ID, R.drawable.ic_stat_tor); + } + + + + } + + + public void newDescriptors(List<String> orList) { + + } + + + public void orConnStatus(String status, String orName) { + + + StringBuilder sb = new StringBuilder(); + sb.append("orConnStatus ("); + sb.append(parseNodeName(orName) ); + sb.append("): "); + sb.append(status); + + debug(sb.toString()); + + } + + + public void streamStatus(String status, String streamID, String target) { + + StringBuilder sb = new StringBuilder(); + sb.append("StreamStatus ("); + sb.append((streamID)); + sb.append("): "); + sb.append(status); + + logNotice(sb.toString()); + + } + + + public void unrecognized(String type, String msg) { + + StringBuilder sb = new StringBuilder(); + sb.append("Message ("); + sb.append(type); + sb.append("): "); + sb.append(msg); + + logNotice(sb.toString()); + + }
- private void initialize() - { - try - { - - if (mNotificationManager == null) - { - - IntentFilter mNetworkStateFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); - registerReceiver(mNetworkStateReceiver , mNetworkStateFilter); - - mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - - } - - - initBinariesAndDirectories(); - updateSettings(); - - new Thread(new Runnable () - { - public void run () - { - try - { - findExistingProc (); - } - catch (Exception e) - { - Log.e(TAG,"error onBind",e); - logNotice("error finding exiting process: " + e.toString()); - } - - } - }).start(); - - } - catch (Exception e) - { - //what error here - Log.e(TAG, "Error installing Orbot binaries",e); - logNotice("There was an error installing Orbot binaries"); - } - - - } - - private void initBinariesAndDirectories () throws Exception - { - - if (appBinHome == null) - appBinHome = getDir(DIRECTORY_TOR_BINARY,Application.MODE_PRIVATE); - - if (appCacheHome == null) - appCacheHome = getDir(DIRECTORY_TOR_DATA,Application.MODE_PRIVATE); - - fileTor= new File(appBinHome, TOR_ASSET_KEY); - - filePolipo = new File(appBinHome, POLIPO_ASSET_KEY); - - fileObfsclient = new File(appBinHome, OBFSCLIENT_ASSET_KEY); - - fileTorRc = new File(appBinHome, TORRC_ASSET_KEY); - - fileXtables = new File(appBinHome, IPTABLES_ASSET_KEY); - - SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); - String version = prefs.getString(PREF_BINARY_TOR_VERSION_INSTALLED,null); - - logNotice("checking binary version: " + version); - - TorResourceInstaller installer = new TorResourceInstaller(this, appBinHome); - - if (version == null || (!version.equals(BINARY_TOR_VERSION)) || (!fileTor.exists())) - { - logNotice("upgrading binaries to latest version: " + BINARY_TOR_VERSION); - - boolean success = installer.installResources(); - - if (success) - prefs.edit().putString(PREF_BINARY_TOR_VERSION_INSTALLED,BINARY_TOR_VERSION).commit(); - } - - updateTorConfigFile (); - + public void bandwidthUsed(long read, long written) { + + if (read != lastRead || written != lastWritten) + { + StringBuilder sb = new StringBuilder(); + sb.append(formatCount(read)); + sb.append(" \u2193"); + sb.append(" / "); + sb.append(formatCount(written)); + sb.append(" \u2191"); + + int iconId = R.drawable.ic_stat_tor; + + if (read > 0 || written > 0) + iconId = R.drawable.ic_stat_tor_xfer; + + if (mConnectivity && prefPersistNotifications) + showToolbarNotification(sb.toString(), NOTIFY_ID, iconId);
- } + mTotalTrafficWritten += written; + mTotalTrafficRead += read; +
- private boolean updateTorConfigFile () throws FileNotFoundException, IOException, TimeoutException - { - SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); - - TorResourceInstaller installer = new TorResourceInstaller(this, appBinHome); - - StringBuffer extraLines = new StringBuffer(); - - String TORRC_CONTROLPORT_FILE_KEY = "ControlPortWriteToFile"; - fileControlPort = new File(appBinHome,"control.txt"); - extraLines.append(TORRC_CONTROLPORT_FILE_KEY).append(' ').append(fileControlPort.getCanonicalPath()).append('\n'); - - if (mTransProxyTethering) - { - extraLines.append("TransListenAddress 0.0.0.0").append('\n'); - extraLines.append("DNSListenAddress 0.0.0.0").append('\n'); - - } - - extraLines.append("RunAsDaemon 1").append('\n'); - extraLines.append("AvoidDiskWrites 1").append('\n'); - - extraLines.append("SOCKSPort ").append("auto").append('\n'); - extraLines.append("SafeSocks 0").append('\n'); - extraLines.append("TestSocks 0").append('\n'); - extraLines.append("WarnUnsafeSocks 1").append('\n'); - - extraLines.append("TransPort ").append("auto").append('\n'); - extraLines.append("DNSPort ").append("auto").append('\n'); - extraLines.append("VirtualAddrNetwork 10.192.0.0/10").append('\n'); - extraLines.append("AutomapHostsOnResolve 1").append('\n'); + }
+ lastWritten = written; + lastRead = read;
- extraLines.append("CircuitStreamTimeout 60").append('\n'); + sendCallbackStatusMessage(lastWritten, lastRead, mTotalTrafficWritten, mTotalTrafficRead); + + } + + private String formatCount(long count) { + // Converts the supplied argument into a string. + // Under 2Mb, returns "xxx.xKb" + // Over 2Mb, returns "xxx.xxMb" + if (count < 1e6) + return ((float)((int)(count*10/1024))/10 + "Kbps"); + return ((float)((int)(count*100/1024/1024))/100 + "Mbps"); + + //return count+" kB"; + } + + public void circuitStatus(String status, String circID, String path) {
- extraLines.append(prefs.getString("pref_custom_torrc", "")); + StringBuilder sb = new StringBuilder(); + sb.append("Circuit ("); + sb.append((circID)); + sb.append(") "); + sb.append(status); + sb.append(": "); + + StringTokenizer st = new StringTokenizer(path,","); + Node node = null; + + while (st.hasMoreTokens()) + { + String nodePath = st.nextToken(); + node = new Node(); + + String[] nodeParts; + + if (nodePath.contains("=")) + nodeParts = nodePath.split("="); + else + nodeParts = nodePath.split("~"); + + if (nodeParts.length == 1) + { + node.id = nodeParts[0].substring(1); + node.name = node.id; + } + else if (nodeParts.length == 2) + { + node.id = nodeParts[0].substring(1); + node.name = nodeParts[1]; + } + + node.status = status; + + sb.append(node.name); + + if (st.hasMoreTokens()) + sb.append (" > "); + } + + if (ENABLE_DEBUG_LOG) + debug(sb.toString()); + else if(status.equals("BUILT")) + {
- logNotice("updating torrc custom configuration..."); + if (mCurrentStatus == STATUS_CONNECTING) + mCurrentStatus = STATUS_ON; + + sendCallbackStatus(mCurrentStatus); + + + logNotice(sb.toString()); + + } + else if (status.equals("CLOSED")) + { + logNotice(sb.toString());
- debug("torrc.custom=" + extraLines.toString()); - - File fileTorRcCustom = new File(fileTorRc.getAbsolutePath() + ".custom"); - boolean success = installer.updateTorConfigCustom(fileTorRcCustom, extraLines.toString()); - - if (success) - { - logNotice ("success."); - } - - return success; - } + } + + if (mShowExpandedNotifications) + { + //get IP from last nodename + if(status.equals("BUILT")){ + + if (node.ipAddress == null) + mExecutor.execute(new ExternalIPFetcher(node)); + + hmBuiltNodes.put(node.id, node); + } + + if (status.equals("CLOSED")) + { + hmBuiltNodes.remove(node.id); + + } + }
- private boolean enableBinExec (File fileBin) throws Exception - { - - logNotice(fileBin.getName() + ": PRE: Is binary exec? " + fileBin.canExecute()); - - if (!fileBin.canExecute()) - { - logNotice("(re)Setting permission on binary: " + fileBin.getCanonicalPath()); - - Shell shell = Shell.startShell(); - shell.add(new SimpleCommand("chmod " + CHMOD_EXE_VALUE + ' ' + fileBin.getCanonicalPath())).waitForFinish(); - - File fileTest = new File(fileBin.getCanonicalPath()); - logNotice(fileTest.getName() + ": POST: Is binary exec? " + fileTest.canExecute()); - - shell.close(); - } - - return fileBin.canExecute(); }
+ private HashMap<String,Node> hmBuiltNodes = new HashMap<String,Node>();
- private void updateSettings () throws TimeoutException, IOException + class Node { - - SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); - - mHasRoot = prefs.getBoolean(PREF_HAS_ROOT,false); - - mEnableTransparentProxy = prefs.getBoolean("pref_transparent", false); - mTransProxyAll = prefs.getBoolean("pref_transparent_all", false); - mTransProxyTethering = prefs.getBoolean("pref_transparent_tethering", false); - mTransProxyNetworkRefresh = prefs.getBoolean("pref_transproxy_refresh", false); - - mShowExpandedNotifications = prefs.getBoolean("pref_expanded_notifications", false); - - ENABLE_DEBUG_LOG = prefs.getBoolean("pref_enable_logging",false); - Log.i(TAG,"debug logging:" + ENABLE_DEBUG_LOG); - - prefPersistNotifications = prefs.getBoolean(TorConstants.PREF_PERSIST_NOTIFICATIONS, true); - + String status; + String id; + String name; + String ipAddress; + String country; + String organization; }
- private void startTor () throws Exception - { - - mCurrentStatus = STATUS_CONNECTING; - sendCallbackStatus(mCurrentStatus); - - if (fileTor == null) - initBinariesAndDirectories(); - - enableBinExec(fileTor); - enableBinExec(filePolipo); - enableBinExec(fileObfsclient); - enableBinExec(fileXtables); - - updateSettings (); - - logNotice(getString(R.string.status_starting_up)); - sendCallbackLogMessage(getString(R.string.status_starting_up)); - - Shell shellUser = Shell.startShell(); - - boolean success = runTorShellCmd(shellUser); - - if (success) - { - if (mPortHTTP != -1) - runPolipoShellCmd(shellUser); - - if (mHasRoot && mEnableTransparentProxy) - { - Shell shellRoot = Shell.startRootShell(); - - disableTransparentProxy(shellRoot); - enableTransparentProxy(shellRoot); - - shellRoot.close(); - } - - getHiddenServiceHostname (); - } - else - { - showToolbarNotification(getString(R.string.unable_to_start_tor), ERROR_NOTIFY_ID, R.drawable.ic_stat_notifyerr); - - } - - shellUser.close(); - } + private class ExternalIPFetcher implements Runnable {
- private boolean flushTransparentProxyRules () throws Exception - { + private Node mNode; + private int MAX_ATTEMPTS = 3; + private final static String ONIONOO_BASE_URL = "https://onionoo.torproject.org/details?fields=country_name,as_name,or_addres..."; + + public ExternalIPFetcher (Node node) + { + mNode = node; + } + + public void run () + { + + for (int i = 0; i < MAX_ATTEMPTS; i++) + { + if (conn != null) + { + try {
- if (mHasRoot) - { - if (mTransProxy == null) - { - mTransProxy = new TorTransProxy(this, fileXtables); - - } - - mTransProxy.flushTransproxyRules(this); - - return true; - } - else - { - return false; - } - } - - /* - * activate means whether to apply the users preferences - * or clear them out - * - * the idea is that if Tor is off then transproxy is off - */ - private boolean enableTransparentProxy (Shell shell) throws Exception - { - - if (mTransProxy == null) - { - mTransProxy = new TorTransProxy(this, fileXtables); - - } - - - SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); - String transProxy = prefs.getString("pref_transport", TorServiceConstants.TOR_TRANSPROXY_PORT_DEFAULT+""); - String dnsPort = prefs.getString("pref_dnsport", TorServiceConstants.TOR_TRANSPROXY_PORT_DEFAULT+""); - - if (transProxy.indexOf(':')!=-1) //we just want the port for this - transProxy = transProxy.split(":")[1]; - - if (dnsPort.indexOf(':')!=-1) //we just want the port for this - dnsPort = dnsPort.split(":")[1]; - - mTransProxy.setTransProxyPort(Integer.parseInt(transProxy)); - mTransProxy.setDNSPort(Integer.parseInt(dnsPort)); - - int code = 0; // Default state is "okay" - - if(mTransProxyAll) - { - - code = mTransProxy.setTransparentProxyingAll(this, true, shell); - } - else - { - ArrayList<TorifiedApp> apps = AppManager.getApps(this, TorServiceUtils.getSharedPrefs(getApplicationContext())); - - code = mTransProxy.setTransparentProxyingByApp(this,apps, true, shell); - } - - debug ("TorTransProxy resp code: " + code); - - if (code == 0) - { - - if (mTransProxyTethering) - { - showToolbarNotification(getString(R.string.transproxy_enabled_for_tethering_), TRANSPROXY_NOTIFY_ID, R.drawable.ic_stat_tor); - - mTransProxy.enableTetheringRules(this, Shell.startRootShell()); - - } - else - { - showToolbarNotification(getString(R.string.transparent_proxying_enabled), TRANSPROXY_NOTIFY_ID, R.drawable.ic_stat_tor); - - } - } - else - { - showToolbarNotification(getString(R.string.warning_error_starting_transparent_proxying_), TRANSPROXY_NOTIFY_ID, R.drawable.ic_stat_tor); - - } - - return true; - } + Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8118));
- /* - * activate means whether to apply the users preferences - * or clear them out - * - * the idea is that if Tor is off then transproxy is off - */ - private boolean disableTransparentProxy (Shell shell) throws Exception - { - - debug ("Transparent Proxying: disabling..."); - - if (mTransProxy == null) - mTransProxy = new TorTransProxy(this, fileXtables); - - mTransProxy.setTransparentProxyingAll(this, false, shell); - ArrayList<TorifiedApp> apps = AppManager.getApps(this, TorServiceUtils.getSharedPrefs(getApplicationContext())); - mTransProxy.setTransparentProxyingByApp(this, apps, false, shell); - - return true; - } + URLConnection conn = new URL(ONIONOO_BASE_URL + mNode.id).openConnection(proxy); + conn.setRequestProperty("Connection","Close"); + conn.setConnectTimeout(60000); + conn.setReadTimeout(60000); + + InputStream is = conn.getInputStream(); + + BufferedReader reader = new BufferedReader(new InputStreamReader(is));
- private boolean runTorShellCmd(Shell shell) throws Exception - { - - String torrcPath = new File(appBinHome, TORRC_ASSET_KEY).getCanonicalPath(); - - updateTorConfigFile(); - - sendCallbackLogMessage(getString(R.string.status_starting_up)); - - String torCmdString = fileTor.getCanonicalPath() - + " DataDirectory " + appCacheHome.getCanonicalPath() - + " --defaults-torrc " + torrcPath - + " -f " + torrcPath + ".custom"; - - debug(torCmdString); - - SimpleCommand shellTorCommand = new SimpleCommand(torCmdString + " --verify-config"); - shell.add(shellTorCommand).waitForFinish(); - - int exitCode = shellTorCommand.getExitCode(); - String output = shellTorCommand.getOutput(); - - if (exitCode != 0 && output != null && output.length() > 0) - { - logNotice("Tor (" + exitCode + "): " + output); - throw new Exception ("Torrc config did not verify"); - - } - - shellTorCommand = new SimpleCommand(torCmdString); - shell.add(shellTorCommand).waitForFinish(); - - exitCode = shellTorCommand.getExitCode(); - output = shellTorCommand.getOutput(); - - - if (exitCode != 0 && output != null && output.length() > 0) - { - logNotice("Tor (" + exitCode + "): " + output); - //throw new Exception ("unable to start"); - return false; - } - - //now try to connect - mLastProcessId = initControlConnection (100,false); - - if (mLastProcessId == -1) - { - logNotice(getString(R.string.couldn_t_start_tor_process_) + "; exit=" + shellTorCommand.getExitCode() + ": " + shellTorCommand.getOutput()); - sendCallbackLogMessage(getString(R.string.couldn_t_start_tor_process_)); - - throw new Exception ("Unable to start Tor"); - } - else - { - - logNotice("Tor started; process id=" + mLastProcessId); - - processSettingsImpl(); - - - } - - return true; - } + // getting JSON string from URL + + StringBuffer json = new StringBuffer(); + String line = null;
- private void updatePolipoConfig () throws FileNotFoundException, IOException - { - - - File file = new File(appBinHome, POLIPOCONFIG_ASSET_KEY); - - Properties props = new Properties(); - - props.load(new FileReader(file)); - - props.put("socksParentProxy", ""localhost:" + mPortSOCKS + """); - props.put("proxyPort",mPortHTTP+""); - - props.store(new FileWriter(file), "updated"); - + while ((line = reader.readLine())!=null) + json.append(line); + + JSONObject jsonNodeInfo = new org.json.JSONObject(json.toString()); + + JSONArray jsonRelays = jsonNodeInfo.getJSONArray("relays"); + + if (jsonRelays.length() > 0) + { + mNode.ipAddress = jsonRelays.getJSONObject(0).getJSONArray("or_addresses").getString(0).split(":")[0]; + mNode.country = jsonRelays.getJSONObject(0).getString("country_name"); + mNode.organization = jsonRelays.getJSONObject(0).getString("as_name"); + + StringBuffer sbInfo = new StringBuffer(); + sbInfo.append(mNode.ipAddress); + + if (mNode.country != null) + sbInfo.append(' ').append(mNode.country); + + if (mNode.organization != null) + sbInfo.append(" (").append(mNode.organization).append(')'); + + logNotice(sbInfo.toString()); + + } + + reader.close(); + is.close(); + + break; + + } catch (Exception e) { + + debug ("Error getting node details from onionoo: " + e.getMessage()); + + + } + } + } + } + + }
- - private void runPolipoShellCmd (Shell shell) throws Exception + private String parseNodeName(String node) { - - logNotice( "Starting polipo process"); - - int polipoProcId = TorServiceUtils.findProcessId(filePolipo.getCanonicalPath()); - - StringBuilder log = null; - - int attempts = 0; - - if (polipoProcId == -1) - { - log = new StringBuilder(); - - updatePolipoConfig(); - - String polipoConfigPath = new File(appBinHome, POLIPOCONFIG_ASSET_KEY).getCanonicalPath(); - SimpleCommand cmdPolipo = new SimpleCommand(filePolipo.getCanonicalPath() + " -c " + polipoConfigPath + " &"); - - shell.add(cmdPolipo); - - //wait one second to make sure it has started up - Thread.sleep(1000); - - while ((polipoProcId = TorServiceUtils.findProcessId(filePolipo.getCanonicalPath())) == -1 && attempts < MAX_START_TRIES) - { - logNotice("Couldn't find Polipo process... retrying...\n" + log); - Thread.sleep(3000); - attempts++; - } - - logNotice(log.toString()); - } - - sendCallbackLogMessage(getString(R.string.privoxy_is_running_on_port_) + PORT_HTTP); - - logNotice("Polipo process id=" + polipoProcId); - + if (node.indexOf('=')!=-1) + { + return (node.substring(node.indexOf("=")+1)); + } + else if (node.indexOf('~')!=-1) + { + return (node.substring(node.indexOf("~")+1)); + } + else + return node; }
- private int initControlConnection (int maxTries, boolean isReconnect) throws Exception, RuntimeException - { - int i = 0; - int controlPort = -1; - - int attempt = 0; - - - logNotice( "Waiting for control port..."); - - while (conn == null && attempt++ < maxTries) - { - try - { - - controlPort = getControlPort(); - - if (controlPort != -1) - { - logNotice( "Connecting to control port: " + controlPort); - - torConnSocket = new Socket(IP_LOCALHOST, controlPort); - torConnSocket.setSoTimeout(CONTROL_SOCKET_TIMEOUT); - - conn = new TorControlConnection(torConnSocket); - conn.launchThread(true);//is daemon - - break; - } - - } - catch (Exception ce) - { - conn = null; - // logException( "Error connecting to Tor local control port: " + ce.getMessage(),ce); - - } - - - try { - // logNotice("waiting..."); - Thread.sleep(1000); } - catch (Exception e){} - - - - } - - if (conn != null) - { - logNotice( "SUCCESS connected to Tor control port."); - - File fileCookie = new File(appCacheHome, TOR_CONTROL_COOKIE); - - if (fileCookie.exists()) - { - byte[] cookie = new byte[(int)fileCookie.length()]; - DataInputStream fis = new DataInputStream(new FileInputStream(fileCookie)); - fis.read(cookie); - fis.close(); - conn.authenticate(cookie); - - logNotice( "SUCCESS - authenticated to control port."); - - sendCallbackLogMessage(getString(R.string.tor_process_starting) + ' ' + getString(R.string.tor_process_complete)); - - addEventHandler(); - - String torProcId = conn.getInfo("process/pid"); - - //remove this for now until we can make a clean way to share logs from internal storage - /** - if (ENABLE_DEBUG_LOG) - { - File fileLog2 = new File(getFilesDir(),"orbot-tor-log.txt"); - fileLog2.setReadable(true); - conn.setConf("Log", "debug file " + fileLog2.getCanonicalPath()); - }*/ - - mCurrentStatus = STATUS_CONNECTING; - sendCallbackStatus(mCurrentStatus); - - String confSocks = conn.getInfo("net/listeners/socks"); - StringTokenizer st = new StringTokenizer(confSocks," "); - - confSocks = st.nextToken().split(":")[1]; - confSocks = confSocks.substring(0,confSocks.length()-1); - mPortSOCKS = Integer.parseInt(confSocks); - - if (!isReconnect) //if we are reconnected then we don't need to reset the ports - { - - SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); - - String socksPortPref = prefs.getString(TorConstants.PREF_SOCKS, TorServiceConstants.PORT_SOCKS_DEFAULT); - if (socksPortPref.indexOf(':')!=-1) - socksPortPref = socksPortPref.split(":")[1]; - - String transPort = prefs.getString("pref_transport", TorServiceConstants.TOR_TRANSPROXY_PORT_DEFAULT+""); - if (transPort.indexOf(':')!=-1) - transPort = transPort.split(":")[1]; - - String dnsPort = prefs.getString("pref_dnsport", TorServiceConstants.TOR_DNS_PORT_DEFAULT+""); - if (dnsPort.indexOf(':')!=-1) - dnsPort = dnsPort.split(":")[1]; - - try - { - int newSocksPort = Integer.parseInt(socksPortPref); - ServerSocket ss = new ServerSocket(newSocksPort); - ss.close(); - - ArrayList<String> socksLines = new ArrayList<String>(); - socksLines.add("SOCKSPort " + mPortSOCKS); - socksLines.add("SOCKSPort " + socksPortPref); - - conn.setConf(socksLines); - - mPortSOCKS = newSocksPort; - - sendCallbackLogMessage("Local SOCKS port: " + socksPortPref); - - } - catch (Exception e) - { - sendCallbackLogMessage("Error setting TransProxy port to: " + socksPortPref); - - - } - - try - { - int newPort = Integer.parseInt(transPort); - ServerSocket ss = new ServerSocket(newPort); - ss.close(); - - ArrayList<String> confLines = new ArrayList<String>(); - - confLines.add("TransPort " + transPort); - - conn.setConf(confLines); - - sendCallbackLogMessage("Local TransProxy port: " + transPort); - - } - catch (Exception e) - { - sendCallbackLogMessage("ERROR setting TransProxy port to: " + transPort); - - - - } - - try - { - int newPort = Integer.parseInt(dnsPort); - ServerSocket ss = new ServerSocket(newPort); - ss.close(); - - ArrayList<String> confLines = new ArrayList<String>(); - - confLines.add("DNSPort " + dnsPort); - - conn.setConf(confLines); - - sendCallbackLogMessage("Local DNSPort port: " + transPort); - - } - catch (Exception e) - { - sendCallbackLogMessage("ERROR setting DNSport to: " + dnsPort); - - - } - } - - return Integer.parseInt(torProcId); - - } - else - { - logNotice ("Tor authentication cookie does not exist yet"); - conn = null; - - } - } - - - return -1; - - } - - private int getControlPort () - { - int result = -1; - - try - { - if (fileControlPort.exists()) - { - debug("Reading control port config file: " + fileControlPort.getCanonicalPath()); - BufferedReader bufferedReader = new BufferedReader(new FileReader(fileControlPort)); - String line = bufferedReader.readLine(); - - if (line != null) - { - String[] lineParts = line.split(":"); - result = Integer.parseInt(lineParts[1]); - } - - - bufferedReader.close(); - - //store last valid control port - SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); - prefs.edit().putInt("controlport", result).commit(); - - } - else - { - debug("Control Port config file does not yet exist (waiting for tor): " + fileControlPort.getCanonicalPath()); - - } - - - } - catch (FileNotFoundException e) - { - debug("unable to get control port; file not found"); - } - catch (Exception e) - { - debug("unable to read control port config file"); - } - - return result; - } - - /* - private void getTorStatus () throws IOException - { - try - { - - if (conn != null) - { - // get a single value. - - // get several values - - if (mCurrentStatus == STATUS_CONNECTING) - { - //Map vals = conn.getInfo(Arrays.asList(new String[]{ - // "status/bootstrap-phase", "status","version"})); - - String bsPhase = conn.getInfo("status/bootstrap-phase"); - Log.d(TAG, "bootstrap-phase: " + bsPhase); - - - } - else - { - // String status = conn.getInfo("status/circuit-established"); - // Log.d(TAG, "status/circuit-established=" + status); - } - } - } - catch (Exception e) - { - Log.d(TAG, "Unable to get Tor status from control port"); - mCurrentStatus = STATUS_UNAVAILABLE; - } - - }*/ - - - public void addEventHandler () throws Exception - { - // We extend NullEventHandler so that we don't need to provide empty - // implementations for all the events we don't care about. - // ... - logNotice( "adding control port event handler"); - - conn.setEventHandler(this); - - conn.setEvents(Arrays.asList(new String[]{ - "ORCONN", "CIRC", "NOTICE", "WARN", "ERR","BW"})); - // conn.setEvents(Arrays.asList(new String[]{ - // "DEBUG", "INFO", "NOTICE", "WARN", "ERR"})); - - logNotice( "SUCCESS added control port event handler"); - - - - } - - /** - * Returns the port number that the HTTP proxy is running on - */ - public int getHTTPPort() throws RemoteException { - return mPortHTTP; - } - - - /** - * Returns the port number that the HTTP proxy is running on - */ - public int getSOCKSPort() throws RemoteException { - return mPortSOCKS; - } - - - public void setTorProfile(int newState) { - - if (newState == STATUS_ON) - { - - if (mCurrentStatus == STATUS_OFF) - { - sendCallbackLogMessage (getString(R.string.status_starting_up)); - - - try - { - - boolean found = findExistingProc (); - - if (!found) - { - killProcess(fileTor); - killProcess(filePolipo); - - startTor(); - } - } - catch (Exception e) - { - - logException("Unable to start Tor: " + e.toString(),e); - mCurrentStatus = STATUS_OFF; - sendCallbackStatus(mCurrentStatus); - - showToolbarNotification(getString(R.string.unable_to_start_tor) + ": " + e.getMessage(), ERROR_NOTIFY_ID, R.drawable.ic_stat_notifyerr); - stopTor(); - } - - } - } - else if (newState == STATUS_OFF) - { - if (mCurrentStatus == STATUS_ON) - { - sendCallbackLogMessage (getString(R.string.status_shutting_down)); - - stopTor(); - - mCurrentStatus = STATUS_OFF; - sendCallbackStatus(mCurrentStatus); - } - - } - } - - @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) - public void startVpnService () { - - SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); - Editor ePrefs = prefs.edit(); - - ePrefs.putString("pref_proxy_type", "socks5"); - ePrefs.putString("pref_proxy_host", "127.0.0.1"); - ePrefs.putString("pref_proxy_port", "9999"); - ePrefs.remove("pref_proxy_username"); - ePrefs.remove("pref_proxy_password"); - ePrefs.commit(); - processSettings(); - - Intent intent = new Intent(TorService.this, OrbotVpnService.class); - startService(intent); - - } - - public void stopVpnService () - { - SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); - Editor ePrefs = prefs.edit(); - - ePrefs.remove("pref_proxy_type"); - ePrefs.remove("pref_proxy_host"); - ePrefs.remove("pref_proxy_port"); - ePrefs.remove("pref_proxy_username"); - ePrefs.remove("pref_proxy_password"); - ePrefs.commit(); - processSettings(); - } - - - - public void message(String severity, String msg) { - - - logNotice(severity + ": " + msg); - - if (msg.indexOf(TOR_CONTROL_PORT_MSG_BOOTSTRAP_DONE)!=-1) - { - mCurrentStatus = STATUS_ON; - sendCallbackStatus(mCurrentStatus); -
- showToolbarNotification(getString(R.string.status_activated), NOTIFY_ID, R.drawable.ic_stat_tor); - }
- - - } - - - public void newDescriptors(List<String> orList) { - - } - - - public void orConnStatus(String status, String orName) { - - - StringBuilder sb = new StringBuilder(); - sb.append("orConnStatus ("); - sb.append(parseNodeName(orName) ); - sb.append("): "); - sb.append(status); - - debug(sb.toString()); - - } - - - public void streamStatus(String status, String streamID, String target) { - - StringBuilder sb = new StringBuilder(); - sb.append("StreamStatus ("); - sb.append((streamID)); - sb.append("): "); - sb.append(status); - - logNotice(sb.toString()); - - } - - - public void unrecognized(String type, String msg) { - - StringBuilder sb = new StringBuilder(); - sb.append("Message ("); - sb.append(type); - sb.append("): "); - sb.append(msg); - - logNotice(sb.toString()); - - - } - - public void bandwidthUsed(long read, long written) { - - if (read != lastRead || written != lastWritten) - { - StringBuilder sb = new StringBuilder(); - sb.append(formatCount(read)); - sb.append(" \u2193"); - sb.append(" / "); - sb.append(formatCount(written)); - sb.append(" \u2191"); - - int iconId = R.drawable.ic_stat_tor; - - if (read > 0 || written > 0) - iconId = R.drawable.ic_stat_tor_xfer; - - if (mConnectivity && prefPersistNotifications) - showToolbarNotification(sb.toString(), NOTIFY_ID, iconId); - - mTotalTrafficWritten += written; - mTotalTrafficRead += read; - - - } - - lastWritten = written; - lastRead = read; - - sendCallbackStatusMessage(lastWritten, lastRead, mTotalTrafficWritten, mTotalTrafficRead); - - } - - private String formatCount(long count) { - // Converts the supplied argument into a string. - // Under 2Mb, returns "xxx.xKb" - // Over 2Mb, returns "xxx.xxMb" - if (count < 1e6) - return ((float)((int)(count*10/1024))/10 + "Kbps"); - return ((float)((int)(count*100/1024/1024))/100 + "Mbps"); - - //return count+" kB"; - } - - public void circuitStatus(String status, String circID, String path) { - - - StringBuilder sb = new StringBuilder(); - sb.append("Circuit ("); - sb.append((circID)); - sb.append(") "); - sb.append(status); - sb.append(": "); - - StringTokenizer st = new StringTokenizer(path,","); - Node node = null; - - while (st.hasMoreTokens()) - { - String nodePath = st.nextToken(); - node = new Node(); - - String[] nodeParts; - - if (nodePath.contains("=")) - nodeParts = nodePath.split("="); - else - nodeParts = nodePath.split("~"); - - if (nodeParts.length == 1) - { - node.id = nodeParts[0].substring(1); - node.name = node.id; - } - else if (nodeParts.length == 2) - { - node.id = nodeParts[0].substring(1); - node.name = nodeParts[1]; - } - - node.status = status; - - sb.append(node.name); - - if (st.hasMoreTokens()) - sb.append (" > "); - } - - if (ENABLE_DEBUG_LOG) - debug(sb.toString()); - else if(status.equals("BUILT")) - { - - if (mCurrentStatus == STATUS_CONNECTING) - mCurrentStatus = STATUS_ON; - - sendCallbackStatus(mCurrentStatus); - - - logNotice(sb.toString()); - - } - else if (status.equals("CLOSED")) - { - logNotice(sb.toString()); - - } - - if (mShowExpandedNotifications) - { - //get IP from last nodename - if(status.equals("BUILT")){ - - if (node.ipAddress == null) - mExecutor.execute(new ExternalIPFetcher(node)); - - hmBuiltNodes.put(node.id, node); - } - - if (status.equals("CLOSED")) - { - hmBuiltNodes.remove(node.id); - - } - } - - } - - private HashMap<String,Node> hmBuiltNodes = new HashMap<String,Node>(); - - class Node - { - String status; - String id; - String name; - String ipAddress; - String country; - String organization; - } - - private class ExternalIPFetcher implements Runnable { - - private Node mNode; - private int MAX_ATTEMPTS = 3; - private final static String ONIONOO_BASE_URL = "https://onionoo.torproject.org/details?fields=country_name,as_name,or_addres..."; - - public ExternalIPFetcher (Node node) - { - mNode = node; - } - - public void run () - { - - for (int i = 0; i < MAX_ATTEMPTS; i++) - { - if (conn != null) - { - try { - - Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8118)); - - URLConnection conn = new URL(ONIONOO_BASE_URL + mNode.id).openConnection(proxy); - conn.setRequestProperty("Connection","Close"); - conn.setConnectTimeout(60000); - conn.setReadTimeout(60000); - - InputStream is = conn.getInputStream(); - - BufferedReader reader = new BufferedReader(new InputStreamReader(is)); - - // getting JSON string from URL - - StringBuffer json = new StringBuffer(); - String line = null; - - while ((line = reader.readLine())!=null) - json.append(line); - - JSONObject jsonNodeInfo = new org.json.JSONObject(json.toString()); - - JSONArray jsonRelays = jsonNodeInfo.getJSONArray("relays"); - - if (jsonRelays.length() > 0) - { - mNode.ipAddress = jsonRelays.getJSONObject(0).getJSONArray("or_addresses").getString(0).split(":")[0]; - mNode.country = jsonRelays.getJSONObject(0).getString("country_name"); - mNode.organization = jsonRelays.getJSONObject(0).getString("as_name"); - - StringBuffer sbInfo = new StringBuffer(); - sbInfo.append(mNode.ipAddress); - - if (mNode.country != null) - sbInfo.append(' ').append(mNode.country); - - if (mNode.organization != null) - sbInfo.append(" (").append(mNode.organization).append(')'); - - logNotice(sbInfo.toString()); - - } - - reader.close(); - is.close(); - - break; - - } catch (Exception e) { - - debug ("Error getting node details from onionoo: " + e.getMessage()); - - - } - } - } - } - - - } - - private String parseNodeName(String node) - { - if (node.indexOf('=')!=-1) - { - return (node.substring(node.indexOf("=")+1)); - } - else if (node.indexOf('~')!=-1) - { - return (node.substring(node.indexOf("~")+1)); - } - else - return node; - } - - - - public void processSettings () - { - - try { - - boolean hadEnableTransparentProxy = mEnableTransparentProxy; - - updateSettings (); - - if (mHasRoot) - { - Shell shell = Shell.startRootShell(); - - if (hadEnableTransparentProxy) - disableTransparentProxy(shell); - - if (mEnableTransparentProxy) - enableTransparentProxy(shell); - - shell.close(); - } - - - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - Thread thread = new Thread() - { - - public void run () - { - try { - - - - processSettingsImpl (); - - - } catch (Exception e) { - logException ("error applying mPrefs",e); - } - } - }; - - thread.start(); - + public void processSettings (){ + try{ + boolean hadEnableTransparentProxy = mEnableTransparentProxy; + updateSettings (); + if (mHasRoot) + { + Shell shell = Shell.startRootShell(); + if (hadEnableTransparentProxy){ + disableTransparentProxy(shell); + } + if (mEnableTransparentProxy){ + enableTransparentProxy(shell); + } + shell.close(); + } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + Thread thread = new Thread(){ + public void run (){ + try { + processSettingsImpl(); + } catch (Exception e) { + logException ("error applying mPrefs",e); + } + } + }; + thread.start(); } -
- public String getInfo (String key) { - try - { - if(conn !=null) - { - String m = conn.getInfo(key); - return m; - - } - } - catch(Exception ioe) - { - // Log.e(TAG,"Unable to get Tor information",ioe); - logNotice("Unable to get Tor information"+ioe.getMessage()); - } - return null; + public String getInfo (String key) { + try { + if(conn !=null){ + String m = conn.getInfo(key); + return m; + } + } + catch(Exception ioe){ + // Log.e(TAG,"Unable to get Tor information",ioe); + logNotice("Unable to get Tor information"+ioe.getMessage()); + } + return null; }
public String getConfiguration (String name) { - try - { - if (conn != null) - { - StringBuffer result = new StringBuffer(); - - List<ConfigEntry> listCe = conn.getConf(name); - - Iterator<ConfigEntry> itCe = listCe.iterator(); - ConfigEntry ce = null; - - - - while (itCe.hasNext()) - { - ce = itCe.next(); - - result.append(ce.key); - result.append(' '); - result.append(ce.value); - result.append('\n'); - } - - return result.toString(); - } - } - catch (Exception ioe) - { - - logException("Unable to get Tor configuration: " + ioe.getMessage(),ioe); - } - - return null; + try + { + if (conn != null) + { + StringBuffer result = new StringBuffer(); + + List<ConfigEntry> listCe = conn.getConf(name); + + Iterator<ConfigEntry> itCe = listCe.iterator(); + ConfigEntry ce = null; + + + + while (itCe.hasNext()) + { + ce = itCe.next(); + + result.append(ce.key); + result.append(' '); + result.append(ce.value); + result.append('\n'); + } + + return result.toString(); + } + } + catch (Exception ioe) + { + + logException("Unable to get Tor configuration: " + ioe.getMessage(),ioe); + } + + return null; }
private final static String RESET_STRING = "="""; @@ -1897,123 +1843,123 @@ public class TorService extends Service implements TorServiceConstants, TorConst {
- if (configBuffer == null) - configBuffer = new ArrayList<String>(); - - if (resetBuffer == null) - resetBuffer = new ArrayList<String>(); - - if (value == null || value.length() == 0) - { - resetBuffer.add(name + RESET_STRING); - - } - else - { - StringBuffer sbConf = new StringBuffer(); - sbConf.append(name); - sbConf.append(' '); - sbConf.append(value); - - configBuffer.add(sbConf.toString()); - } - - return false; + if (configBuffer == null) + configBuffer = new ArrayList<String>(); + + if (resetBuffer == null) + resetBuffer = new ArrayList<String>(); + + if (value == null || value.length() == 0) + { + resetBuffer.add(name + RESET_STRING); + + } + else + { + StringBuffer sbConf = new StringBuffer(); + sbConf.append(name); + sbConf.append(' '); + sbConf.append(value); + + configBuffer.add(sbConf.toString()); + } + + return false; }
public void newIdentity () { - //it is possible to not have a connection yet, and someone might try to newnym - if (conn != null) - { - new Thread () - { - public void run () - { - try { - - conn.signal("NEWNYM"); - - } - catch (Exception ioe){ - debug("error requesting newnym: " + ioe.getLocalizedMessage()); - } - } - }.start(); - } - } - - public boolean saveConfiguration () - { - try - { - if (conn != null) - { - - if (resetBuffer != null && resetBuffer.size() > 0) - { - for (String value : configBuffer) - { - - debug("removing torrc conf: " + value); - - - } - - conn.resetConf(resetBuffer); - resetBuffer = null; - } - - if (configBuffer != null && configBuffer.size() > 0) - { - - for (String value : configBuffer) - { - - debug("Setting torrc conf: " + value); - - - } - - conn.setConf(configBuffer); - - configBuffer = null; - } - - // Flush the configuration to disk. - //this is doing bad things right now NF 22/07/10 - //conn.saveConf(); - - return true; - } - } - catch (Exception ioe) - { - - logException("Unable to update Tor configuration: " + ioe.getMessage(),ioe); - - } - - return false; - - } - - - - + //it is possible to not have a connection yet, and someone might try to newnym + if (conn != null) + { + new Thread () + { + public void run () + { + try { + + conn.signal("NEWNYM"); + + } + catch (Exception ioe){ + debug("error requesting newnym: " + ioe.getLocalizedMessage()); + } + } + }.start(); + } + } + + public boolean saveConfiguration () + { + try + { + if (conn != null) + { + + if (resetBuffer != null && resetBuffer.size() > 0) + { + for (String value : configBuffer) + { + + debug("removing torrc conf: " + value); + + + } + + conn.resetConf(resetBuffer); + resetBuffer = null; + } + + if (configBuffer != null && configBuffer.size() > 0) + { + + for (String value : configBuffer) + { + + debug("Setting torrc conf: " + value); + + + } + + conn.setConf(configBuffer); + + configBuffer = null; + } + + // Flush the configuration to disk. + //this is doing bad things right now NF 22/07/10 + //conn.saveConf(); + + return true; + } + } + catch (Exception ioe) + { + + logException("Unable to update Tor configuration: " + ioe.getMessage(),ioe); + + } + + return false; + + } + + + +
private void sendCallbackStatusMessage (long upload, long download, long written, long read) { - - - Intent intent = new Intent("log"); - // You can also include some extra data. - intent.putExtra("up",upload); - intent.putExtra("down",download); - intent.putExtra("written",written); - intent.putExtra("read",read); - - LocalBroadcastManager.getInstance(this).sendBroadcast(intent); + + + Intent intent = new Intent("log"); + // You can also include some extra data. + intent.putExtra("up",upload); + intent.putExtra("down",download); + intent.putExtra("written",written); + intent.putExtra("read",read); + + LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
@@ -2021,23 +1967,23 @@ public class TorService extends Service implements TorServiceConstants, TorConst
private void sendCallbackLogMessage (String logMessage) { - - - Intent intent = new Intent("log"); - // You can also include some extra data. - intent.putExtra("log", logMessage); - LocalBroadcastManager.getInstance(this).sendBroadcast(intent); + + + Intent intent = new Intent("log"); + // You can also include some extra data. + intent.putExtra("log", logMessage); + LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
private void sendCallbackStatus (int currentStatus) { - - - Intent intent = new Intent("status"); - // You can also include some extra data. - intent.putExtra("status", currentStatus); - LocalBroadcastManager.getInstance(this).sendBroadcast(intent); + + + Intent intent = new Intent("status"); + // You can also include some extra data. + intent.putExtra("status", currentStatus); + LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
@@ -2048,85 +1994,85 @@ public class TorService extends Service implements TorServiceConstants, TorConst */
private final BroadcastReceiver mNetworkStateReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - - SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); - - boolean doNetworKSleep = prefs.getBoolean(TorConstants.PREF_DISABLE_NETWORK, true); - - final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); - final NetworkInfo netInfo = cm.getActiveNetworkInfo(); - - if(netInfo != null && netInfo.isConnected()) { - // WE ARE CONNECTED: DO SOMETHING - mConnectivity = true; - } - else { - // WE ARE NOT: DO SOMETHING ELSE - mConnectivity = false; - } - - if (doNetworKSleep) - { - try { - updateConfiguration("DisableNetwork", mConnectivity ? "0" : "1", false); - - if (mCurrentStatus != STATUS_OFF) - { - if (!mConnectivity) - { - logNotice(context.getString(R.string.no_network_connectivity_putting_tor_to_sleep_)); - showToolbarNotification(getString(R.string.no_internet_connection_tor),NOTIFY_ID,R.drawable.ic_stat_tor_off); - - } - else - { - logNotice(context.getString(R.string.network_connectivity_is_good_waking_tor_up_)); - showToolbarNotification(getString(R.string.status_activated),NOTIFY_ID,R.drawable.ic_stat_tor); - - if (mHasRoot && mEnableTransparentProxy && mTransProxyNetworkRefresh) - { - - Shell shell = Shell.startRootShell(); - - disableTransparentProxy(shell); - enableTransparentProxy(shell); - - shell.close(); - } - - } - } - - } catch (Exception e) { - logException ("error updating state after network restart",e); - } - } - - } + @Override + public void onReceive(Context context, Intent intent) { + + SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); + + boolean doNetworKSleep = prefs.getBoolean(TorConstants.PREF_DISABLE_NETWORK, true); + + final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); + final NetworkInfo netInfo = cm.getActiveNetworkInfo(); + + if(netInfo != null && netInfo.isConnected()) { + // WE ARE CONNECTED: DO SOMETHING + mConnectivity = true; + } + else { + // WE ARE NOT: DO SOMETHING ELSE + mConnectivity = false; + } + + if (doNetworKSleep) + { + try { + updateConfiguration("DisableNetwork", mConnectivity ? "0" : "1", false); + + if (mCurrentStatus != STATUS_OFF) + { + if (!mConnectivity) + { + logNotice(context.getString(R.string.no_network_connectivity_putting_tor_to_sleep_)); + showToolbarNotification(getString(R.string.no_internet_connection_tor),NOTIFY_ID,R.drawable.ic_stat_tor_off); + + } + else + { + logNotice(context.getString(R.string.network_connectivity_is_good_waking_tor_up_)); + showToolbarNotification(getString(R.string.status_activated),NOTIFY_ID,R.drawable.ic_stat_tor); + + if (mHasRoot && mEnableTransparentProxy && mTransProxyNetworkRefresh) + { + + Shell shell = Shell.startRootShell(); + + disableTransparentProxy(shell); + enableTransparentProxy(shell); + + shell.close(); + } + + } + } + + } catch (Exception e) { + logException ("error updating state after network restart",e); + } + } + + } };
private boolean processSettingsImpl () throws Exception { - logNotice(getString(R.string.updating_settings_in_tor_service)); - - SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); + logNotice(getString(R.string.updating_settings_in_tor_service)); + + SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext());
- /* + /* String socksConfig = prefs.getString(TorConstants.PREF_SOCKS, TorServiceConstants.PORT_SOCKS_DEFAULT);
- enableSocks (socksConfig,false); - - String transPort = prefs.getString("pref_transport", TorServiceConstants.TOR_TRANSPROXY_PORT_DEFAULT+""); - String dnsPort = prefs.getString("pref_dnsport", TorServiceConstants.TOR_DNS_PORT_DEFAULT+""); - - enableTransProxyAndDNSPorts(transPort, dnsPort); - */ - - boolean useBridges = prefs.getBoolean(TorConstants.PREF_BRIDGES_ENABLED, false); - - //boolean autoUpdateBridges = prefs.getBoolean(TorConstants.PREF_BRIDGES_UPDATED, false); + enableSocks (socksConfig,false); + + String transPort = prefs.getString("pref_transport", TorServiceConstants.TOR_TRANSPROXY_PORT_DEFAULT+""); + String dnsPort = prefs.getString("pref_dnsport", TorServiceConstants.TOR_DNS_PORT_DEFAULT+""); + + enableTransProxyAndDNSPorts(transPort, dnsPort); + */ + + boolean useBridges = prefs.getBoolean(TorConstants.PREF_BRIDGES_ENABLED, false); + + //boolean autoUpdateBridges = prefs.getBoolean(TorConstants.PREF_BRIDGES_UPDATED, false);
boolean becomeRelay = prefs.getBoolean(TorConstants.PREF_OR, false); boolean ReachableAddresses = prefs.getBoolean(TorConstants.PREF_REACHABLE_ADDRESSES,false); @@ -2140,133 +2086,133 @@ public class TorService extends Service implements TorServiceConstants, TorConst String proxyType = prefs.getString("pref_proxy_type", null); if (proxyType != null && proxyType.length() > 0) { - String proxyHost = prefs.getString("pref_proxy_host", null); - String proxyPort = prefs.getString("pref_proxy_port", null); - String proxyUser = prefs.getString("pref_proxy_username", null); - String proxyPass = prefs.getString("pref_proxy_password", null); - - if ((proxyHost != null && proxyHost.length()>0) && (proxyPort != null && proxyPort.length() > 0)) - { - updateConfiguration(proxyType + "Proxy", proxyHost + ':' + proxyPort, false); - - if (proxyUser != null && proxyPass != null) - { - if (proxyType.equalsIgnoreCase("socks5")) - { - updateConfiguration("Socks5ProxyUsername", proxyUser, false); - updateConfiguration("Socks5ProxyPassword", proxyPass, false); - } - else - updateConfiguration(proxyType + "ProxyAuthenticator", proxyUser + ':' + proxyPort, false); - - } - else if (proxyPass != null) - updateConfiguration(proxyType + "ProxyAuthenticator", proxyUser + ':' + proxyPort, false); - - - - } + String proxyHost = prefs.getString("pref_proxy_host", null); + String proxyPort = prefs.getString("pref_proxy_port", null); + String proxyUser = prefs.getString("pref_proxy_username", null); + String proxyPass = prefs.getString("pref_proxy_password", null); + + if ((proxyHost != null && proxyHost.length()>0) && (proxyPort != null && proxyPort.length() > 0)) + { + updateConfiguration(proxyType + "Proxy", proxyHost + ':' + proxyPort, false); + + if (proxyUser != null && proxyPass != null) + { + if (proxyType.equalsIgnoreCase("socks5")) + { + updateConfiguration("Socks5ProxyUsername", proxyUser, false); + updateConfiguration("Socks5ProxyPassword", proxyPass, false); + } + else + updateConfiguration(proxyType + "ProxyAuthenticator", proxyUser + ':' + proxyPort, false); + + } + else if (proxyPass != null) + updateConfiguration(proxyType + "ProxyAuthenticator", proxyUser + ':' + proxyPort, false); + + + + } }
if (entranceNodes.length() > 0 || exitNodes.length() > 0 || excludeNodes.length() > 0) { - //only apply GeoIP if you need it - File fileGeoIP = new File(appBinHome,GEOIP_ASSET_KEY); - File fileGeoIP6 = new File(appBinHome,GEOIP6_ASSET_KEY); - - try - { - if ((!fileGeoIP.exists())) - { - TorResourceInstaller installer = new TorResourceInstaller(this, appBinHome); - boolean success = installer.installGeoIP(); - - } - - updateConfiguration("GeoIPFile", fileGeoIP.getCanonicalPath(), false); - updateConfiguration("GeoIPv6File", fileGeoIP6.getCanonicalPath(), false); - - } - catch (Exception e) - { - showToolbarNotification (getString(R.string.error_installing_binares),ERROR_NOTIFY_ID,R.drawable.ic_stat_notifyerr); - - return false; - } + //only apply GeoIP if you need it + File fileGeoIP = new File(appBinHome,GEOIP_ASSET_KEY); + File fileGeoIP6 = new File(appBinHome,GEOIP6_ASSET_KEY); + + try + { + if ((!fileGeoIP.exists())) + { + TorResourceInstaller installer = new TorResourceInstaller(this, appBinHome); + boolean success = installer.installGeoIP(); + + } + + updateConfiguration("GeoIPFile", fileGeoIP.getCanonicalPath(), false); + updateConfiguration("GeoIPv6File", fileGeoIP6.getCanonicalPath(), false); + + } + catch (Exception e) + { + showToolbarNotification (getString(R.string.error_installing_binares),ERROR_NOTIFY_ID,R.drawable.ic_stat_notifyerr); + + return false; + } }
updateConfiguration("EntryNodes", entranceNodes, false); updateConfiguration("ExitNodes", exitNodes, false); - updateConfiguration("ExcludeNodes", excludeNodes, false); - updateConfiguration("StrictNodes", enableStrictNodes ? "1" : "0", false); - - if (useBridges) - { - - debug ("Using bridges"); - String bridgeCfgKey = "Bridge"; - - String bridgeList = prefs.getString(TorConstants.PREF_BRIDGES_LIST,null); - - if (bridgeList == null || bridgeList.length() == 0) - { - String msgBridge = getString(R.string.bridge_requires_ip) + - getString(R.string.send_email_for_bridges); - showToolbarNotification(msgBridge, ERROR_NOTIFY_ID, R.drawable.ic_stat_tor); - debug(msgBridge); - - return false; - } - - - String bridgeDelim = "\n"; - - if (bridgeList.indexOf(",") != -1) - { - bridgeDelim = ","; - } - - showToolbarNotification(getString(R.string.notification_using_bridges) + ": " + bridgeList, TRANSPROXY_NOTIFY_ID, R.drawable.ic_stat_tor); + updateConfiguration("ExcludeNodes", excludeNodes, false); + updateConfiguration("StrictNodes", enableStrictNodes ? "1" : "0", false); + + if (useBridges) + { + + debug ("Using bridges"); + String bridgeCfgKey = "Bridge"; + + String bridgeList = prefs.getString(TorConstants.PREF_BRIDGES_LIST,null); + + if (bridgeList == null || bridgeList.length() == 0) + { + String msgBridge = getString(R.string.bridge_requires_ip) + + getString(R.string.send_email_for_bridges); + showToolbarNotification(msgBridge, ERROR_NOTIFY_ID, R.drawable.ic_stat_tor); + debug(msgBridge); + + return false; + } + + + String bridgeDelim = "\n"; + + if (bridgeList.indexOf(",") != -1) + { + bridgeDelim = ","; + } + + showToolbarNotification(getString(R.string.notification_using_bridges) + ": " + bridgeList, TRANSPROXY_NOTIFY_ID, R.drawable.ic_stat_tor);
- StringTokenizer st = new StringTokenizer(bridgeList,bridgeDelim); - while (st.hasMoreTokens()) - { - String bridgeConfigLine = st.nextToken().trim(); - debug("Adding bridge: " + bridgeConfigLine); - updateConfiguration(bridgeCfgKey, bridgeConfigLine, false); - - } - - //check if any PT bridges are needed - boolean obfsBridges = bridgeList.contains("obfs2")||bridgeList.contains("obfs3")||bridgeList.contains("scramblesuit"); - - if (obfsBridges) - { - String bridgeConfig = "obfs2,obfs3,scramblesuit exec " + fileObfsclient.getCanonicalPath(); - - debug ("Using OBFUSCATED bridges: " + bridgeConfig); - - updateConfiguration("ClientTransportPlugin",bridgeConfig, false); - } - else - { - debug ("Using standard bridges"); - } - - - - updateConfiguration("UpdateBridgesFromAuthority", "0", false); - - - updateConfiguration("UseBridges", "1", false); - - - } - else - { - updateConfiguration("UseBridges", "0", false); - - } + StringTokenizer st = new StringTokenizer(bridgeList,bridgeDelim); + while (st.hasMoreTokens()) + { + String bridgeConfigLine = st.nextToken().trim(); + debug("Adding bridge: " + bridgeConfigLine); + updateConfiguration(bridgeCfgKey, bridgeConfigLine, false); + + } + + //check if any PT bridges are needed + boolean obfsBridges = bridgeList.contains("obfs2")||bridgeList.contains("obfs3")||bridgeList.contains("scramblesuit"); + + if (obfsBridges) + { + String bridgeConfig = "obfs2,obfs3,scramblesuit exec " + fileObfsclient.getCanonicalPath(); + + debug ("Using OBFUSCATED bridges: " + bridgeConfig); + + updateConfiguration("ClientTransportPlugin",bridgeConfig, false); + } + else + { + debug ("Using standard bridges"); + } + + + + updateConfiguration("UpdateBridgesFromAuthority", "0", false); + + + updateConfiguration("UseBridges", "1", false); + + + } + else + { + updateConfiguration("UseBridges", "0", false); + + }
try { @@ -2285,7 +2231,7 @@ public class TorService extends Service implements TorServiceConstants, TorConst } catch (Exception e) { - showToolbarNotification (getString(R.string.your_reachableaddresses_settings_caused_an_exception_),ERROR_NOTIFY_ID,R.drawable.ic_stat_notifyerr); + showToolbarNotification (getString(R.string.your_reachableaddresses_settings_caused_an_exception_),ERROR_NOTIFY_ID,R.drawable.ic_stat_notifyerr);
return false; } @@ -2301,20 +2247,20 @@ public class TorService extends Service implements TorServiceConstants, TorConst
updateConfiguration("ServerDNSResolvConfFile", dnsFile, false); updateConfiguration("ORPort", ORPort + "", false); - updateConfiguration("Nickname", nickname, false); - updateConfiguration("ExitPolicy", "reject *:*", false); + updateConfiguration("Nickname", nickname, false); + updateConfiguration("ExitPolicy", "reject *:*", false);
} else { - updateConfiguration("ORPort", "", false); - updateConfiguration("Nickname", "", false); - updateConfiguration("ExitPolicy", "", false); + updateConfiguration("ORPort", "", false); + updateConfiguration("Nickname", "", false); + updateConfiguration("ExitPolicy", "", false); } } catch (Exception e) { - showToolbarNotification (getString(R.string.your_relay_settings_caused_an_exception_),ERROR_NOTIFY_ID,R.drawable.ic_stat_notifyerr); + showToolbarNotification (getString(R.string.your_relay_settings_caused_an_exception_),ERROR_NOTIFY_ID,R.drawable.ic_stat_notifyerr);
return false; @@ -2322,189 +2268,188 @@ public class TorService extends Service implements TorServiceConstants, TorConst
if (enableHiddenServices) { - logNotice("hidden services are enabled"); - - //updateConfiguration("RendPostPeriod", "600 seconds", false); //possible feature to investigate - - String hsPorts = prefs.getString("pref_hs_ports",""); - - StringTokenizer st = new StringTokenizer (hsPorts,","); - String hsPortConfig = null; - int hsPort = -1; - - while (st.hasMoreTokens()) - { - try - { - hsPortConfig = st.nextToken().trim(); - - if (hsPortConfig.indexOf(":")==-1) //setup the port to localhost if not specifed - { - hsPortConfig = hsPortConfig + " 127.0.0.1:" + hsPortConfig; - } - - hsPort = Integer.parseInt(hsPortConfig.split(" ")[0]); - - String hsDirPath = new File(appCacheHome,"hs" + hsPort).getCanonicalPath(); - - debug("Adding hidden service on port: " + hsPortConfig); - - - updateConfiguration("HiddenServiceDir",hsDirPath, false); - updateConfiguration("HiddenServicePort",hsPortConfig, false); - - - } catch (NumberFormatException e) { - Log.e(this.TAG,"error parsing hsport",e); - } catch (Exception e) { - Log.e(this.TAG,"error starting share server",e); - } - } - - + logNotice("hidden services are enabled"); + + //updateConfiguration("RendPostPeriod", "600 seconds", false); //possible feature to investigate + + String hsPorts = prefs.getString("pref_hs_ports",""); + + StringTokenizer st = new StringTokenizer (hsPorts,","); + String hsPortConfig = null; + int hsPort = -1; + + while (st.hasMoreTokens()) + { + try + { + hsPortConfig = st.nextToken().trim(); + + if (hsPortConfig.indexOf(":")==-1) //setup the port to localhost if not specifed + { + hsPortConfig = hsPortConfig + " 127.0.0.1:" + hsPortConfig; + } + + hsPort = Integer.parseInt(hsPortConfig.split(" ")[0]); + + String hsDirPath = new File(appCacheHome,"hs" + hsPort).getCanonicalPath(); + + debug("Adding hidden service on port: " + hsPortConfig); + + + updateConfiguration("HiddenServiceDir",hsDirPath, false); + updateConfiguration("HiddenServicePort",hsPortConfig, false); + + + } catch (NumberFormatException e) { + Log.e(this.TAG,"error parsing hsport",e); + } catch (Exception e) { + Log.e(this.TAG,"error starting share server",e); + } + } + + } else { - updateConfiguration("HiddenServiceDir","", false); - + updateConfiguration("HiddenServiceDir","", false); + }
saveConfiguration(); - + return true; }
/* private void enableSocks (String socks, boolean safeSocks) throws RemoteException - { - updateConfiguration("SOCKSPort", socks, false); - updateConfiguration("SafeSocks", safeSocks ? "1" : "0", false); - updateConfiguration("TestSocks", "1", false); - updateConfiguration("WarnUnsafeSocks", "1", false); - saveConfiguration(); + { + updateConfiguration("SOCKSPort", socks, false); + updateConfiguration("SafeSocks", safeSocks ? "1" : "0", false); + updateConfiguration("TestSocks", "1", false); + updateConfiguration("WarnUnsafeSocks", "1", false); + saveConfiguration();
}
private void enableTransProxyAndDNSPorts (String transPort, String dnsPort) throws RemoteException { - logMessage ("Transparent Proxying: enabling port..."); - - updateConfiguration("TransPort",transPort,false); - updateConfiguration("DNSPort",dnsPort,false); - updateConfiguration("VirtualAddrNetwork","10.192.0.0/10",false); - updateConfiguration("AutomapHostsOnResolve","1",false); - saveConfiguration(); + logMessage ("Transparent Proxying: enabling port..."); + + updateConfiguration("TransPort",transPort,false); + updateConfiguration("DNSPort",dnsPort,false); + updateConfiguration("VirtualAddrNetwork","10.192.0.0/10",false); + updateConfiguration("AutomapHostsOnResolve","1",false); + saveConfiguration(); }*/
private void blockPlaintextPorts (String portList) throws RemoteException { - - updateConfiguration("RejectPlaintextPorts",portList,false); + updateConfiguration("RejectPlaintextPorts",portList,false); }
//using Google DNS for now as the public DNS server private String writeDNSFile () throws IOException { - File file = new File(appBinHome,"resolv.conf"); - - PrintWriter bw = new PrintWriter(new FileWriter(file)); - bw.println("nameserver 8.8.8.8"); - bw.println("nameserver 8.8.4.4"); - bw.close(); - - return file.getCanonicalPath(); + File file = new File(appBinHome,"resolv.conf"); + + PrintWriter bw = new PrintWriter(new FileWriter(file)); + bw.println("nameserver 8.8.8.8"); + bw.println("nameserver 8.8.4.4"); + bw.close(); + + return file.getCanonicalPath(); + } + + @SuppressLint("NewApi") + @Override + public void onTrimMemory(int level) { + super.onTrimMemory(level); + + switch (level) + { + + case TRIM_MEMORY_BACKGROUND: + debug("trim memory requested: app in the background"); + return; + + /** + public static final int TRIM_MEMORY_BACKGROUND + Added in API level 14 + Level for onTrimMemory(int): the process has gone on to the LRU list. This is a good opportunity to clean up resources that can efficiently and quickly be re-built if the user returns to the app. + Constant Value: 40 (0x00000028) + */ + + case TRIM_MEMORY_COMPLETE: + + debug("trim memory requested: cleanup all memory"); + return; + /** + public static final int TRIM_MEMORY_COMPLETE + Added in API level 14 + Level for onTrimMemory(int): the process is nearing the end of the background LRU list, and if more memory isn't found soon it will be killed. + Constant Value: 80 (0x00000050) + */ + case TRIM_MEMORY_MODERATE: + + debug("trim memory requested: clean up some memory"); + return; + + /** + public static final int TRIM_MEMORY_MODERATE + Added in API level 14 + Level for onTrimMemory(int): the process is around the middle of the background LRU list; freeing memory can help the system keep other processes running later in the list for better overall performance. + Constant Value: 60 (0x0000003c) + */ + + case TRIM_MEMORY_RUNNING_CRITICAL: + + debug("trim memory requested: memory on device is very low and critical"); + return; + /** + public static final int TRIM_MEMORY_RUNNING_CRITICAL + Added in API level 16 + Level for onTrimMemory(int): the process is not an expendable background process, but the device is running extremely low on memory and is about to not be able to keep any background processes running. Your running process should free up as many non-critical resources as it can to allow that memory to be used elsewhere. The next thing that will happen after this is onLowMemory() called to report that nothing at all can be kept in the background, a situation that can start to notably impact the user. + Constant Value: 15 (0x0000000f) + */ + + case TRIM_MEMORY_RUNNING_LOW: + + debug("trim memory requested: memory on device is running low"); + return; + /** + public static final int TRIM_MEMORY_RUNNING_LOW + Added in API level 16 + Level for onTrimMemory(int): the process is not an expendable background process, but the device is running low on memory. Your running process should free up unneeded resources to allow that memory to be used elsewhere. + Constant Value: 10 (0x0000000a) + */ + case TRIM_MEMORY_RUNNING_MODERATE: + + debug("trim memory requested: memory on device is moderate"); + return; + /** + public static final int TRIM_MEMORY_RUNNING_MODERATE + Added in API level 16 + Level for onTrimMemory(int): the process is not an expendable background process, but the device is running moderately low on memory. Your running process may want to release some unneeded resources for use elsewhere. + Constant Value: 5 (0x00000005) + */ + case TRIM_MEMORY_UI_HIDDEN: + + debug("trim memory requested: app is not showing UI anymore"); + return; + + /** + public static final int TRIM_MEMORY_UI_HIDDEN + Level for onTrimMemory(int): the process had been showing a user interface, and is no longer doing so. Large allocations with the UI should be released at this point to allow memory to be better managed. + Constant Value: 20 (0x00000014) + */ + } + }
- @SuppressLint("NewApi") - @Override - public void onTrimMemory(int level) { - super.onTrimMemory(level); - - switch (level) - { - - case TRIM_MEMORY_BACKGROUND: - debug("trim memory requested: app in the background"); - return; - - /** - public static final int TRIM_MEMORY_BACKGROUND - Added in API level 14 - Level for onTrimMemory(int): the process has gone on to the LRU list. This is a good opportunity to clean up resources that can efficiently and quickly be re-built if the user returns to the app. - Constant Value: 40 (0x00000028) - */ - - case TRIM_MEMORY_COMPLETE: - - debug("trim memory requested: cleanup all memory"); - return; - /** - public static final int TRIM_MEMORY_COMPLETE - Added in API level 14 - Level for onTrimMemory(int): the process is nearing the end of the background LRU list, and if more memory isn't found soon it will be killed. - Constant Value: 80 (0x00000050) - */ - case TRIM_MEMORY_MODERATE: - - debug("trim memory requested: clean up some memory"); - return; - - /** - public static final int TRIM_MEMORY_MODERATE - Added in API level 14 - Level for onTrimMemory(int): the process is around the middle of the background LRU list; freeing memory can help the system keep other processes running later in the list for better overall performance. - Constant Value: 60 (0x0000003c) - */ - - case TRIM_MEMORY_RUNNING_CRITICAL: - - debug("trim memory requested: memory on device is very low and critical"); - return; - /** - public static final int TRIM_MEMORY_RUNNING_CRITICAL - Added in API level 16 - Level for onTrimMemory(int): the process is not an expendable background process, but the device is running extremely low on memory and is about to not be able to keep any background processes running. Your running process should free up as many non-critical resources as it can to allow that memory to be used elsewhere. The next thing that will happen after this is onLowMemory() called to report that nothing at all can be kept in the background, a situation that can start to notably impact the user. - Constant Value: 15 (0x0000000f) - */ - - case TRIM_MEMORY_RUNNING_LOW: - - debug("trim memory requested: memory on device is running low"); - return; - /** - public static final int TRIM_MEMORY_RUNNING_LOW - Added in API level 16 - Level for onTrimMemory(int): the process is not an expendable background process, but the device is running low on memory. Your running process should free up unneeded resources to allow that memory to be used elsewhere. - Constant Value: 10 (0x0000000a) - */ - case TRIM_MEMORY_RUNNING_MODERATE: - - debug("trim memory requested: memory on device is moderate"); - return; - /** - public static final int TRIM_MEMORY_RUNNING_MODERATE - Added in API level 16 - Level for onTrimMemory(int): the process is not an expendable background process, but the device is running moderately low on memory. Your running process may want to release some unneeded resources for use elsewhere. - Constant Value: 5 (0x00000005) - */ - case TRIM_MEMORY_UI_HIDDEN: - - debug("trim memory requested: app is not showing UI anymore"); - return; - - /** - public static final int TRIM_MEMORY_UI_HIDDEN - Level for onTrimMemory(int): the process had been showing a user interface, and is no longer doing so. Large allocations with the UI should be released at this point to allow memory to be better managed. - Constant Value: 20 (0x00000014) - */ - } - - } - - @Override - public IBinder onBind(Intent arg0) { - // TODO Auto-generated method stub - return null; - } + @Override + public IBinder onBind(Intent arg0) { + // TODO Auto-generated method stub + return null; + }
} diff --git a/src/org/torproject/android/settings/AppManager.java b/src/org/torproject/android/settings/AppManager.java index 50b0b25..6214307 100644 --- a/src/org/torproject/android/settings/AppManager.java +++ b/src/org/torproject/android/settings/AppManager.java @@ -11,10 +11,7 @@ import java.util.Iterator; import java.util.List; import java.util.StringTokenizer;
- - - -import org.torproject.android.R; +import org.sandroproxy.ony.R; import org.torproject.android.TorConstants; import org.torproject.android.service.TorService; import org.torproject.android.service.TorServiceUtils; diff --git a/src/org/torproject/android/settings/SettingsPreferences.java b/src/org/torproject/android/settings/SettingsPreferences.java index 9a8891d..0fd9a89 100644 --- a/src/org/torproject/android/settings/SettingsPreferences.java +++ b/src/org/torproject/android/settings/SettingsPreferences.java @@ -5,8 +5,8 @@ package org.torproject.android.settings;
import java.util.Locale;
+import org.sandroproxy.ony.R; import org.sufficientlysecure.rootcommands.RootCommands; -import org.torproject.android.R; import org.torproject.android.service.TorServiceUtils;
import android.content.Context; diff --git a/src/org/torproject/android/vpn/OrbotVpnService.java b/src/org/torproject/android/vpn/OrbotVpnService.java index 9a58b66..66d22b8 100644 --- a/src/org/torproject/android/vpn/OrbotVpnService.java +++ b/src/org/torproject/android/vpn/OrbotVpnService.java @@ -20,23 +20,36 @@ import java.io.IOException; import java.net.InetAddress; import java.nio.ByteBuffer; import java.util.Locale; +import java.util.Set;
+import org.sandroproxy.ony.R; +import org.torproject.android.Orbot; +import org.torproject.android.service.TorService; import org.torproject.android.service.TorServiceConstants;
+import com.runjva.sourceforge.jsocks.protocol.ProxyServer; +import com.runjva.sourceforge.jsocks.server.ServerAuthenticatorNone; + +import android.annotation.SuppressLint; import android.annotation.TargetApi; +import android.app.Notification; +import android.app.NotificationManager; import android.app.PendingIntent; +import android.content.Context; import android.content.Intent; import android.net.VpnService; import android.os.Build; import android.os.Handler; import android.os.Message; import android.os.ParcelFileDescriptor; +import android.support.v4.app.NotificationCompat; import android.util.Log; +import android.widget.RemoteViews; import android.widget.Toast;
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public class OrbotVpnService extends VpnService implements Handler.Callback { - private static final String TAG = "OrbotVpnService"; + private static final String TAG = "DrobotVpnService";
private PendingIntent mConfigureIntent;
@@ -48,14 +61,28 @@ public class OrbotVpnService extends VpnService implements Handler.Callback { private ParcelFileDescriptor mInterface;
private int mSocksProxyPort = 9999; - // private ProxyServer mProxyServer; + private ProxyServer mProxyServer;
private final static int VPN_MTU = 1500;
+ private static final int NOTIFY_ID = 10; + private static final int TRANSPROXY_NOTIFY_ID = 20; + private static final int ERROR_NOTIFY_ID = 30; + private static final int HS_NOTIFY_ID = 40; + + private boolean prefPersistNotifications = true; + + private NotificationManager mNotificationManager = null; + private android.support.v4.app.NotificationCompat.Builder mNotifyBuilder; + private Notification mNotification; + private boolean mShowExpandedNotifications = false; + private boolean mNotificationShowing = false; + + @Override public int onStartCommand(Intent intent, int flags, int startId) {
- // The handler is only used to show messages. + // The handler is only used to show messages. if (mHandler == null) { mHandler = new Handler(this); } @@ -63,30 +90,46 @@ public class OrbotVpnService extends VpnService implements Handler.Callback { // Stop the previous session by interrupting the thread. if (mThreadVPN == null || (!mThreadVPN.isAlive())) { - startSocksBypass (); - setupTun2Socks(); + startSocksBypass (); + setupTun2Socks(); }
return START_STICKY; }
- private void startSocksBypass () - { + private void startSocksBypass(){ + mThreadProxy = new Thread () + { + public void run () + { + + try { + mProxyServer = new ProxyServer(new ServerAuthenticatorNone(null, null)); + ProxyServer.setVpnService(OrbotVpnService.this); + mProxyServer.start(mSocksProxyPort, 5, InetAddress.getLocalHost()); + } catch (Exception e) { + Log.d(TAG,"proxy server error: " + e.getLocalizedMessage(),e); + } + } + }; + + mThreadProxy.start(); }
@Override public void onDestroy() { - - - - if (mInterface != null) - try { - mInterface.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + if (mProxyServer != null){ + mProxyServer.stop(); + } + if (mInterface != null){ + try { + mInterface.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } }
@Override @@ -100,152 +143,158 @@ public class OrbotVpnService extends VpnService implements Handler.Callback {
private void setupTun2Socks() {
- mThreadVPN = new Thread () - { - - public void run () - { - if (mInterface == null) - { - // Set the locale to English (or probably any other language that^M - // uses Hindu-Arabic (aka Latin) numerals).^M - // We have found that VpnService.Builder does something locale-dependent^M - // internally that causes errors when the locale uses its own numerals^M - // (i.e., Farsi and Arabic).^M - Locale.setDefault(new Locale("en")); - - Builder builder = new Builder(); - - builder.setMtu(VPN_MTU); - builder.addAddress("10.0.0.1",8); - builder.setSession("OrbotVPN"); - builder.addRoute("0.0.0.0",0); - builder.addRoute("10.0.0.0",8); - //builder.addRoute("192.0.0.0",8); - //builder.addRoute("192.168.43.0",8); - builder.addDnsServer("8.8.8.8"); - - // Create a new interface using the builder and save the parameters. - mInterface = builder.setSession(mSessionName) - .setConfigureIntent(mConfigureIntent) - .establish(); - - try - { - Tun2Socks.Start(mInterface, VPN_MTU, "10.0.0.2", "255.255.255.0", "localhost:" + TorServiceConstants.PORT_SOCKS_DEFAULT, "50.116.51.157:7300", true); - } - catch (Exception e) - { - Log.d(TAG,"tun2Socks has stopped",e); - } - } - } - }; - - mThreadVPN.start(); + mThreadVPN = new Thread () + { + + public void run () + { + if (mInterface == null) + { + // Set the locale to English (or probably any other language that^M + // uses Hindu-Arabic (aka Latin) numerals).^M + // We have found that VpnService.Builder does something locale-dependent^M + // internally that causes errors when the locale uses its own numerals^M + // (i.e., Farsi and Arabic).^M + Locale.setDefault(new Locale("en")); + + Builder builder = new Builder(); + + builder.setMtu(VPN_MTU); + builder.addAddress("10.0.0.1",28); + builder.setSession("DrobotVPN"); + builder.addRoute("0.0.0.0",0); + //builder.addRoute("192.0.0.0",8); + //builder.addRoute("192.168.43.0",8); + + // Create a new interface using the builder and save the parameters. + mInterface = builder.setSession(mSessionName) + .setConfigureIntent(mConfigureIntent) + .establish(); + + try + { + Tun2Socks.Start(mInterface, + VPN_MTU, + "10.0.0.2", + "255.255.255.0", + "127.0.0.1:" + TorServiceConstants.PORT_SOCKS_DEFAULT, + "10.0.0.1:" + String.valueOf(TorServiceConstants.TOR_DNS_PORT_DEFAULT), + true); + + } + catch (Exception e) + { + Log.d(TAG,"tun2Socks has stopped",e); + } + } + } + }; + mThreadVPN.start(); + showToolbarNotification(getString(R.string.status_activated), NOTIFY_ID, R.drawable.ic_stat_tor); }
- @Override - public void onRevoke() { - - new Thread () - { - public void run() - { - try - { - mInterface.close(); - Tun2Socks.Stop(); - } - catch (Exception e) - { - Log.d(TAG,"error stopping tun2socks",e); - } - } - }.start(); - - super.onRevoke(); - - } + @Override + public void onRevoke() { + + new Thread () + { + public void run() + { + try + { + mInterface.close(); + Tun2Socks.Stop(); + } + catch (Exception e) + { + Log.d(TAG,"error stopping tun2socks",e); + } + } + }.start(); + clearNotifications(); + super.onRevoke(); + }
- /* - private void debugPacket(ByteBuffer packet) + private void clearNotifications() { + if (mNotificationManager != null) + mNotificationManager.cancelAll(); + mNotificationShowing = false; + + } + + + @SuppressLint("NewApi") + private void showToolbarNotification (String notifyMsg, int notifyType, int icon) + { + + //Reusable code. + Intent intent = new Intent(OrbotVpnService.this, Orbot.class); + PendingIntent pendIntent = PendingIntent.getActivity(OrbotVpnService.this, 0, intent, 0); + + if (mNotifyBuilder == null) + { + + mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + + if (mNotifyBuilder == null) + { + mNotifyBuilder = new NotificationCompat.Builder(this) + .setContentTitle(getString(R.string.app_name)) + .setSmallIcon(R.drawable.ic_stat_tor); + mNotifyBuilder.setContentIntent(pendIntent); + } + }
- int buffer = packet.get(); - int version; - int headerlength; - version = buffer >> 4; - headerlength = buffer & 0x0F; - headerlength *= 4; - Log.d(TAG, "IP Version:"+version); - Log.d(TAG, "Header Length:"+headerlength); - - String status = ""; - status += "Header Length:"+headerlength; - - buffer = packet.get(); //DSCP + EN - buffer = packet.getChar(); //Total Length - - Log.d(TAG, "Total Length:"+buffer); - - buffer = packet.getChar(); //Identification - Log.d(TAG, "Identification:"+buffer); - - buffer = packet.getChar(); //Flags + Fragment Offset - buffer = packet.get(); //Time to Live - buffer = packet.get(); //Protocol - - Log.d(TAG, "Protocol:"+buffer); - - status += " Protocol:"+buffer; - - buffer = packet.getChar(); //Header checksum - - String sourceIP = ""; - buffer = packet.get(); //Source IP 1st Octet - sourceIP += buffer; - sourceIP += "."; - - buffer = packet.get(); //Source IP 2nd Octet - sourceIP += buffer; - sourceIP += "."; - - buffer = packet.get(); //Source IP 3rd Octet - sourceIP += buffer; - sourceIP += "."; - - buffer = packet.get(); //Source IP 4th Octet - sourceIP += buffer; - - Log.d(TAG, "Source IP:"+sourceIP); - - status += " Source IP:"+sourceIP; - - String destIP = ""; - buffer = packet.get(); //Destination IP 1st Octet - destIP += buffer; - destIP += "."; - - buffer = packet.get(); //Destination IP 2nd Octet - destIP += buffer; - destIP += "."; - - buffer = packet.get(); //Destination IP 3rd Octet - destIP += buffer; - destIP += "."; - - buffer = packet.get(); //Destination IP 4th Octet - destIP += buffer; - - Log.d(TAG, "Destination IP:"+destIP); - - status += " Destination IP:"+destIP; - - //Log.d(TAG, "version:"+packet.getInt()); - //Log.d(TAG, "version:"+packet.getInt()); - //Log.d(TAG, "version:"+packet.getInt()); - - }*/ - + mNotifyBuilder.setContentText(notifyMsg); + mNotifyBuilder.setSmallIcon(icon); + + if (notifyType != NOTIFY_ID) + { + mNotifyBuilder.setTicker(notifyMsg); + // mNotifyBuilder.setLights(Color.GREEN, 1000, 1000); + } + else + { + mNotifyBuilder.setTicker(null); + } + + mNotifyBuilder.setOngoing(prefPersistNotifications); + + mNotification = mNotifyBuilder.build(); + + if (Build.VERSION.SDK_INT >= 16 && mShowExpandedNotifications) { + + + // Create remote view that needs to be set as bigContentView for the notification. + RemoteViews expandedView = new RemoteViews(this.getPackageName(), + R.layout.layout_notification_expanded); + + StringBuffer sbInfo = new StringBuffer(); + + + if (notifyType == NOTIFY_ID) + expandedView.setTextViewText(R.id.text, notifyMsg); + else + { + expandedView.setTextViewText(R.id.info, notifyMsg); + + } + expandedView.setTextViewText(R.id.title, getString(R.string.app_name)); + + expandedView.setImageViewResource(R.id.icon, icon); + mNotification.bigContentView = expandedView; + } + + if (prefPersistNotifications && (!mNotificationShowing)) + { + startForeground(NOTIFY_ID, mNotification); + } + else + { + mNotificationManager.notify(NOTIFY_ID, mNotification); + } + + mNotificationShowing = true; + } } diff --git a/src/org/torproject/android/vpn/Tun2Socks.java b/src/org/torproject/android/vpn/Tun2Socks.java index fa60dbd..a7c638e 100644 --- a/src/org/torproject/android/vpn/Tun2Socks.java +++ b/src/org/torproject/android/vpn/Tun2Socks.java @@ -25,6 +25,7 @@ import java.net.Socket; import android.annotation.TargetApi; import android.os.Build; import android.os.ParcelFileDescriptor; +import android.util.Log;
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) public class Tun2Socks @@ -35,6 +36,8 @@ public class Tun2Socks boolean doVpnProtect(DatagramSocket socket); };
+ private static final String TAG = Tun2Socks.class.getSimpleName(); + private static final boolean LOGD = true;
private static Thread mThread; private static ParcelFileDescriptor mVpnInterfaceFileDescriptor; @@ -61,11 +64,11 @@ public class Tun2Socks boolean udpgwTransparentDNS) {
- if (!mLibLoaded) - { - System.loadLibrary("tun2socks"); - mLibLoaded = true; - } + if (!mLibLoaded) + { + System.loadLibrary("tun2socks"); + mLibLoaded = true; + }
mVpnInterfaceFileDescriptor = vpnInterfaceFileDescriptor; mVpnInterfaceMTU = vpnInterfaceMTU; @@ -76,16 +79,14 @@ public class Tun2Socks mUdpgwTransparentDNS = udpgwTransparentDNS;
if (mVpnInterfaceFileDescriptor != null) - runTun2Socks( - mVpnInterfaceFileDescriptor.detachFd(), - mVpnInterfaceMTU, - mVpnIpAddress, - mVpnNetMask, - mSocksServerAddress, - mUdpgwServerAddress, - mUdpgwTransparentDNS ? 1 : 0); - - + runTun2Socks( + mVpnInterfaceFileDescriptor.detachFd(), + mVpnInterfaceMTU, + mVpnIpAddress, + mVpnNetMask, + mSocksServerAddress, + mUdpgwServerAddress, + mUdpgwTransparentDNS ? 1 : 0); }
public static void Stop() @@ -94,7 +95,23 @@ public class Tun2Socks terminateTun2Socks();
} - + + public static void logTun2Socks( + String level, + String channel, + String msg) + { + String logMsg = level + "(" + channel + "): " + msg; + if (0 == level.compareTo("ERROR")) + { + Log.e(TAG, logMsg); + } + else + { + if (LOGD) Log.d(TAG, logMsg); + } + } + private native static int runTun2Socks( int vpnInterfaceFileDescriptor, int vpnInterfaceMTU, diff --git a/src/org/torproject/android/wizard/ChooseLocaleWizardActivity.java b/src/org/torproject/android/wizard/ChooseLocaleWizardActivity.java index 1a620c1..8325bb5 100644 --- a/src/org/torproject/android/wizard/ChooseLocaleWizardActivity.java +++ b/src/org/torproject/android/wizard/ChooseLocaleWizardActivity.java @@ -2,7 +2,7 @@ package org.torproject.android.wizard;
import java.util.Locale;
-import org.torproject.android.R; +import org.sandroproxy.ony.R; import org.torproject.android.TorConstants; import org.torproject.android.service.TorServiceUtils;
@@ -24,66 +24,66 @@ import android.widget.Toast;
public class ChooseLocaleWizardActivity extends Activity implements TorConstants {
- private int flag = 0; - private ListView listLocales; - - protected void onCreate(Bundle savedInstanceState) - { + private int flag = 0; + private ListView listLocales; + + protected void onCreate(Bundle savedInstanceState) + { super.onCreate(savedInstanceState);
- } - - @Override - protected void onStart() { - - super.onStart(); - setContentView(R.layout.layout_wizard_locale); - - - listLocales = (ListView)findViewById(R.id.wizard_locale_list); - Button next = ((Button)findViewById(R.id.btnWizard2)); - // next.setEnabled(false); - - String[] strLangs = getResources().getStringArray(R.array.languages); - strLangs[0] = Locale.getDefault().getDisplayName(); - ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, strLangs); + } + + @Override + protected void onStart() { + + super.onStart(); + setContentView(R.layout.layout_wizard_locale); + + + listLocales = (ListView)findViewById(R.id.wizard_locale_list); + Button next = ((Button)findViewById(R.id.btnWizard2)); + // next.setEnabled(false); + + String[] strLangs = getResources().getStringArray(R.array.languages); + strLangs[0] = Locale.getDefault().getDisplayName(); + ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, strLangs); listLocales.setAdapter(adapter); - - listLocales.setSelection(0); - - - listLocales.setOnItemClickListener(new OnItemClickListener() { - + + listLocales.setSelection(0); + + + listLocales.setOnItemClickListener(new OnItemClickListener() { +
- @Override - public void onItemClick(AdapterView<?> arg0, View arg1, - int arg2, long arg3) { - - setLocalePref(arg2); - finish(); - startActivity(new Intent(ChooseLocaleWizardActivity.this, LotsaText.class)); - - } - }); - - next.setOnClickListener(new View.OnClickListener() { - - public void onClick(View v) { - setLocalePref(0); - finish(); - startActivity(new Intent(ChooseLocaleWizardActivity.this, LotsaText.class)); + @Override + public void onItemClick(AdapterView<?> arg0, View arg1, + int arg2, long arg3) { + + setLocalePref(arg2); + finish(); + startActivity(new Intent(ChooseLocaleWizardActivity.this, LotsaText.class)); + + } + }); + + next.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + setLocalePref(0); + finish(); + startActivity(new Intent(ChooseLocaleWizardActivity.this, LotsaText.class));
- } - }); - + } + }); +
- - } - - private void setLocalePref(int selId) - { + + } + + private void setLocalePref(int selId) + {
- SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); + SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext());
Configuration config = getResources().getConfiguration();
@@ -91,18 +91,18 @@ public class ChooseLocaleWizardActivity extends Activity implements TorConstants
String lang = localeVals[selId];
- Editor pEdit = prefs.edit(); - pEdit.putString(PREF_DEFAULT_LOCALE, lang); - pEdit.commit(); - Locale locale = null; - + Editor pEdit = prefs.edit(); + pEdit.putString(PREF_DEFAULT_LOCALE, lang); + pEdit.commit(); + Locale locale = null; + if (lang.equals("xx")) { - locale = Locale.getDefault(); + locale = Locale.getDefault();
} else - locale = new Locale(lang); + locale = new Locale(lang);
Locale.setDefault(locale); config.locale = locale; @@ -110,27 +110,27 @@ public class ChooseLocaleWizardActivity extends Activity implements TorConstants
- - } + + }
- @Override - protected void onRestoreInstanceState(Bundle savedInstanceState) { - super.onRestoreInstanceState(savedInstanceState); - } + @Override + protected void onRestoreInstanceState(Bundle savedInstanceState) { + super.onRestoreInstanceState(savedInstanceState); + }
- @Override - protected void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - - } - - //Code to override the back button! - @Override - public boolean onKeyDown(int keyCode, KeyEvent event) { - if(keyCode == KeyEvent.KEYCODE_BACK){ - Toast.makeText(getApplicationContext(), R.string.wizard_exit_at_first_screen_toast, Toast.LENGTH_SHORT).show(); - return true; - } - return false; - } + @Override + protected void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + + } + + //Code to override the back button! + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if(keyCode == KeyEvent.KEYCODE_BACK){ + Toast.makeText(getApplicationContext(), R.string.wizard_exit_at_first_screen_toast, Toast.LENGTH_SHORT).show(); + return true; + } + return false; + } } \ No newline at end of file diff --git a/src/org/torproject/android/wizard/ConfigureTransProxy.java b/src/org/torproject/android/wizard/ConfigureTransProxy.java index ca7f3ac..d8e5a1a 100644 --- a/src/org/torproject/android/wizard/ConfigureTransProxy.java +++ b/src/org/torproject/android/wizard/ConfigureTransProxy.java @@ -1,12 +1,8 @@ package org.torproject.android.wizard;
+import org.sandroproxy.ony.R; import org.torproject.android.Orbot; -import org.torproject.android.R; import org.torproject.android.TorConstants; -import org.torproject.android.R.drawable; -import org.torproject.android.R.id; -import org.torproject.android.R.layout; -import org.torproject.android.R.string; import org.torproject.android.service.TorServiceUtils; import org.torproject.android.settings.AppManager;
diff --git a/src/org/torproject/android/wizard/LotsaText.java b/src/org/torproject/android/wizard/LotsaText.java index 536edab..669aa02 100644 --- a/src/org/torproject/android/wizard/LotsaText.java +++ b/src/org/torproject/android/wizard/LotsaText.java @@ -1,6 +1,6 @@ package org.torproject.android.wizard;
-import org.torproject.android.R; +import org.sandroproxy.ony.R; import org.torproject.android.TorConstants; import org.torproject.android.service.TorServiceUtils;
diff --git a/src/org/torproject/android/wizard/Permissions.java b/src/org/torproject/android/wizard/Permissions.java index 229f5bd..500d785 100644 --- a/src/org/torproject/android/wizard/Permissions.java +++ b/src/org/torproject/android/wizard/Permissions.java @@ -1,7 +1,7 @@ package org.torproject.android.wizard;
+import org.sandroproxy.ony.R; import org.sufficientlysecure.rootcommands.RootCommands; -import org.torproject.android.R; import org.torproject.android.TorConstants; import org.torproject.android.service.TorServiceUtils;
@@ -22,49 +22,49 @@ import android.widget.TextView;
public class Permissions extends Activity implements TorConstants {
- private Context context; - - protected void onCreate(Bundle savedInstanceState) - { + private Context context; + + protected void onCreate(Bundle savedInstanceState) + { super.onCreate(savedInstanceState); context = this;
- } - - @Override - protected void onStart() { - - super.onStart(); - setContentView(R.layout.layout_wizard_permissions); - - stepFourRoot(); - - } - - @Override - protected void onResume() { - super.onResume(); - - - } - - - private void stepFourRoot(){ - - String msg1 = context.getString(R.string.wizard_permissions_root_msg1); - String msg2 = context.getString(R.string.wizard_permissions_root_msg2); - + } + + @Override + protected void onStart() { + + super.onStart(); + setContentView(R.layout.layout_wizard_permissions); + + stepFourRoot(); + + } + + @Override + protected void onResume() { + super.onResume(); + + + } + + + private void stepFourRoot(){ + + String msg1 = context.getString(R.string.wizard_permissions_root_msg1); + String msg2 = context.getString(R.string.wizard_permissions_root_msg2); + TextView txtBody1 = ((TextView)findViewById(R.id.WizardTextBody1)); - txtBody1.setText(msg1); - + txtBody1.setText(msg1); +
TextView txtBody2 = ((TextView)findViewById(R.id.WizardTextBody2)); - txtBody2.setText(msg2); - txtBody2.setVisibility(TextView.VISIBLE); - - Button grantPermissions = ((Button)findViewById(R.id.grantPermissions)); - grantPermissions.setVisibility(Button.VISIBLE); - + txtBody2.setText(msg2); + txtBody2.setVisibility(TextView.VISIBLE); + + Button grantPermissions = ((Button)findViewById(R.id.grantPermissions)); + grantPermissions.setVisibility(Button.VISIBLE); + Button back = ((Button)findViewById(R.id.btnWizard1)); Button next = ((Button)findViewById(R.id.btnWizard2)); next.setEnabled(false); @@ -74,133 +74,133 @@ public class Permissions extends Activity implements TorConstants {
consent.setOnCheckedChangeListener(new OnCheckedChangeListener (){
- public void onCheckedChanged(CompoundButton buttonView, - boolean isChecked) { - - - //this is saying do not use root - - SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); + public void onCheckedChanged(CompoundButton buttonView, + boolean isChecked) { + + + //this is saying do not use root + + SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext());
- Editor pEdit = prefs.edit(); - - pEdit.putBoolean(PREF_TRANSPARENT, false); - pEdit.putBoolean(PREF_TRANSPARENT_ALL, false); - pEdit.putBoolean(PREF_HAS_ROOT, false); - - pEdit.commit(); - - /* - Button next = ((Button)findViewById(R.id.btnWizard2)); - if(isChecked) - next.setEnabled(true); - else - next.setEnabled(false); - */ - - stepFour(); - - } - + Editor pEdit = prefs.edit(); + + pEdit.putBoolean(PREF_TRANSPARENT, false); + pEdit.putBoolean(PREF_TRANSPARENT_ALL, false); + pEdit.putBoolean(PREF_HAS_ROOT, false); + + pEdit.commit(); + + /* + Button next = ((Button)findViewById(R.id.btnWizard2)); + if(isChecked) + next.setEnabled(true); + else + next.setEnabled(false); + */ + + stepFour(); + + } + });
grantPermissions.setOnClickListener(new View.OnClickListener() { - - public void onClick(View v) { - //Check and Install iptables - TorTransProxy.testOwnerModule(this) - - SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); - - boolean hasRoot = RootCommands.rootAccessGiven(); - Editor pEdit = prefs.edit(); - pEdit.putBoolean(PREF_HAS_ROOT,hasRoot); - pEdit.commit(); - - if (!hasRoot) - { + + public void onClick(View v) { + //Check and Install iptables - TorTransProxy.testOwnerModule(this) + + SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext()); + + boolean hasRoot = RootCommands.rootAccessGiven(); + Editor pEdit = prefs.edit(); + pEdit.putBoolean(PREF_HAS_ROOT,hasRoot); + pEdit.commit(); + + if (!hasRoot) + {
- stepFour(); - - } - else - { - finish(); - startActivity(new Intent(Permissions.this, ConfigureTransProxy.class)); - } + stepFour(); + + } + else + { + finish(); + startActivity(new Intent(Permissions.this, ConfigureTransProxy.class)); + }
- - } - }); - - back.setOnClickListener(new View.OnClickListener() { - - public void onClick(View v) { - finish(); - startActivity(new Intent(Permissions.this, LotsaText.class)); - } - }); - - - next.setOnClickListener(new View.OnClickListener() { - - - public void onClick(View v) { - finish(); - startActivity(new Intent(Permissions.this, TipsAndTricks.class)); - } - }); - - } - - private void stepFour(){ - - String title = context.getString(R.string.wizard_permissions_title); - String msg = context.getString(R.string.wizard_permissions_no_root_msg); - - setTitle(title); - + + } + }); + + back.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + finish(); + startActivity(new Intent(Permissions.this, LotsaText.class)); + } + }); + + + next.setOnClickListener(new View.OnClickListener() { + + + public void onClick(View v) { + finish(); + startActivity(new Intent(Permissions.this, TipsAndTricks.class)); + } + }); + + } + + private void stepFour(){ + + String title = context.getString(R.string.wizard_permissions_title); + String msg = context.getString(R.string.wizard_permissions_no_root_msg); + + setTitle(title); + TextView txtBody = ((TextView)findViewById(R.id.WizardTextBody1)); - txtBody.setText(msg); - + txtBody.setText(msg); + Button btn1 = ((Button)findViewById(R.id.btnWizard1)); Button btn2 = ((Button)findViewById(R.id.btnWizard2)); btn2.setEnabled(true);
TextView txtBody2 = ((TextView)findViewById(R.id.WizardTextBody2)); - txtBody2.setVisibility(TextView.GONE); - - Button grantPermissions = ((Button)findViewById(R.id.grantPermissions)); - grantPermissions.setVisibility(Button.GONE); + txtBody2.setVisibility(TextView.GONE); + + Button grantPermissions = ((Button)findViewById(R.id.grantPermissions)); + grantPermissions.setVisibility(Button.GONE);
CheckBox consent = (CheckBox)findViewById(R.id.checkBox); consent.setVisibility(CheckBox.GONE);
- btn1.setOnClickListener(new View.OnClickListener() { - - public void onClick(View v) { - finish(); - startActivity(new Intent(Permissions.this, LotsaText.class)); - } - }); - - btn2.setOnClickListener(new View.OnClickListener() { - - public void onClick(View v) { - finish(); - startActivity(new Intent(Permissions.this, TipsAndTricks.class)); - } - }); - } - - //Code to override the back button! - public boolean onKeyDown(int keyCode, KeyEvent event) { - if(keyCode == KeyEvent.KEYCODE_BACK){ - finish(); - startActivity(new Intent(getBaseContext(), LotsaText.class)); - return true; - } - return false; - } - + btn1.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + finish(); + startActivity(new Intent(Permissions.this, LotsaText.class)); + } + }); + + btn2.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + finish(); + startActivity(new Intent(Permissions.this, TipsAndTricks.class)); + } + }); + } + + //Code to override the back button! + public boolean onKeyDown(int keyCode, KeyEvent event) { + if(keyCode == KeyEvent.KEYCODE_BACK){ + finish(); + startActivity(new Intent(getBaseContext(), LotsaText.class)); + return true; + } + return false; + } + } \ No newline at end of file diff --git a/src/org/torproject/android/wizard/TipsAndTricks.java b/src/org/torproject/android/wizard/TipsAndTricks.java index d10278b..4034c39 100644 --- a/src/org/torproject/android/wizard/TipsAndTricks.java +++ b/src/org/torproject/android/wizard/TipsAndTricks.java @@ -1,7 +1,7 @@ package org.torproject.android.wizard;
+import org.sandroproxy.ony.R; import org.torproject.android.Orbot; -import org.torproject.android.R; import org.torproject.android.TorConstants;
import android.app.Activity; @@ -17,233 +17,229 @@ import android.widget.TextView;
public class TipsAndTricks extends Activity implements TorConstants {
- protected void onCreate(Bundle savedInstanceState) - { + protected void onCreate(Bundle savedInstanceState) + { super.onCreate(savedInstanceState);
- } - - @Override - protected void onStart() { - - super.onStart(); - setContentView(R.layout.layout_wizard_tips); - - stepFive(); - - } - - @Override - protected void onResume() { - super.onResume(); - - - } - - void stepFive(){ - - - String title = getString(R.string.wizard_tips_title); - - setTitle(title); - + } + + @Override + protected void onStart() { + + super.onStart(); + setContentView(R.layout.layout_wizard_tips); + + stepFive(); + + } + + @Override + protected void onResume() { + super.onResume(); + + + } + + void stepFive(){ + + + String title = getString(R.string.wizard_tips_title); + + setTitle(title); + Button btnLink = (Button)findViewById(R.id.WizardRootButtonInstallGibberbot);
btnLink.setOnClickListener(new OnClickListener() { - - public void onClick(View view) { + + public void onClick(View view) {
- String url = getString(R.string.gibberbot_apk_url); - finish(); - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); + String url = getString(R.string.gibberbot_apk_url); + finish(); + startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
- } - }); + } + });
btnLink = (Button)findViewById(R.id.WizardRootButtonInstallOrweb);
btnLink.setOnClickListener(new OnClickListener() { - - public void onClick(View view) { - - String url = getString(R.string.orweb_apk_url); - finish(); - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); + + public void onClick(View view) { + + String url = getString(R.string.orweb_apk_url); + finish(); + startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
- } - }); + } + });
btnLink = (Button)findViewById(R.id.WizardRootButtonInstallDuckgo);
btnLink.setOnClickListener(new OnClickListener() { - - public void onClick(View view) { - - String url = getString(R.string.duckgo_apk_url); - finish(); - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); + + public void onClick(View view) { + + String url = getString(R.string.duckgo_apk_url); + finish(); + startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
- } - }); + } + });
btnLink = (Button)findViewById(R.id.WizardRootButtonInstallFirefox);
btnLink.setOnClickListener(new OnClickListener() { - - public void onClick(View view) { - - String url = getString(R.string.proxymob_setup_url); - finish(); - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); + + public void onClick(View view) { + + String url = getString(R.string.proxymob_setup_url); + finish(); + startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
- } - }); + } + });
btnLink = (Button)findViewById(R.id.WizardRootButtonInstallTwitter);
btnLink.setOnClickListener(new OnClickListener() { - - public void onClick(View view) { - - String url = getString(R.string.twitter_setup_url); - finish(); - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); + + public void onClick(View view) { + + String url = getString(R.string.twitter_setup_url); + finish(); + startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
- } - }); + } + });
btnLink = (Button)findViewById(R.id.WizardRootButtonInstallStoryMaker);
btnLink.setOnClickListener(new OnClickListener() { - - public void onClick(View view) { - - String url = getString(R.string.story_maker_url); - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); + + public void onClick(View view) { + + String url = getString(R.string.story_maker_url); + startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
- } - }); + } + });
btnLink = (Button)findViewById(R.id.WizardRootButtonInstallMartus);
btnLink.setOnClickListener(new OnClickListener() { - - public void onClick(View view) { - - String url = getString(R.string.martus_url); - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); + + public void onClick(View view) { + + String url = getString(R.string.martus_url); + startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
- } - }); + } + });
btnLink = (Button)findViewById(R.id.WizardRootButtonGooglePlay);
btnLink.setOnClickListener(new OnClickListener() { - - public void onClick(View view) { - - String url = getString(R.string.wizard_tips_play_url); - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); + + public void onClick(View view) { + + String url = getString(R.string.wizard_tips_play_url); + startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
- } - }); + } + });
Button back = ((Button)findViewById(R.id.btnWizard1)); Button next = ((Button)findViewById(R.id.btnWizard2));
back.setOnClickListener(new View.OnClickListener() { - - public void onClick(View v) { - finish(); - startActivityForResult(new Intent(TipsAndTricks.this, Permissions.class), 1); - } - }); - - next.setOnClickListener(new View.OnClickListener() { - - public void onClick(View v) { - showWizardFinal(); - } - }); - - } - - private void showWizardFinal () - { - setContentView(R.layout.scrollingtext_buttons_view); - String title = getString(R.string.wizard_final); - String msg = getString(R.string.wizard_final_msg); - - setTitle(title); + + public void onClick(View v) { + finish(); + startActivityForResult(new Intent(TipsAndTricks.this, Permissions.class), 1); + } + }); + + next.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + showWizardFinal(); + } + }); + + } + + private void showWizardFinal () + { + setContentView(R.layout.scrollingtext_buttons_view); + String title = getString(R.string.wizard_final); + String msg = getString(R.string.wizard_final_msg); + + setTitle(title);
TextView txtBody = ((TextView)findViewById(R.id.WizardTextBody)); - txtBody.setText(msg); - + txtBody.setText(msg); + Button btn1 = ((Button)findViewById(R.id.btnWizard1)); Button btn2 = ((Button)findViewById(R.id.btnWizard2));
btn2.setText(getString(R.string.btn_finish)); - btn1.setVisibility(Button.VISIBLE); - - btn1.setOnClickListener(new View.OnClickListener() { - - public void onClick(View v) { - finish(); - startActivity(new Intent(TipsAndTricks.this, Permissions.class)); - } - }); - - btn2.setOnClickListener(new View.OnClickListener() { - - public void onClick(View v) { - finish(); - } - }); - } - - //Code to override the back button! - @Override - public boolean onKeyDown(int keyCode, KeyEvent event) { - if(keyCode == KeyEvent.KEYCODE_BACK){ - finish(); - startActivity(new Intent(getBaseContext(), Permissions.class)); - return true; - } - return false; - } - - /* - private void showWizardFinal () - { - String title = null; - String msg = null; - - - title = context.getString(R.string.wizard_final); - msg = context.getString(R.string.wizard_final_msg); - - DialogInterface.OnClickListener ocListener = new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - context.startActivity(new Intent(context, Orbot.class)); - - } - }; - - - new AlertDialog.Builder(context) - .setIcon(R.drawable.icon) + btn1.setVisibility(Button.VISIBLE); + + btn1.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + finish(); + startActivity(new Intent(TipsAndTricks.this, Permissions.class)); + } + }); + + btn2.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + finish(); + } + }); + } + + //Code to override the back button! + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if(keyCode == KeyEvent.KEYCODE_BACK){ + finish(); + startActivity(new Intent(getBaseContext(), Permissions.class)); + return true; + } + return false; + } + + /* + private void showWizardFinal () + { + String title = null; + String msg = null; + + + title = context.getString(R.string.wizard_final); + msg = context.getString(R.string.wizard_final_msg); + + DialogInterface.OnClickListener ocListener = new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + context.startActivity(new Intent(context, Orbot.class)); + + } + }; + + + new AlertDialog.Builder(context) + .setIcon(R.drawable.icon) .setTitle(title) .setPositiveButton(R.string.button_close, ocListener) .setMessage(msg) .show(); - - - - - }*/ + }*/ } \ No newline at end of file