/
TorService.java
1973 lines (1502 loc) · 67.3 KB
/
TorService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2009-2011, Nathan Freitas, Orbot / The Guardian Project - https://guardianproject.info/apps/orbot */
/* See LICENSE for licensing information */
/*
* Code for iptables binary management taken from DroidWall GPLv3
* Copyright (C) 2009-2010 Rodrigo Zechin Rosauro
*/
package org.torproject.android.service;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.os.RemoteException;
import android.provider.BaseColumns;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;
import com.jrummyapps.android.shell.CommandResult;
import com.jrummyapps.android.shell.Shell;
import org.torproject.android.control.ConfigEntry;
import org.torproject.android.control.TorControlConnection;
import org.torproject.android.service.vpn.TorifiedApp;
import org.torproject.android.service.util.DummyActivity;
import org.torproject.android.service.util.Prefs;
import org.torproject.android.service.util.TorResourceInstaller;
import org.torproject.android.service.util.TorServiceUtils;
import org.torproject.android.service.util.Utils;
import org.torproject.android.service.vpn.OrbotVpnManager;
import org.torproject.android.service.vpn.TorVpnService;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;
public class TorService extends Service implements TorServiceConstants, OrbotConstants
{
private String 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 = HTTP_PROXY_PORT_DEFAULT;
private int mPortSOCKS = SOCKS_PROXY_PORT_DEFAULT;
private static final int NOTIFY_ID = 1;
private static final int ERROR_NOTIFY_ID = 3;
private static final int HS_NOTIFY_ID = 4;
private ArrayList<String> configBuffer = null;
private ArrayList<String> resetBuffer = null;
private boolean isTorUpgradeAndConfigComplete = false;
private File fileControlPort;
private boolean mConnectivity = true;
private int mNetworkType = -1;
private NotificationManager mNotificationManager = null;
private NotificationCompat.Builder mNotifyBuilder;
private Notification mNotification;
private boolean mNotificationShowing = false;
boolean mIsLollipop = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
private ExecutorService mExecutor = Executors.newFixedThreadPool(3);
TorEventHandler mEventHandler;
public static File appBinHome;
public static File appCacheHome;
public static File fileTor;
public static File filePolipo;
public static File fileObfsclient;
public static File fileTorRc;
private File mHSBasePath;
private ArrayList<Bridge> alBridges = null;
private static final Uri HS_CONTENT_URI = Uri.parse("content://org.torproject.android.ui.hiddenservices.providers/hs");
private static final Uri COOKIE_CONTENT_URI = Uri.parse("content://org.torproject.android.ui.hiddenservices.providers.cookie/cookie");
public static final class HiddenService implements BaseColumns {
public static final String NAME = "name";
public static final String PORT = "port";
public static final String ONION_PORT = "onion_port";
public static final String DOMAIN = "domain";
public static final String AUTH_COOKIE = "auth_cookie";
public static final String AUTH_COOKIE_VALUE = "auth_cookie_value";
public static final String CREATED_BY_USER = "created_by_user";
public static final String ENABLED = "enabled";
private HiddenService() {
}
}
public static final class ClientCookie implements BaseColumns {
public static final String DOMAIN = "domain";
public static final String AUTH_COOKIE_VALUE = "auth_cookie_value";
public static final String ENABLED = "enabled";
private ClientCookie() {
}
}
private String[] hsProjection = new String[]{
HiddenService._ID,
HiddenService.NAME,
HiddenService.DOMAIN,
HiddenService.PORT,
HiddenService.AUTH_COOKIE,
HiddenService.AUTH_COOKIE_VALUE,
HiddenService.ONION_PORT,
HiddenService.ENABLED};
private String[] cookieProjection = new String[]{
ClientCookie._ID,
ClientCookie.DOMAIN,
ClientCookie.AUTH_COOKIE_VALUE,
ClientCookie.ENABLED};
public void debug(String msg)
{
if (Prefs.useDebugLogging())
{
Log.d(OrbotConstants.TAG,msg);
sendCallbackLogMessage(msg);
}
}
public void logException(String msg, Exception e)
{
if (Prefs.useDebugLogging())
{
Log.e(OrbotConstants.TAG,msg,e);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(baos));
sendCallbackLogMessage(msg + '\n'+ new String(baos.toByteArray()));
}
else
sendCallbackLogMessage(msg);
}
private boolean findExistingTorDaemon() {
try {
mLastProcessId = initControlConnection(3, true);
if (mLastProcessId != -1 && conn != null) {
sendCallbackLogMessage(getString(R.string.found_existing_tor_process));
sendCallbackStatus(STATUS_ON);
showToolbarNotification(getString(R.string.status_activated),NOTIFY_ID,R.drawable.ic_stat_tor);
return true;
}
} catch (Exception e) {
}
return false;
}
/* (non-Javadoc)
* @see android.app.Service#onLowMemory()
*/
@Override
public void onLowMemory() {
super.onLowMemory();
logNotice( "Low Memory Warning!");
}
private void clearNotifications ()
{
if (mNotificationManager != null)
mNotificationManager.cancelAll();
if (mEventHandler != null)
mEventHandler.getNodes().clear();
mNotificationShowing = false;
}
@SuppressLint("NewApi")
protected void showToolbarNotification (String notifyMsg, int notifyType, int icon)
{
//Reusable code.
PackageManager pm = getPackageManager();
Intent intent = pm.getLaunchIntentForPackage(getPackageName());
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);
/**
//Restart intent
Intent yesReceive = new Intent();
yesReceive.setAction("Restart");
PendingIntent pendingIntentYes = PendingIntent.getBroadcast(this, 12345, yesReceive, PendingIntent.FLAG_UPDATE_CURRENT);
mNotifyBuilder.addAction(R.drawable.ic_stat_tor_off, "Restart", pendingIntentYes);
//Maybe intent
Intent maybeReceive = new Intent();
maybeReceive.setAction("Identity");
PendingIntent pendingIntentMaybe = PendingIntent.getBroadcast(this, 12345, maybeReceive, PendingIntent.FLAG_UPDATE_CURRENT);
mNotifyBuilder.addAction(R.drawable.ic_stat_tor_xfer, "New Identity", pendingIntentMaybe);
**/
}
}
mNotifyBuilder.setContentText(notifyMsg);
mNotifyBuilder.setSmallIcon(icon);
if (notifyType != NOTIFY_ID)
{
mNotifyBuilder.setTicker(notifyMsg);
}
else
{
mNotifyBuilder.setTicker(null);
}
mNotifyBuilder.setOngoing(Prefs.persistNotifications());
if (!Prefs.persistNotifications())
mNotifyBuilder.setPriority(Notification.PRIORITY_LOW);
mNotifyBuilder.setCategory(Notification.CATEGORY_SERVICE);
mNotification = mNotifyBuilder.build();
if (Build.VERSION.SDK_INT >= 16 && Prefs.expandedNotifications()) {
// 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 (mEventHandler != null && mEventHandler.getNodes().size() > 0)
{
Set<String> itBuiltNodes = mEventHandler.getNodes().keySet();
for (String key : itBuiltNodes)
{
TorEventHandler.Node node = mEventHandler.getNodes().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 (Prefs.persistNotifications() && (!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) {
if (intent != null)
exec (new IncomingIntentRouter(intent));
else
Log.d(OrbotConstants.TAG, "Got null onStartCommand() intent");
return Service.START_STICKY;
}
private class IncomingIntentRouter implements Runnable
{
Intent mIntent;
public IncomingIntentRouter (Intent intent)
{
mIntent = intent;
}
public void run() {
while (!isTorUpgradeAndConfigComplete)
{
try { Thread.sleep (500);}
catch (Exception e){}
}
String action = mIntent.getAction();
if (action != null) {
if (action.equals(ACTION_START)) {
replyWithStatus(mIntent);
startTor();
}
else if (action.equals(ACTION_STATUS)) {
replyWithStatus(mIntent);
}
else if (action.equals(CMD_SIGNAL_HUP)) {
requestTorRereadConfig();
} else if (action.equals(CMD_NEWNYM)) {
newIdentity();
} else if (action.equals(CMD_VPN)) {
startVPNService();
} else if (action.equals(CMD_VPN_CLEAR)) {
clearVpnProxy();
} else if (action.equals(CMD_SET_EXIT)) {
setExitNode(mIntent.getStringExtra("exit"));
} else {
Log.w(OrbotConstants.TAG, "unhandled TorService Intent: " + action);
}
}
}
}
@Override
public void onTaskRemoved(Intent rootIntent){
Log.d(OrbotConstants.TAG,"task removed");
Intent intent = new Intent( this, DummyActivity.class );
intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity( intent );
}
@Override
public void onDestroy() {
try {
unregisterReceiver(mNetworkStateReceiver);
}
catch (IllegalArgumentException iae)
{
//not registered yet
}
stopTor();
/**
try
{
mShell.close();
}
catch (IOException ioe)
{
Log.d(TAG, "Error closing shell",ioe);
}**/
super.onDestroy();
}
private void stopTor ()
{
new Thread(new Runnable ()
{
public void run ()
{
stopTorAsync();
}
}).start();
}
private void stopTorAsync () {
Log.i("TorService", "stopTor");
try {
sendCallbackStatus(STATUS_STOPPING);
sendCallbackLogMessage(getString(R.string.status_shutting_down));
killAllDaemons();
//stop the foreground priority and make sure to remove the persistant notification
stopForeground(true);
sendCallbackLogMessage(getString(R.string.status_disabled));
}
catch (Exception e)
{
logNotice("An error occured stopping Tor: " + e.getMessage());
sendCallbackLogMessage(getString(R.string.something_bad_happened));
}
clearNotifications();
sendCallbackStatus(STATUS_OFF);
}
private void killAllDaemons() throws Exception {
if (conn != null) {
logNotice("Using control port to shutdown Tor");
try {
logNotice("sending HALT signal to Tor process");
conn.shutdownTor("HALT");
} catch (IOException e) {
Log.d(OrbotConstants.TAG, "error shutting down Tor via connection", e);
}
conn = null;
}
/**
if (mShellPolipo != null)
{
mShellPolipo.close();
//logNotice("Polipo exited with value: " + exitValue);
}**/
}
private void requestTorRereadConfig() {
try {
conn.signal("HUP");
return;
} catch (IOException e) {
e.printStackTrace();
}
// if that fails, try again using native utils
try {
TorServiceUtils.killProcess(fileTor, "-1"); // this is -HUP
} catch (Exception e) {
e.printStackTrace();
}
}
protected void logNotice (String msg)
{
if (msg != null && msg.trim().length() > 0)
{
if (Prefs.useDebugLogging())
Log.d(OrbotConstants.TAG, msg);
sendCallbackLogMessage(msg);
}
}
@Override
public void onCreate() {
super.onCreate();
try
{
appBinHome = getDir(TorServiceConstants.DIRECTORY_TOR_BINARY, Application.MODE_PRIVATE);
appCacheHome = getDir(TorServiceConstants.DIRECTORY_TOR_DATA,Application.MODE_PRIVATE);
//mShell = Shell.startShell();
fileTor= new File(appBinHome, TorServiceConstants.TOR_ASSET_KEY);
filePolipo = new File(appBinHome, TorServiceConstants.POLIPO_ASSET_KEY);
fileObfsclient = new File(appBinHome, TorServiceConstants.OBFSCLIENT_ASSET_KEY);
fileTorRc = new File(appBinHome, TorServiceConstants.TORRC_ASSET_KEY);
mHSBasePath = new File(
getFilesDir().getAbsolutePath(),
TorServiceConstants.HIDDEN_SERVICES_DIR
);
if (!mHSBasePath.isDirectory())
mHSBasePath.mkdirs();
mEventHandler = new TorEventHandler(this);
if (mNotificationManager == null)
{
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
IntentFilter mNetworkStateFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mNetworkStateReceiver , mNetworkStateFilter);
new Thread(new Runnable ()
{
public void run ()
{
try
{
torUpgradeAndConfig();
findExistingTorDaemon();
}
catch (Exception e)
{
Log.e(OrbotConstants.TAG,"error onBind",e);
logNotice("error finding exiting process: " + e.toString());
}
}
}).start();
}
catch (Exception e)
{
//what error here
Log.e(OrbotConstants.TAG, "Error installing Orbot binaries",e);
logNotice("There was an error installing Orbot binaries");
}
Log.i("TorService", "onCreate end");
}
protected String getCurrentStatus ()
{
return mCurrentStatus;
}
private void torUpgradeAndConfig() throws IOException, TimeoutException {
if (isTorUpgradeAndConfigComplete)
return;
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 ();
isTorUpgradeAndConfigComplete = true;
}
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');
// extraLines.append("RunAsDaemon 1").append('\n');
// extraLines.append("AvoidDiskWrites 1").append('\n');
String socksPortPref = prefs.getString(OrbotConstants.PREF_SOCKS,
String.valueOf(TorServiceConstants.SOCKS_PROXY_PORT_DEFAULT));
if (socksPortPref.indexOf(':')!=-1)
socksPortPref = socksPortPref.split(":")[1];
if (!socksPortPref.equalsIgnoreCase("auto"))
{
boolean isPortUsed = TorServiceUtils.isPortOpen("127.0.0.1",Integer.parseInt(socksPortPref),500);
if (isPortUsed) //the specified port is not available, so let Tor find one instead
socksPortPref = "auto";
}
String isolate = " ";
if(prefs.getBoolean(OrbotConstants.PREF_ISOLATE_DEST, false))
{
isolate += "IsolateDestAddr";
}
extraLines.append("SOCKSPort ").append(socksPortPref).append(isolate).append('\n');
extraLines.append("SafeSocks 0").append('\n');
extraLines.append("TestSocks 0").append('\n');
extraLines.append("WarnUnsafeSocks 1").append('\n');
if(prefs.getBoolean(OrbotConstants.PREF_CONNECTION_PADDING, false))
{
extraLines.append("ConnectionPadding 1").append('\n');
}
if(prefs.getBoolean(OrbotConstants.PREF_REDUCED_CONNECTION_PADDING, true))
{
extraLines.append("ReducedConnectionPadding 1").append('\n');
}
String transPort = prefs.getString("pref_transport", TorServiceConstants.TOR_TRANSPROXY_PORT_DEFAULT+"");
String dnsPort = prefs.getString("pref_dnsport", TorServiceConstants.TOR_DNS_PORT_DEFAULT+"");
extraLines.append("TransPort ").append(transPort).append('\n');
extraLines.append("DNSPort ").append(dnsPort).append("\n");
if (Prefs.useVpn())
extraLines.append("DNSListenAddress 0.0.0.0").append('\n');
extraLines.append("VirtualAddrNetwork 10.192.0.0/10").append('\n');
extraLines.append("AutomapHostsOnResolve 1").append('\n');
extraLines.append("DisableNetwork 0").append('\n');
if (Prefs.useDebugLogging())
{
extraLines.append("Log debug syslog").append('\n');
extraLines.append("Log info syslog").append('\n');
extraLines.append("SafeLogging 0").append('\n');
}
processSettingsImpl(extraLines);
String torrcCustom = new String(prefs.getString("pref_custom_torrc", "").getBytes("US-ASCII"));
extraLines.append(torrcCustom).append('\n');
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;
}
/**
* Send Orbot's status in reply to an
* {@link TorServiceConstants#ACTION_START} {@link Intent}, targeted only to
* the app that sent the initial request. If the user has disabled auto-
* starts, the reply {@code ACTION_START Intent} will include the extra
* {@link TorServiceConstants#STATUS_STARTS_DISABLED}
*/
private void replyWithStatus(Intent startRequest) {
String packageName = startRequest.getStringExtra(EXTRA_PACKAGE_NAME);
Intent reply = new Intent(ACTION_STATUS);
reply.putExtra(EXTRA_STATUS, mCurrentStatus);
reply.putExtra(EXTRA_SOCKS_PROXY, "socks://127.0.0.1:" + mPortSOCKS);
reply.putExtra(EXTRA_SOCKS_PROXY_HOST, "127.0.0.1");
reply.putExtra(EXTRA_SOCKS_PROXY_PORT, mPortSOCKS);
reply.putExtra(EXTRA_HTTP_PROXY, "http://127.0.0.1" + mPortHTTP);
reply.putExtra(EXTRA_HTTP_PROXY_HOST, "127.0.0.1");
reply.putExtra(EXTRA_HTTP_PROXY_PORT, mPortHTTP);
if (packageName != null)
{
reply.setPackage(packageName);
sendBroadcast(reply);
}
else
{
LocalBroadcastManager.getInstance(this).sendBroadcast(reply);
}
}
/**
* The entire process for starting tor and related services is run from this method.
*/
private void startTor() {
// STATUS_STARTING is set in onCreate()
if (mCurrentStatus == STATUS_STOPPING) {
// these states should probably be handled better
sendCallbackLogMessage("Ignoring start request, currently " + mCurrentStatus);
return;
} else if (mCurrentStatus == STATUS_ON) {
sendCallbackLogMessage("Ignoring start request, already started.");
setTorNetworkEnabled (true);
return;
}
try {
// make sure there are no stray daemons running
// killAllDaemons();
sendCallbackStatus(STATUS_STARTING);
showToolbarNotification(getString(R.string.status_starting_up),NOTIFY_ID,R.drawable.ic_stat_tor);
sendCallbackLogMessage(getString(R.string.status_starting_up));
logNotice(getString(R.string.status_starting_up));
ArrayList<String> customEnv = new ArrayList<String>();
if (Prefs.bridgesEnabled())
if (Prefs.useVpn() && !mIsLollipop)
{
customEnv.add("TOR_PT_PROXY=socks5://" + OrbotVpnManager.sSocksProxyLocalhost + ":" + OrbotVpnManager.sSocksProxyServerPort);
}
boolean success = runTorShellCmd();
if (mPortHTTP != -1)
runPolipoShellCmd();
// Tor is running, update new .onion names at db
ContentResolver mCR = getApplicationContext().getContentResolver();
Cursor hidden_services = mCR.query(HS_CONTENT_URI, hsProjection, null, null, null);
if(hidden_services != null) {
try {
while (hidden_services.moveToNext()) {
String HSDomain = hidden_services.getString(hidden_services.getColumnIndex(HiddenService.DOMAIN));
Integer HSLocalPort = hidden_services.getInt(hidden_services.getColumnIndex(HiddenService.PORT));
Integer HSAuthCookie = hidden_services.getInt(hidden_services.getColumnIndex(HiddenService.AUTH_COOKIE));
String HSAuthCookieValue = hidden_services.getString(hidden_services.getColumnIndex(HiddenService.AUTH_COOKIE_VALUE));
// Update only new domains or restored from backup with auth cookie
if((HSDomain == null || HSDomain.length() < 1) || (HSAuthCookie == 1 && (HSAuthCookieValue == null || HSAuthCookieValue.length() < 1))) {
String hsDirPath = new File(mHSBasePath.getAbsolutePath(),"hs" + HSLocalPort).getCanonicalPath();
File file = new File(hsDirPath, "hostname");
if (file.exists())
{
ContentValues fields = new ContentValues();
try {
String onionHostname = Utils.readString(new FileInputStream(file)).trim();
if(HSAuthCookie == 1) {
String[] aux = onionHostname.split(" ");
onionHostname = aux[0];
fields.put(HiddenService.AUTH_COOKIE_VALUE, aux[1]);
}
fields.put(HiddenService.DOMAIN, onionHostname);
mCR.update(HS_CONTENT_URI, fields, "port=" + HSLocalPort , null);
} 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);
}
}
else
{
showToolbarNotification(getString(R.string.unable_to_read_hidden_service_name), HS_NOTIFY_ID, R.drawable.ic_stat_notifyerr);
}
}
}
} catch (NumberFormatException e) {
Log.e(OrbotConstants.TAG,"error parsing hsport",e);
} catch (Exception e) {
Log.e(OrbotConstants.TAG,"error starting share server",e);
}
hidden_services.close();
}
} catch (Exception e) {
logException("Unable to start Tor: " + e.toString(), e);
showToolbarNotification(
getString(R.string.unable_to_start_tor) + ": " + e.getMessage(),
ERROR_NOTIFY_ID, R.drawable.ic_stat_notifyerr);
//stopTor();
}
}
private boolean runTorShellCmd() throws Exception
{
boolean result = true;
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);
int exitCode = -1;
try {
exitCode = exec(torCmdString + " --verify-config", true);
}
catch (Exception e)
{
logNotice("Tor configuration did not verify: " + e.getMessage());
return false;
}
try {
exitCode = exec(torCmdString, true);
}
catch (Exception e)
{
logNotice("Tor was unable to start: " + e.getMessage());
return false;
}
if (exitCode != 0)
{
logNotice("Tor did not start. Exit:" + exitCode);
return false;
}
//now try to connect
mLastProcessId = initControlConnection (100,false);
if (mLastProcessId == -1)
{
logNotice(getString(R.string.couldn_t_start_tor_process_) + "; exit=" + exitCode);
sendCallbackLogMessage(getString(R.string.couldn_t_start_tor_process_));
throw new Exception ("Unable to start Tor");
}
else
{
logNotice("Tor started; process id=" + mLastProcessId);
}
return result;
}
protected void exec (Runnable runn)
{
mExecutor.execute(runn);
}
private int exec (String cmd, boolean wait) throws Exception
{
CommandResult shellResult = Shell.run(cmd);
debug("CMD: " + cmd + "; SUCCESS=" + shellResult.isSuccessful());
if (!shellResult.isSuccessful()) {
throw new Exception("Error: " + shellResult.exitCode + " ERR=" + shellResult.getStderr() + " OUT=" + shellResult.getStdout());
}
/**
SimpleCommand command = new SimpleCommand(cmd);
mShell.add(command);
if (wait)
command.waitForFinish();
return command.getExitCode();
**/
return shellResult.exitCode;
}
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 () throws Exception
{
logNotice( "Starting polipo process");
updatePolipoConfig();
String polipoConfigPath = new File(appBinHome, POLIPOCONFIG_ASSET_KEY).getCanonicalPath();
String cmd = (filePolipo.getCanonicalPath() + " -c " + polipoConfigPath);
CommandResult shellResult = Shell.run(cmd);
sendCallbackLogMessage(getString(R.string.privoxy_is_running_on_port_) + mPortHTTP);
logNotice("Polipo is running");
}
protected TorControlConnection getControlConnection ()
{
return conn;
}
private int initControlConnection (int maxTries, boolean isReconnect) throws Exception, RuntimeException
{
int controlPort = -1;
int attempt = 0;
logNotice( "Waiting for control port...");
while (conn == null && attempt++ < maxTries)
{