remove bind service and use localbroadcast instead

this should fix problems with the service being killed on unbind
This commit is contained in:
Nathan Freitas 2014-10-24 01:14:02 -04:00
parent f6ad0fff3d
commit c9bb1c2890
3 changed files with 290 additions and 339 deletions

View File

@ -8,7 +8,6 @@ import static org.torproject.android.TorConstants.TAG;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.Locale; import java.util.Locale;
import org.torproject.android.service.ITorService;
import org.torproject.android.service.TorService; import org.torproject.android.service.TorService;
import org.torproject.android.service.TorServiceConstants; import org.torproject.android.service.TorServiceConstants;
import org.torproject.android.service.TorServiceUtils; import org.torproject.android.service.TorServiceUtils;
@ -20,12 +19,12 @@ import org.torproject.android.wizard.TipsAndTricks;
import android.annotation.TargetApi; import android.annotation.TargetApi;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.app.ProgressDialog; import android.app.ProgressDialog;
import android.content.ComponentName; import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnClickListener;
import android.content.Intent; import android.content.Intent;
import android.content.ServiceConnection; import android.content.IntentFilter;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
@ -38,9 +37,9 @@ import android.net.VpnService;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.os.IBinder;
import android.os.Message; import android.os.Message;
import android.os.RemoteException; import android.os.RemoteException;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBarActivity;
import android.text.ClipboardManager; import android.text.ClipboardManager;
import android.text.Layout; import android.text.Layout;
@ -80,10 +79,6 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
/* Some tracking bits */ /* Some tracking bits */
private int torStatus = TorServiceConstants.STATUS_OFF; //latest status reported from the tor service private int torStatus = TorServiceConstants.STATUS_OFF; //latest status reported from the tor service
/* Tor Service interaction */
/* The primary interface we will be calling on the service. */
ITorService mService = null;
private SharedPreferences mPrefs = null; private SharedPreferences mPrefs = null;
private boolean autoStartFromIntent = false; private boolean autoStartFromIntent = false;
@ -101,23 +96,64 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
appConflictChecker (); appConflictChecker ();
startService ();
// 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"));
startService("init");
}
// 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; ProgressDialog mProgressDialog;
private void startService () private void startService (String action)
{ {
Intent torService = new Intent(this, TorService.class); Intent torService = new Intent(this, TorService.class);
torService.setAction(action);
startService(torService); startService(torService);
bindService(torService,
mConnection, Context.BIND_AUTO_CREATE);
appendLogTextAndScroll("starting Tor background service... ");
mProgressDialog = ProgressDialog.show(this, "", getString(R.string.status_starting_up), true);
} }
@ -365,11 +401,7 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
try try
{ {
if (mService == null) if (torStatus == TorServiceConstants.STATUS_OFF)
{
}
else if (mService.getStatus() == TorServiceConstants.STATUS_OFF)
{ {
if (mItemOnOff != null) if (mItemOnOff != null)
mItemOnOff.setTitle(R.string.menu_stop); mItemOnOff.setTitle(R.string.menu_stop);
@ -593,12 +625,9 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
{ {
autoStartFromIntent = true; autoStartFromIntent = true;
if (mService != null)
{
try { try {
startTor(); startTor();
Intent nResult = new Intent(); Intent nResult = new Intent();
//nResult.putExtra("socks", ); //TODO respond with socks, transport, dns, etc //nResult.putExtra("socks", ); //TODO respond with socks, transport, dns, etc
@ -609,8 +638,6 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
}
} }
else if (action.equals(Intent.ACTION_VIEW)) else if (action.equals(Intent.ACTION_VIEW))
@ -794,6 +821,19 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void startVpnService () { 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();
updateSettings();
Intent intent = VpnService.prepare(this); Intent intent = VpnService.prepare(this);
if (intent != null) { if (intent != null) {
startActivityForResult(intent, REQUEST_VPN); startActivityForResult(intent, REQUEST_VPN);
@ -802,6 +842,19 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
} }
} }
public void stopVpnService ()
{
SharedPreferences prefs = TorServiceUtils.getSharedPrefs(getApplicationContext());
Editor ePrefs = prefs.edit();
ePrefs.remove("pref_proxy_host");
ePrefs.remove("pref_proxy_port");
ePrefs.remove("pref_proxy_username");
ePrefs.remove("pref_proxy_password");
ePrefs.commit();
updateSettings();
}
@Override @Override
protected void onActivityResult(int request, int response, Intent data) { protected void onActivityResult(int request, int response, Intent data) {
@ -812,9 +865,8 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
{ {
if (data != null && data.getBooleanExtra("transproxywipe", false)) if (data != null && data.getBooleanExtra("transproxywipe", false))
{ {
try {
boolean result = mService.flushTransProxy(); boolean result = flushTransProxy();
if (result) if (result)
{ {
@ -828,18 +880,11 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
Toast.makeText(this, R.string.you_do_not_have_root_access_enabled, Toast.LENGTH_SHORT).show(); Toast.makeText(this, R.string.you_do_not_have_root_access_enabled, Toast.LENGTH_SHORT).show();
} }
} catch (RemoteException e) {
e.printStackTrace();
}
} }
else if (torStatus == TorServiceConstants.STATUS_ON) else if (torStatus == TorServiceConstants.STATUS_ON)
{ {
try { updateSettings();
mService.processSettings();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(this, R.string.you_may_need_to_stop_and_start_orbot_for_settings_change_to_be_enabled_, Toast.LENGTH_SHORT).show(); Toast.makeText(this, R.string.you_may_need_to_stop_and_start_orbot_for_settings_change_to_be_enabled_, Toast.LENGTH_SHORT).show();
} }
@ -851,6 +896,18 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
} }
} }
private boolean flushTransProxy ()
{
startService("flush");
return true;
}
private boolean updateSettings ()
{
//todo send service command
startService("update");
return true;
}
@Override @Override
protected void onResume() { protected void onResume() {
@ -858,23 +915,8 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
setLocale(); setLocale();
if (mService != null)
{
try {
torStatus = mService.getStatus();
if (torStatus == 0) //make sure we don't have a tor process already running
mService.checkAndInit();
handleIntents(); handleIntents();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateStatus("");
}
} }
@ -917,17 +959,11 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
private void updateStatus (String torServiceMsg) private void updateStatus (String torServiceMsg)
{ {
int newTorStatus = torStatus;
if (mService != null)
try {newTorStatus = mService.getStatus();}
catch (RemoteException e){}
//now update the layout_main UI based on the status //now update the layout_main UI based on the status
if (imgStatus != null) if (imgStatus != null)
{ {
if (newTorStatus == TorServiceConstants.STATUS_ON) if (torStatus == TorServiceConstants.STATUS_ON)
{ {
imgStatus.setImageResource(R.drawable.toron); imgStatus.setImageResource(R.drawable.toron);
@ -967,7 +1003,7 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
} }
} }
else if (newTorStatus == TorServiceConstants.STATUS_CONNECTING) else if (torStatus == TorServiceConstants.STATUS_CONNECTING)
{ {
imgStatus.setImageResource(R.drawable.torstarting); imgStatus.setImageResource(R.drawable.torstarting);
@ -984,7 +1020,7 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
} }
else if (newTorStatus == TorServiceConstants.STATUS_OFF) else if (torStatus == TorServiceConstants.STATUS_OFF)
{ {
imgStatus.setImageResource(R.drawable.toroff); imgStatus.setImageResource(R.drawable.toroff);
lblStatus.setText(getString(R.string.status_disabled) + "\n" + getString(R.string.press_to_start)); lblStatus.setText(getString(R.string.status_disabled) + "\n" + getString(R.string.press_to_start));
@ -996,9 +1032,6 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
} }
torStatus = newTorStatus;
} }
@ -1009,14 +1042,15 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
{ {
startService ("start");
torStatus = TorServiceConstants.STATUS_CONNECTING;
mTxtOrbotLog.setText(""); mTxtOrbotLog.setText("");
if (mService != null)
{
// this is a bit of a strange/old/borrowed code/design i used to change the service state // this is a bit of a strange/old/borrowed code/design i used to change the service state
// not sure it really makes sense when what we want to say is just "startTor" // not sure it really makes sense when what we want to say is just "startTor"
mService.setProfile(TorServiceConstants.STATUS_ON); //this means turn on // mService.setProfile(TorServiceConstants.STATUS_ON); //this means turn on
//here we update the UI which is a bit sloppy and mixed up code wise //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 //might be best to just call updateStatus() instead of directly manipulating UI in this method - yep makes sense
@ -1028,12 +1062,6 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
msg.getData().putString(HANDLER_TOR_MSG, getString(R.string.status_starting_up)); msg.getData().putString(HANDLER_TOR_MSG, getString(R.string.status_starting_up));
mHandler.sendMessage(msg); mHandler.sendMessage(msg);
}
else
{
showAlert(getString(R.string.error),"Tor Service has not started yet. Please wait and try again.",false);
}
} }
@ -1041,16 +1069,14 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
//now we stop Tor! amazing! //now we stop Tor! amazing!
private void stopTor () throws RemoteException private void stopTor () throws RemoteException
{ {
if (mService != null)
{ startService ("stop");
mService.setProfile(TorServiceConstants.STATUS_OFF); torStatus = TorServiceConstants.STATUS_OFF;
// mService.setProfile(TorServiceConstants.STATUS_OFF);
Message msg = mHandler.obtainMessage(TorServiceConstants.DISABLE_TOR_MSG); Message msg = mHandler.obtainMessage(TorServiceConstants.DISABLE_TOR_MSG);
mHandler.sendMessage(msg); mHandler.sendMessage(msg);
updateStatus("");
}
} }
@ -1110,6 +1136,7 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
{ {
try try
{ {
/**
if (mService != null) if (mService != null)
{ {
for (String log : mService.getLog()) for (String log : mService.getLog())
@ -1142,7 +1169,7 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
if (mService != null) if (mService != null)
torStatus = mService.getStatus(); torStatus = mService.getStatus();
} }**/
} }
catch (Exception re) catch (Exception re)
{ {
@ -1227,60 +1254,6 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
// we should use this to activity monitor unbind so that we don't have to call // we should use this to activity monitor unbind so that we don't have to call
// bindService() a million times // bindService() a million times
private final ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
if (mProgressDialog != null && mProgressDialog.isShowing())
mProgressDialog.dismiss();
appendLogTextAndScroll("Tor background service connected.");
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. We are communicating with our
// service through an IDL interface, so get a client-side
// representation of that from the raw service object.
mService = ITorService.Stub.asInterface(service);
// We want to monitor the service for as long as we are
// connected to it.
try {
torStatus = mService.getStatus();
initUpdates();
handleIntents();
updateStatus("");
} catch (RemoteException e) {
// In this case the service has crashed before we could even
// do anything with it; we can count on soon being
// disconnected (and then reconnected if it can be restarted)
// so there is no need to do anything here.
Log.d(TAG,"error registering callback to service",e);
}
}
public void onServiceDisconnected(ComponentName className) {
appendLogTextAndScroll("Tor background service disconnected.");
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mKeepUpdating = false;
mService = null;
}
};
private void setLocale () private void setLocale ()
{ {
@ -1300,12 +1273,8 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
@Override @Override
protected void onDestroy() { protected void onDestroy() {
super.onDestroy(); super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
if (mConnection != null && mService != null)
{
unbindService(mConnection);
mService = null;
}
} }
public class DataCount { public class DataCount {
@ -1354,8 +1323,10 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
public void spinOrbot (float direction) public void spinOrbot (float direction)
{ {
try { startService ("newnym");
mService.newIdentity(); //request a new identity
//mService.newIdentity(); //request a new identity
//TODO trigger newnym
Toast.makeText(this, R.string.newnym, Toast.LENGTH_SHORT).show(); Toast.makeText(this, R.string.newnym, Toast.LENGTH_SHORT).show();
@ -1367,10 +1338,7 @@ public class Orbot extends ActionBarActivity implements TorConstants, OnLongClic
rotation.setRepeatCount(0); rotation.setRepeatCount(0);
imgStatus.startAnimation(rotation); imgStatus.startAnimation(rotation);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
class MyGestureDetector extends SimpleOnGestureListener { class MyGestureDetector extends SimpleOnGestureListener {

View File

@ -38,7 +38,6 @@ import java.util.StringTokenizer;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import java.util.regex.Pattern;
import net.freehaven.tor.control.ConfigEntry; import net.freehaven.tor.control.ConfigEntry;
import net.freehaven.tor.control.EventHandler; import net.freehaven.tor.control.EventHandler;
@ -74,6 +73,7 @@ import android.os.IBinder;
import android.os.RemoteException; import android.os.RemoteException;
import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder; import android.support.v4.app.NotificationCompat.Builder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log; import android.util.Log;
import android.widget.RemoteViews; import android.widget.RemoteViews;
@ -183,6 +183,7 @@ public class TorService extends Service implements TorServiceConstants, TorConst
sendCallbackLogMessage (getString(R.string.found_existing_tor_process)); sendCallbackLogMessage (getString(R.string.found_existing_tor_process));
mCurrentStatus = STATUS_ON; mCurrentStatus = STATUS_ON;
sendCallbackStatus(mCurrentStatus);
return true; return true;
} }
@ -339,7 +340,9 @@ public class TorService extends Service implements TorServiceConstants, TorConst
try try
{ {
initialize();
//android.os.Debug.waitForDebugger();
new Thread (new TorStarter(intent)).start(); new Thread (new TorStarter(intent)).start();
return Service.START_STICKY; return Service.START_STICKY;
@ -367,21 +370,40 @@ public class TorService extends Service implements TorServiceConstants, TorConst
try try
{ {
if (mNotificationManager == null)
{
IntentFilter mNetworkStateFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mNetworkStateReceiver , mNetworkStateFilter);
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
//if this is a start on boot launch turn tor on //if this is a start on boot launch turn tor on
if (mIntent != null && mIntent.getAction()!=null && mIntent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) if (mIntent != null)
{
String action = mIntent.getAction();
if (action!=null)
{
if(action.equals(Intent.ACTION_BOOT_COMPLETED)||action.equals("start"))
{ {
setTorProfile(STATUS_ON); setTorProfile(STATUS_ON);
} }
else if (action.equals("stop"))
{
setTorProfile(STATUS_OFF);
}
else if (action.equals("init"))
{
sendCallbackStatus(mCurrentStatus);
}
else if (action.equals("newnym"))
{
newIdentity();
}
else if (action.equals("flush"))
{
flushTransparentProxyRules();
}
else if (action.equals("update"))
{
processSettings();
}
}
}
} }
catch (Exception e) catch (Exception e)
{ {
@ -417,20 +439,21 @@ public class TorService extends Service implements TorServiceConstants, TorConst
stopForeground(true); stopForeground(true);
mCurrentStatus = STATUS_OFF; mCurrentStatus = STATUS_OFF;
sendCallbackStatus(mCurrentStatus);
if (mHasRoot && mEnableTransparentProxy) if (mHasRoot && mEnableTransparentProxy)
disableTransparentProxy(Shell.startRootShell()); disableTransparentProxy(Shell.startRootShell());
clearNotifications(); clearNotifications();
sendCallbackStatusMessage(getString(R.string.status_disabled)); sendCallbackLogMessage(getString(R.string.status_disabled));
} }
catch (Exception e) catch (Exception e)
{ {
Log.d(TAG, "An error occured stopping Tor",e); Log.d(TAG, "An error occured stopping Tor",e);
logNotice("An error occured stopping Tor: " + e.getMessage()); logNotice("An error occured stopping Tor: " + e.getMessage());
sendCallbackStatusMessage(getString(R.string.something_bad_happened)); sendCallbackLogMessage(getString(R.string.something_bad_happened));
} }
} }
@ -571,6 +594,18 @@ public class TorService extends Service implements TorServiceConstants, TorConst
{ {
try try
{ {
if (mNotificationManager == null)
{
IntentFilter mNetworkStateFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mNetworkStateReceiver , mNetworkStateFilter);
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
initBinariesAndDirectories(); initBinariesAndDirectories();
updateSettings(); updateSettings();
@ -739,6 +774,7 @@ public class TorService extends Service implements TorServiceConstants, TorConst
{ {
mCurrentStatus = STATUS_CONNECTING; mCurrentStatus = STATUS_CONNECTING;
sendCallbackStatus(mCurrentStatus);
if (fileTor == null) if (fileTor == null)
initBinariesAndDirectories(); initBinariesAndDirectories();
@ -751,7 +787,7 @@ public class TorService extends Service implements TorServiceConstants, TorConst
updateSettings (); updateSettings ();
logNotice(getString(R.string.status_starting_up)); logNotice(getString(R.string.status_starting_up));
sendCallbackStatusMessage(getString(R.string.status_starting_up)); sendCallbackLogMessage(getString(R.string.status_starting_up));
boolean success = runTorShellCmd(); boolean success = runTorShellCmd();
@ -899,7 +935,7 @@ public class TorService extends Service implements TorServiceConstants, TorConst
updateTorConfigFile(); updateTorConfigFile();
sendCallbackStatusMessage(getString(R.string.status_starting_up)); sendCallbackLogMessage(getString(R.string.status_starting_up));
if (mShellTor != null) if (mShellTor != null)
mShellTor.close(); mShellTor.close();
@ -947,7 +983,7 @@ public class TorService extends Service implements TorServiceConstants, TorConst
if (mLastProcessId == -1) if (mLastProcessId == -1)
{ {
logNotice(getString(R.string.couldn_t_start_tor_process_) + "; exit=" + shellTorCommand.getExitCode() + ": " + shellTorCommand.getOutput()); logNotice(getString(R.string.couldn_t_start_tor_process_) + "; exit=" + shellTorCommand.getExitCode() + ": " + shellTorCommand.getOutput());
sendCallbackStatusMessage(getString(R.string.couldn_t_start_tor_process_)); sendCallbackLogMessage(getString(R.string.couldn_t_start_tor_process_));
throw new Exception ("Unable to start Tor"); throw new Exception ("Unable to start Tor");
} }
@ -1088,7 +1124,7 @@ public class TorService extends Service implements TorServiceConstants, TorConst
logNotice( "SUCCESS - authenticated to control port."); logNotice( "SUCCESS - authenticated to control port.");
sendCallbackStatusMessage(getString(R.string.tor_process_starting) + ' ' + getString(R.string.tor_process_complete)); sendCallbackLogMessage(getString(R.string.tor_process_starting) + ' ' + getString(R.string.tor_process_complete));
addEventHandler(); addEventHandler();
@ -1104,6 +1140,7 @@ public class TorService extends Service implements TorServiceConstants, TorConst
}*/ }*/
mCurrentStatus = STATUS_CONNECTING; mCurrentStatus = STATUS_CONNECTING;
sendCallbackStatus(mCurrentStatus);
String confSocks = conn.getInfo("net/listeners/socks"); String confSocks = conn.getInfo("net/listeners/socks");
StringTokenizer st = new StringTokenizer(confSocks," "); StringTokenizer st = new StringTokenizer(confSocks," ");
@ -1340,7 +1377,7 @@ public class TorService extends Service implements TorServiceConstants, TorConst
if (profile == STATUS_ON) if (profile == STATUS_ON)
{ {
sendCallbackStatusMessage (getString(R.string.status_starting_up)); sendCallbackLogMessage (getString(R.string.status_starting_up));
try try
{ {
@ -1352,17 +1389,21 @@ public class TorService extends Service implements TorServiceConstants, TorConst
logException("Unable to start Tor: " + e.toString(),e); logException("Unable to start Tor: " + e.toString(),e);
mCurrentStatus = STATUS_OFF; mCurrentStatus = STATUS_OFF;
sendCallbackStatus(mCurrentStatus);
showToolbarNotification(getString(R.string.unable_to_start_tor) + ": " + e.getMessage(), ERROR_NOTIFY_ID, R.drawable.ic_stat_notifyerr); showToolbarNotification(getString(R.string.unable_to_start_tor) + ": " + e.getMessage(), ERROR_NOTIFY_ID, R.drawable.ic_stat_notifyerr);
stopTor(); stopTor();
} }
} }
else else if (profile == STATUS_OFF)
{ {
sendCallbackStatusMessage (getString(R.string.status_shutting_down)); sendCallbackLogMessage (getString(R.string.status_shutting_down));
stopTor(); stopTor();
mCurrentStatus = STATUS_OFF; mCurrentStatus = STATUS_OFF;
sendCallbackStatus(mCurrentStatus);
} }
} }
@ -1375,6 +1416,8 @@ public class TorService extends Service implements TorServiceConstants, TorConst
if (msg.indexOf(TOR_CONTROL_PORT_MSG_BOOTSTRAP_DONE)!=-1) if (msg.indexOf(TOR_CONTROL_PORT_MSG_BOOTSTRAP_DONE)!=-1)
{ {
mCurrentStatus = STATUS_ON; mCurrentStatus = STATUS_ON;
sendCallbackStatus(mCurrentStatus);
showToolbarNotification(getString(R.string.status_activated), NOTIFY_ID, R.drawable.ic_stat_tor); showToolbarNotification(getString(R.string.status_activated), NOTIFY_ID, R.drawable.ic_stat_tor);
} }
@ -1457,6 +1500,8 @@ public class TorService extends Service implements TorServiceConstants, TorConst
lastWritten = written; lastWritten = written;
lastRead = read; lastRead = read;
sendCallbackStatusMessage(lastWritten, lastRead, mTotalTrafficWritten, mTotalTrafficRead);
} }
private String formatCount(long count) { private String formatCount(long count) {
@ -1522,6 +1567,9 @@ public class TorService extends Service implements TorServiceConstants, TorConst
if (mCurrentStatus == STATUS_CONNECTING) if (mCurrentStatus == STATUS_CONNECTING)
mCurrentStatus = STATUS_ON; mCurrentStatus = STATUS_ON;
sendCallbackStatus(mCurrentStatus);
logNotice(sb.toString()); logNotice(sb.toString());
} }
@ -1646,18 +1694,7 @@ public class TorService extends Service implements TorServiceConstants, TorConst
return node; return node;
} }
public IBinder onBind(Intent intent) {
logNotice("Background service is bound. Status=" + mCurrentStatus);
return mBinder;
}
@Override
public void onRebind(Intent intent) {
super.onRebind(intent);
}
public boolean checkAndInitImpl () public boolean checkAndInitImpl ()
{ {
@ -1678,35 +1715,6 @@ public class TorService extends Service implements TorServiceConstants, TorConst
return false; return false;
} }
/**
* The IRemoteInterface is defined through IDL
*/
private final ITorService.Stub mBinder = new ITorService.Stub() {
public int getStatus () {
return getTorStatus();
}
public boolean checkAndInit () {
return checkAndInitImpl();
}
public void setProfile (final int profileNew)
{
new Thread(new Runnable()
{
@Override
public void run() {
setTorProfile(profileNew);
}
}).start();
}
public void processSettings () public void processSettings ()
@ -1924,76 +1932,49 @@ public class TorService extends Service implements TorServiceConstants, TorConst
} }
@Override
public String[] getStatusMessage() throws RemoteException {
synchronized (mStatusBuffer)
{
String[] status = mStatusBuffer.toArray(new String[mStatusBuffer.size()]);
mStatusBuffer.clear();
return status;
}
}
@Override
public String[] getLog() throws RemoteException {
synchronized (mLogBuffer)
{
String[] status = mLogBuffer.toArray(new String[mLogBuffer.size()]);
mLogBuffer.clear();
return status;
}
}
@Override
public long[] getBandwidth() throws RemoteException {
long[] bw = {lastRead,lastWritten,mTotalTrafficRead,mTotalTrafficWritten};
return bw;
}
@Override
public boolean flushTransProxy () throws RemoteException {
try
{
return flushTransparentProxyRules();
}
catch (Exception e)
{
Log.e(TAG,"error in transproxy",e);
return false;
}
}
};
private ArrayList<String> mStatusBuffer = new ArrayList<String>();
private void sendCallbackStatusMessage (String newStatus)
{
mStatusBuffer.add(newStatus);
}
private void sendCallbackStatusMessage (long upload, long download, long written, long read) 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);
} }
private ArrayList<String> mLogBuffer = new ArrayList<String>(); // private ArrayList<String> mLogBuffer = new ArrayList<String>();
private void sendCallbackLogMessage (String logMessage) private void sendCallbackLogMessage (String logMessage)
{ {
mLogBuffer.add(logMessage); 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);
}
/* /*
* Another way to do this would be to use the Observer pattern by defining the * Another way to do this would be to use the Observer pattern by defining the
* BroadcastReciever in the Android manifest. * BroadcastReciever in the Android manifest.
@ -2021,11 +2002,7 @@ public class TorService extends Service implements TorServiceConstants, TorConst
if (doNetworKSleep) if (doNetworKSleep)
{ {
try { try {
if (mBinder != null) updateConfiguration("DisableNetwork", mConnectivity ? "0" : "1", false);
{
mBinder.updateConfiguration("DisableNetwork", mConnectivity ? "0" : "1", false);
mBinder.saveConfiguration();
}
if (mCurrentStatus != STATUS_OFF) if (mCurrentStatus != STATUS_OFF)
{ {
@ -2102,21 +2079,21 @@ public class TorService extends Service implements TorServiceConstants, TorConst
if ((proxyHost != null && proxyHost.length()>0) && (proxyPort != null && proxyPort.length() > 0)) if ((proxyHost != null && proxyHost.length()>0) && (proxyPort != null && proxyPort.length() > 0))
{ {
mBinder.updateConfiguration(proxyType + "Proxy", proxyHost + ':' + proxyPort, false); updateConfiguration(proxyType + "Proxy", proxyHost + ':' + proxyPort, false);
if (proxyUser != null && proxyPass != null) if (proxyUser != null && proxyPass != null)
{ {
if (proxyType.equalsIgnoreCase("socks5")) if (proxyType.equalsIgnoreCase("socks5"))
{ {
mBinder.updateConfiguration("Socks5ProxyUsername", proxyUser, false); updateConfiguration("Socks5ProxyUsername", proxyUser, false);
mBinder.updateConfiguration("Socks5ProxyPassword", proxyPass, false); updateConfiguration("Socks5ProxyPassword", proxyPass, false);
} }
else else
mBinder.updateConfiguration(proxyType + "ProxyAuthenticator", proxyUser + ':' + proxyPort, false); updateConfiguration(proxyType + "ProxyAuthenticator", proxyUser + ':' + proxyPort, false);
} }
else if (proxyPass != null) else if (proxyPass != null)
mBinder.updateConfiguration(proxyType + "ProxyAuthenticator", proxyUser + ':' + proxyPort, false); updateConfiguration(proxyType + "ProxyAuthenticator", proxyUser + ':' + proxyPort, false);
@ -2138,8 +2115,8 @@ public class TorService extends Service implements TorServiceConstants, TorConst
} }
mBinder.updateConfiguration("GeoIPFile", fileGeoIP.getCanonicalPath(), false); updateConfiguration("GeoIPFile", fileGeoIP.getCanonicalPath(), false);
mBinder.updateConfiguration("GeoIPv6File", fileGeoIP6.getCanonicalPath(), false); updateConfiguration("GeoIPv6File", fileGeoIP6.getCanonicalPath(), false);
} }
catch (Exception e) catch (Exception e)
@ -2150,10 +2127,10 @@ public class TorService extends Service implements TorServiceConstants, TorConst
} }
} }
mBinder.updateConfiguration("EntryNodes", entranceNodes, false); updateConfiguration("EntryNodes", entranceNodes, false);
mBinder.updateConfiguration("ExitNodes", exitNodes, false); updateConfiguration("ExitNodes", exitNodes, false);
mBinder.updateConfiguration("ExcludeNodes", excludeNodes, false); updateConfiguration("ExcludeNodes", excludeNodes, false);
mBinder.updateConfiguration("StrictNodes", enableStrictNodes ? "1" : "0", false); updateConfiguration("StrictNodes", enableStrictNodes ? "1" : "0", false);
if (useBridges) if (useBridges)
{ {
@ -2188,7 +2165,7 @@ public class TorService extends Service implements TorServiceConstants, TorConst
{ {
String bridgeConfigLine = st.nextToken().trim(); String bridgeConfigLine = st.nextToken().trim();
debug("Adding bridge: " + bridgeConfigLine); debug("Adding bridge: " + bridgeConfigLine);
mBinder.updateConfiguration(bridgeCfgKey, bridgeConfigLine, false); updateConfiguration(bridgeCfgKey, bridgeConfigLine, false);
} }
@ -2201,7 +2178,7 @@ public class TorService extends Service implements TorServiceConstants, TorConst
debug ("Using OBFUSCATED bridges: " + bridgeConfig); debug ("Using OBFUSCATED bridges: " + bridgeConfig);
mBinder.updateConfiguration("ClientTransportPlugin",bridgeConfig, false); updateConfiguration("ClientTransportPlugin",bridgeConfig, false);
} }
else else
{ {
@ -2210,16 +2187,16 @@ public class TorService extends Service implements TorServiceConstants, TorConst
mBinder.updateConfiguration("UpdateBridgesFromAuthority", "0", false); updateConfiguration("UpdateBridgesFromAuthority", "0", false);
mBinder.updateConfiguration("UseBridges", "1", false); updateConfiguration("UseBridges", "1", false);
} }
else else
{ {
mBinder.updateConfiguration("UseBridges", "0", false); updateConfiguration("UseBridges", "0", false);
} }
@ -2230,12 +2207,12 @@ public class TorService extends Service implements TorServiceConstants, TorConst
String ReachableAddressesPorts = String ReachableAddressesPorts =
prefs.getString(TorConstants.PREF_REACHABLE_ADDRESSES_PORTS, "*:80,*:443"); prefs.getString(TorConstants.PREF_REACHABLE_ADDRESSES_PORTS, "*:80,*:443");
mBinder.updateConfiguration("ReachableAddresses", ReachableAddressesPorts, false); updateConfiguration("ReachableAddresses", ReachableAddressesPorts, false);
} }
else else
{ {
mBinder.updateConfiguration("ReachableAddresses", "", false); updateConfiguration("ReachableAddresses", "", false);
} }
} }
catch (Exception e) catch (Exception e)
@ -2254,17 +2231,17 @@ public class TorService extends Service implements TorServiceConstants, TorConst
String dnsFile = writeDNSFile (); String dnsFile = writeDNSFile ();
mBinder.updateConfiguration("ServerDNSResolvConfFile", dnsFile, false); updateConfiguration("ServerDNSResolvConfFile", dnsFile, false);
mBinder.updateConfiguration("ORPort", ORPort + "", false); updateConfiguration("ORPort", ORPort + "", false);
mBinder.updateConfiguration("Nickname", nickname, false); updateConfiguration("Nickname", nickname, false);
mBinder.updateConfiguration("ExitPolicy", "reject *:*", false); updateConfiguration("ExitPolicy", "reject *:*", false);
} }
else else
{ {
mBinder.updateConfiguration("ORPort", "", false); updateConfiguration("ORPort", "", false);
mBinder.updateConfiguration("Nickname", "", false); updateConfiguration("Nickname", "", false);
mBinder.updateConfiguration("ExitPolicy", "", false); updateConfiguration("ExitPolicy", "", false);
} }
} }
catch (Exception e) catch (Exception e)
@ -2279,7 +2256,7 @@ public class TorService extends Service implements TorServiceConstants, TorConst
{ {
logNotice("hidden services are enabled"); logNotice("hidden services are enabled");
//mBinder.updateConfiguration("RendPostPeriod", "600 seconds", false); //possible feature to investigate //updateConfiguration("RendPostPeriod", "600 seconds", false); //possible feature to investigate
String hsPorts = prefs.getString("pref_hs_ports",""); String hsPorts = prefs.getString("pref_hs_ports","");
@ -2305,8 +2282,8 @@ public class TorService extends Service implements TorServiceConstants, TorConst
debug("Adding hidden service on port: " + hsPortConfig); debug("Adding hidden service on port: " + hsPortConfig);
mBinder.updateConfiguration("HiddenServiceDir",hsDirPath, false); updateConfiguration("HiddenServiceDir",hsDirPath, false);
mBinder.updateConfiguration("HiddenServicePort",hsPortConfig, false); updateConfiguration("HiddenServicePort",hsPortConfig, false);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
@ -2320,11 +2297,11 @@ public class TorService extends Service implements TorServiceConstants, TorConst
} }
else else
{ {
mBinder.updateConfiguration("HiddenServiceDir","", false); updateConfiguration("HiddenServiceDir","", false);
} }
mBinder.saveConfiguration(); saveConfiguration();
return true; return true;
} }
@ -2332,11 +2309,11 @@ public class TorService extends Service implements TorServiceConstants, TorConst
/* /*
private void enableSocks (String socks, boolean safeSocks) throws RemoteException private void enableSocks (String socks, boolean safeSocks) throws RemoteException
{ {
mBinder.updateConfiguration("SOCKSPort", socks, false); updateConfiguration("SOCKSPort", socks, false);
mBinder.updateConfiguration("SafeSocks", safeSocks ? "1" : "0", false); updateConfiguration("SafeSocks", safeSocks ? "1" : "0", false);
mBinder.updateConfiguration("TestSocks", "1", false); updateConfiguration("TestSocks", "1", false);
mBinder.updateConfiguration("WarnUnsafeSocks", "1", false); updateConfiguration("WarnUnsafeSocks", "1", false);
mBinder.saveConfiguration(); saveConfiguration();
} }
@ -2344,17 +2321,17 @@ public class TorService extends Service implements TorServiceConstants, TorConst
{ {
logMessage ("Transparent Proxying: enabling port..."); logMessage ("Transparent Proxying: enabling port...");
mBinder.updateConfiguration("TransPort",transPort,false); updateConfiguration("TransPort",transPort,false);
mBinder.updateConfiguration("DNSPort",dnsPort,false); updateConfiguration("DNSPort",dnsPort,false);
mBinder.updateConfiguration("VirtualAddrNetwork","10.192.0.0/10",false); updateConfiguration("VirtualAddrNetwork","10.192.0.0/10",false);
mBinder.updateConfiguration("AutomapHostsOnResolve","1",false); updateConfiguration("AutomapHostsOnResolve","1",false);
mBinder.saveConfiguration(); saveConfiguration();
}*/ }*/
private void blockPlaintextPorts (String portList) throws RemoteException private void blockPlaintextPorts (String portList) throws RemoteException
{ {
mBinder.updateConfiguration("RejectPlaintextPorts",portList,false); updateConfiguration("RejectPlaintextPorts",portList,false);
} }
//using Google DNS for now as the public DNS server //using Google DNS for now as the public DNS server
@ -2456,5 +2433,11 @@ public class TorService extends Service implements TorServiceConstants, TorConst
} }
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
} }

View File

@ -76,7 +76,7 @@ public interface TorServiceConstants {
public static final int DISABLE_TOR_MSG = 3; public static final int DISABLE_TOR_MSG = 3;
public static final int LOG_MSG = 4; public static final int LOG_MSG = 4;
public static final String BINARY_TOR_VERSION = "0.2.5.7-openssl1.0.1i"; public static final String BINARY_TOR_VERSION = "0.2.5.8-openssl1.0.1i";
public static final String PREF_BINARY_TOR_VERSION_INSTALLED = "BINARY_TOR_VERSION_INSTALLED"; public static final String PREF_BINARY_TOR_VERSION_INSTALLED = "BINARY_TOR_VERSION_INSTALLED";
//obfsproxy //obfsproxy