-
-
Notifications
You must be signed in to change notification settings - Fork 326
/
OrbotMainActivity.java
1392 lines (1093 loc) · 48 KB
/
OrbotMainActivity.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, Nathan Freitas, Orbot / The Guardian Project - https://guardianproject.info */
/* See LICENSE for licensing information */
package org.torproject.android;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.animation.AccelerateInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import org.json.JSONArray;
import org.torproject.android.service.OrbotConstants;
import org.torproject.android.service.TorService;
import org.torproject.android.service.TorServiceConstants;
import org.torproject.android.service.util.Prefs;
import org.torproject.android.service.vpn.TorVpnService;
import org.torproject.android.service.vpn.VpnConstants;
import org.torproject.android.service.vpn.VpnPrefs;
import org.torproject.android.settings.Languages;
import org.torproject.android.settings.LocaleHelper;
import org.torproject.android.settings.SettingsPreferences;
import org.torproject.android.ui.AppManagerActivity;
import org.torproject.android.ui.Rotate3dAnimation;
import org.torproject.android.ui.VPNEnableActivity;
import org.torproject.android.ui.hiddenservices.ClientCookiesActivity;
import org.torproject.android.ui.hiddenservices.HiddenServicesActivity;
import org.torproject.android.ui.hiddenservices.backup.BackupUtils;
import org.torproject.android.ui.hiddenservices.permissions.PermissionManager;
import org.torproject.android.ui.hiddenservices.providers.HSContentProvider;
import org.torproject.android.ui.onboarding.BridgeWizardActivity;
import org.torproject.android.ui.onboarding.OnboardingActivity;
import pl.bclogic.pulsator4droid.library.PulsatorLayout;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;
import java.util.StringTokenizer;
import static android.support.v4.content.FileProvider.getUriForFile;
import static org.torproject.android.MainConstants.COUNTRY_CODES;
import static org.torproject.android.MainConstants.RESULT_CLOSE_ALL;
import static org.torproject.android.MainConstants.URL_TOR_CHECK;
import static org.torproject.android.service.vpn.VpnPrefs.PREFS_KEY_TORIFIED;
import static org.torproject.android.service.vpn.VpnUtils.getSharedPrefs;
public class OrbotMainActivity extends AppCompatActivity
implements OrbotConstants, OnLongClickListener {
/* Useful UI bits */
private TextView lblStatus = null; //the main text display widget
private TextView lblPorts = null;
private ImageView imgStatus = null; //the main touchable image for activating Orbot
private TextView downloadText = null;
private TextView uploadText = null;
private TextView mTxtOrbotLog = null;
private Button mBtnStart = null;
private SwitchCompat mBtnVPN = null;
private SwitchCompat mBtnBridges = null;
private Spinner spnCountries = null;
private DrawerLayout mDrawer;
/* Some tracking bits */
private String torStatus = null; //latest status reported from the tor service
private Intent lastStatusIntent; // the last ACTION_STATUS Intent received
private SharedPreferences mPrefs = null;
private boolean autoStartFromIntent = false;
private final static int REQUEST_VPN = 8888;
private final static int REQUEST_SETTINGS = 0x9874;
private final static int REQUEST_VPN_APPS_SELECT = 8889;
private final static int LOG_DRAWER_GRAVITY = Gravity.END;
// message types for mStatusUpdateHandler
private final static int STATUS_UPDATE = 1;
private static final int MESSAGE_TRAFFIC_COUNT = 2;
private static final int MESSAGE_PORTS = 3;
public final static String INTENT_ACTION_REQUEST_HIDDEN_SERVICE = "org.torproject.android.REQUEST_HS_PORT";
public final static String INTENT_ACTION_REQUEST_START_TOR = "org.torproject.android.START_TOR";
PulsatorLayout mPulsator;
private void migratePreferences() {
String hsPortString = mPrefs.getString("pref_hs_ports", "");
if (hsPortString.length() > 0) {
StringTokenizer st = new StringTokenizer(hsPortString, ",");
ContentResolver cr = getContentResolver();
while (st.hasMoreTokens()) {
int hsPort = Integer.parseInt(st.nextToken().split(" ")[0]);
ContentValues fields = new ContentValues();
fields.put("name", hsPort);
fields.put("port", hsPort);
fields.put("onion_port", hsPort);
cr.insert(HSContentProvider.CONTENT_URI, fields);
}
Editor pEdit = mPrefs.edit();
pEdit.remove("pref_hs_ports");
pEdit.commit();
}
}
/**
* Called when the activity is first created.
*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPrefs = Prefs.getSharedPrefs(getApplicationContext());
migratePreferences(); // Migrate old preferences
/* Create the widgets before registering for broadcasts to guarantee
* that the widgets exist when the status updates try to update them */
doLayout();
/* receive the internal status broadcasts, which are separate from the public
* status broadcasts to prevent other apps from sending fake/wrong status
* info to this app */
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
lbm.registerReceiver(mLocalBroadcastReceiver,
new IntentFilter(TorServiceConstants.ACTION_STATUS));
lbm.registerReceiver(mLocalBroadcastReceiver,
new IntentFilter(TorServiceConstants.LOCAL_ACTION_BANDWIDTH));
lbm.registerReceiver(mLocalBroadcastReceiver,
new IntentFilter(TorServiceConstants.LOCAL_ACTION_LOG));
lbm.registerReceiver(mLocalBroadcastReceiver,
new IntentFilter(TorServiceConstants.LOCAL_ACTION_PORTS));
boolean showFirstTime = mPrefs.getBoolean("connect_first_time", true);
if (showFirstTime)
{
Editor pEdit = mPrefs.edit();
pEdit.putBoolean("connect_first_time", false);
pEdit.commit();
startActivity(new Intent(this,OnboardingActivity.class));
}
/**
* Resets previous DNS Port to the default
*/
getSharedPrefs(getApplicationContext()).edit().putInt(VpnPrefs.PREFS_DNS_PORT,
VpnConstants.TOR_DNS_PORT_DEFAULT).apply();
}
private void sendIntentToService(final String action) {
Intent torService = new Intent(OrbotMainActivity.this, TorService.class);
torService.setAction(action);
startService(torService);
}
private void stopTor() {
// requestTorStatus();
Intent torService = new Intent(OrbotMainActivity.this, TorService.class);
stopService(torService);
}
/**
* The state and log info from {@link TorService} are sent to the UI here in
* the form of a local broadcast. Regular broadcasts can be sent by any app,
* so local ones are used here so other apps cannot interfere with Orbot's
* operation.
*/
private BroadcastReceiver mLocalBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action == null)
return;
if (action.equals(TorServiceConstants.LOCAL_ACTION_LOG)) {
Message msg = mStatusUpdateHandler.obtainMessage(STATUS_UPDATE);
msg.obj = intent.getStringExtra(TorServiceConstants.LOCAL_EXTRA_LOG);
msg.getData().putString("status", intent.getStringExtra(TorServiceConstants.EXTRA_STATUS));
mStatusUpdateHandler.sendMessage(msg);
} else if (action.equals(TorServiceConstants.LOCAL_ACTION_BANDWIDTH)) {
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 = mStatusUpdateHandler.obtainMessage(MESSAGE_TRAFFIC_COUNT);
msg.getData().putLong("download", download);
msg.getData().putLong("upload", upload);
msg.getData().putLong("readTotal", read);
msg.getData().putLong("writeTotal", written);
msg.getData().putString("status", intent.getStringExtra(TorServiceConstants.EXTRA_STATUS));
mStatusUpdateHandler.sendMessage(msg);
} else if (action.equals(TorServiceConstants.ACTION_STATUS)) {
lastStatusIntent = intent;
Message msg = mStatusUpdateHandler.obtainMessage(STATUS_UPDATE);
msg.getData().putString("status", intent.getStringExtra(TorServiceConstants.EXTRA_STATUS));
mStatusUpdateHandler.sendMessage(msg);
}
else if (action.equals(TorServiceConstants.LOCAL_ACTION_PORTS)) {
Message msg = mStatusUpdateHandler.obtainMessage(MESSAGE_PORTS);
msg.getData().putInt("socks",intent.getIntExtra(TorService.EXTRA_SOCKS_PROXY_PORT,-1));
msg.getData().putInt("http",intent.getIntExtra(TorService.EXTRA_HTTP_PROXY_PORT,-1));
mStatusUpdateHandler.sendMessage(msg);
}
}
};
private void doLayout ()
{
setContentView(R.layout.layout_main);
setTitle(R.string.app_name);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
mTxtOrbotLog = (TextView)findViewById(R.id.orbotLog);
lblStatus = (TextView)findViewById(R.id.lblStatus);
lblStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDrawer.openDrawer(LOG_DRAWER_GRAVITY);
}
});
lblPorts = findViewById(R.id.lblPorts);
imgStatus = (ImageView)findViewById(R.id.imgStatus);
imgStatus.setOnLongClickListener(this);
downloadText = (TextView)findViewById(R.id.trafficDown);
uploadText = (TextView)findViewById(R.id.trafficUp);
downloadText.setText(formatCount(0) + " / " + formatTotal(0));
uploadText.setText(formatCount(0) + " / " + formatTotal(0));
mBtnStart =(Button)findViewById(R.id.btnStart);
mBtnStart.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
if (torStatus == TorServiceConstants.STATUS_OFF) {
lblStatus.setText(getString(R.string.status_starting_up));
startTor();
} else {
lblStatus.setText(getString(R.string.status_shutting_down));
stopTor();
}
}
});
mBtnVPN = (SwitchCompat)findViewById(R.id.btnVPN);
boolean useVPN = Prefs.useVpn();
mBtnVPN.setChecked(useVPN);
//auto start VPN if VPN is enabled
if (useVPN) {
startActivity(new Intent(OrbotMainActivity.this,VPNEnableActivity.class));
}
mBtnVPN.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
enableVPN(isChecked);
}
});
mBtnBridges = (SwitchCompat)findViewById(R.id.btnBridges);
mBtnBridges.setChecked(Prefs.bridgesEnabled());
mBtnBridges.setOnClickListener(new View.OnClickListener ()
{
@Override
public void onClick(View v) {
promptSetupBridges (); //if ARM processor, show all bridge options
}
});
spnCountries = (Spinner)findViewById(R.id.spinnerCountry);
setCountrySpinner();
mPulsator = (PulsatorLayout) findViewById(R.id.pulsator);
}
private void setCountrySpinner ()
{
String currentExit = Prefs.getExitNodes();
if (currentExit.length() > 4)
{
//someone put a complex value in, so let's disable
ArrayList<String> cList = new ArrayList<String>();
cList.add(0, currentExit);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, cList);
spnCountries.setAdapter(adapter);
spnCountries.setEnabled(false);
}
else {
int selIdx = -1;
ArrayList<String> cList = new ArrayList<String>();
cList.add(0, getString(R.string.vpn_default_world));
for (int i = 0; i < COUNTRY_CODES.length; i++) {
Locale locale = new Locale("", COUNTRY_CODES[i]);
cList.add(locale.getDisplayCountry());
if (currentExit.contains(COUNTRY_CODES[i]))
selIdx = i + 1;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, cList);
spnCountries.setAdapter(adapter);
if (selIdx > 0)
spnCountries.setSelection(selIdx,true);
spnCountries.setOnItemSelectedListener(new OnItemSelectedListener() {
int mOldPosition = spnCountries.getSelectedItemPosition();
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
if (mOldPosition == position)
return;
mOldPosition = position; //new position!
String country = null;
if (position == 0)
country = "";
else
country = '{' + COUNTRY_CODES[position - 1] + '}';
Intent torService = new Intent(OrbotMainActivity.this, TorService.class);
torService.setAction(TorServiceConstants.CMD_SET_EXIT);
torService.putExtra("exit", country);
startService(torService);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
}
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleHelper.onAttach(base));
}
/*
* Create the UI Options Menu (non-Javadoc)
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.orbot_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_newnym)
{
requestNewTorIdentity();
}
else if (item.getItemId() == R.id.menu_settings)
{
Intent intent = new Intent(OrbotMainActivity.this, SettingsPreferences.class);
startActivityForResult(intent, REQUEST_SETTINGS);
}
else if (item.getItemId() == R.id.menu_exit)
{
//exit app
doExit();
}
else if (item.getItemId() == R.id.menu_about)
{
showAbout();
}
else if (item.getItemId() == R.id.menu_scan)
{
IntentIntegrator integrator = new IntentIntegrator(OrbotMainActivity.this);
integrator.initiateScan();
}
else if (item.getItemId() == R.id.menu_share_bridge)
{
String bridges = Prefs.getBridgesList();
if (bridges != null && bridges.length() > 0)
{
try {
bridges = "bridge://" + URLEncoder.encode(bridges,"UTF-8");
IntentIntegrator integrator = new IntentIntegrator(OrbotMainActivity.this);
integrator.shareText(bridges);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else if (item.getItemId() == R.id.menu_hidden_services) {
startActivity(new Intent(this, HiddenServicesActivity.class));
} else if (item.getItemId() == R.id.menu_client_cookies) {
startActivity(new Intent(this, ClientCookiesActivity.class));
}
return super.onOptionsItemSelected(item);
}
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 " + TorService.BINARY_TOR_VERSION + ")";
} catch (NameNotFoundException e) {
version = "Version Not Found";
}
TextView versionName = (TextView)view.findViewById(R.id.versionName);
versionName.setText(version);
TextView aboutOther = (TextView)view.findViewById(R.id.aboutother);
try
{
String aboutText = readFromAssets(this,"LICENSE");
aboutText = aboutText.replace("\n","<br/>");
aboutOther.setText(Html.fromHtml(aboutText));
}
catch (Exception e){}
new AlertDialog.Builder(this)
.setTitle(getString(R.string.button_about))
.setView(view)
.show();
}
private static String readFromAssets(Context context, String filename) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open(filename)));
// do reading, usually loop until end of file reading
StringBuilder sb = new StringBuilder();
String mLine = reader.readLine();
while (mLine != null) {
sb.append(mLine + '\n'); // process line
mLine = reader.readLine();
}
reader.close();
return sb.toString();
}
/**
* This is our attempt to REALLY exit Orbot, and stop the background service
* However, Android doesn't like people "quitting" apps, and/or our code may
* not be quite right b/c no matter what we do, it seems like the TorService
* still exists
**/
private void doExit() {
stopTor();
// Kill all the wizard activities
setResult(RESULT_CLOSE_ALL);
finish();
}
protected void onPause() {
try
{
super.onPause();
if (aDialog != null)
aDialog.dismiss();
}
catch (IllegalStateException ise)
{
//can happen on exit/shutdown
}
}
@Override
public void onBackPressed() {
// check to see if the log is open, if so close it
if (mDrawer.isDrawerOpen(LOG_DRAWER_GRAVITY)) {
mDrawer.closeDrawers();
}
else {
super.onBackPressed();
}
}
private void refreshVPNApps ()
{
TorVpnService.stop(this);
startActivity(new Intent(OrbotMainActivity.this, VPNEnableActivity.class));
}
private void enableVPN (boolean enable)
{
Prefs.putUseVpn(enable);
if (enable) {
startActivityForResult(new Intent(OrbotMainActivity.this, VPNEnableActivity.class), REQUEST_VPN);
} else
TorVpnService.stop(this);
addAppShortcuts();
}
private void enableHiddenServicePort(
String hsName, final int hsPort, int hsRemotePort,
final String backupToPackage, final Uri hsKeyPath,
final Boolean authCookie
) throws RemoteException, InterruptedException {
String onionHostname = null;
if (hsName == null)
hsName = "hs" + hsPort;
if (hsRemotePort == -1)
hsRemotePort = hsPort;
ContentValues fields = new ContentValues();
fields.put(HSContentProvider.HiddenService.NAME, hsName);
fields.put(HSContentProvider.HiddenService.PORT, hsPort);
fields.put(HSContentProvider.HiddenService.ONION_PORT, hsRemotePort);
fields.put(HSContentProvider.HiddenService.AUTH_COOKIE, authCookie);
ContentResolver cr = getContentResolver();
Cursor row = cr.query(
HSContentProvider.CONTENT_URI,
HSContentProvider.PROJECTION,
HSContentProvider.HiddenService.ONION_PORT + "=" + hsPort,
null,
null
);
if (row == null || row.getCount() < 1) {
cr.insert(HSContentProvider.CONTENT_URI, fields);
} else if (row.moveToFirst()) {
onionHostname = row.getString(row.getColumnIndex(HSContentProvider.HiddenService.DOMAIN));
row.close();
}
if (onionHostname == null || onionHostname.length() < 1) {
if (hsKeyPath != null) {
BackupUtils hsutils = new BackupUtils(getApplicationContext());
hsutils.restoreKeyBackup(hsPort, hsKeyPath);
}
if (torStatus.equals(TorServiceConstants.STATUS_OFF)) {
startTor();
} else {
stopTor();
Toast.makeText(
this, R.string.start_tor_again_for_finish_the_process, Toast.LENGTH_LONG
).show();
}
new Thread() {
public void run() {
String hostname = null;
Intent nResult = new Intent();
while (hostname == null) {
try {
Thread.sleep(3000); //wait three seconds
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Cursor onion = getContentResolver().query(
HSContentProvider.CONTENT_URI,
HSContentProvider.PROJECTION,
HSContentProvider.HiddenService.ONION_PORT + "=" + hsPort,
null,
null
);
if (onion != null && onion.getCount() > 0) {
onion.moveToNext();
hostname = onion.getString(onion.getColumnIndex(HSContentProvider.HiddenService.DOMAIN));
if(hostname == null || hostname.length() < 1)
continue;
nResult.putExtra("hs_host", hostname);
if (authCookie) {
nResult.putExtra(
"hs_auth_cookie",
onion.getString(onion.getColumnIndex(HSContentProvider.HiddenService.AUTH_COOKIE_VALUE))
);
}
if (backupToPackage != null && backupToPackage.length() > 0) {
String servicePath = getFilesDir() + "/" + TorServiceConstants.HIDDEN_SERVICES_DIR + "/hs" + hsPort;
File hidden_service_key = new File(servicePath, "private_key");
Context context = getApplicationContext();
Uri contentUri = getUriForFile(
context,
"org.torproject.android.ui.hiddenservices.storage",
hidden_service_key
);
context.grantUriPermission(backupToPackage, contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
nResult.setData(contentUri);
nResult.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
onion.close();
setResult(RESULT_OK, nResult);
finish();
}
}
}
}.start();
} else {
Intent nResult = new Intent();
nResult.putExtra("hs_host", onionHostname);
setResult(RESULT_OK, nResult);
finish();
}
}
private synchronized void handleIntents() {
if (getIntent() == null)
return;
// Get intent, action and MIME type
Intent intent = getIntent();
String action = intent.getAction();
if (action == null)
return;
switch (action) {
case INTENT_ACTION_REQUEST_HIDDEN_SERVICE:
final int hiddenServicePort = intent.getIntExtra("hs_port", -1);
final int hiddenServiceRemotePort = intent.getIntExtra("hs_onion_port", -1);
final String hiddenServiceName = intent.getStringExtra("hs_name");
final String backupToPackage = intent.getStringExtra("hs_backup_to_package");
final Boolean authCookie = intent.getBooleanExtra("hs_auth_cookie", false);
final Uri mKeyUri = intent.getData();
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
try {
enableHiddenServicePort(
hiddenServiceName, hiddenServicePort,
hiddenServiceRemotePort, backupToPackage,
mKeyUri, authCookie
);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
};
String requestMsg = getString(R.string.hidden_service_request, hiddenServicePort);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(requestMsg).setPositiveButton("Allow", dialogClickListener)
.setNegativeButton("Deny", dialogClickListener).show();
return; //don't null the setIntent() as we need it later
case INTENT_ACTION_REQUEST_START_TOR:
autoStartFromIntent = true;
startTor();
break;
case 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(getString(R.string.bridges_updated), getString(R.string.restart_orbot_to_use_this_bridge_) + newBridgeValue, false);
setNewBridges(newBridgeValue);
}
}
break;
}
updateStatus(null, torStatus);
setIntent(null);
}
private void setNewBridges(String newBridgeValue) {
Prefs.setBridgesList(newBridgeValue); //set the string to a preference
Prefs.putBridgesEnabled(true);
setResult(RESULT_OK);
mBtnBridges.setChecked(true);
enableBridges(true);
}
/*
* Launch the system activity for Uri viewing with the provided url
*/
private void openBrowser(final String browserLaunchUrl,boolean forceExternal, String pkgId) {
if (pkgId != null) {
startIntent(pkgId,Intent.ACTION_VIEW,Uri.parse(browserLaunchUrl));
}
else if (mBtnVPN.isChecked()||forceExternal) {
//use the system browser since VPN is on
startIntent(null,Intent.ACTION_VIEW, Uri.parse(browserLaunchUrl));
}
}
private void startIntent (String pkg, String action, Uri data)
{
Intent i;
PackageManager pm = getPackageManager();
try {
if (pkg != null) {
i = pm.getLaunchIntentForPackage(pkg);
if (i == null)
throw new PackageManager.NameNotFoundException();
}
else
{
i = new Intent();
}
i.setAction(action);
i.setData(data);
if (i.resolveActivity(pm)!=null)
startActivity(i);
} catch (PackageManager.NameNotFoundException e) {
}
}
@Override
protected void onActivityResult(int request, int response, Intent data) {
super.onActivityResult(request, response, data);
if (request == REQUEST_SETTINGS && response == RESULT_OK)
{
if (data != null && (!TextUtils.isEmpty(data.getStringExtra("locale")))) {
String newLocale = data.getStringExtra("locale");
Prefs.setDefaultLocale(newLocale);
Languages.setLanguage(this, newLocale, true);
// Language.setFromPreference(this, "pref_default_locale");
finish();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
startActivity(new Intent(OrbotMainActivity.this,OrbotMainActivity.class));
}
}, 1000);
}
}
else if (request == REQUEST_VPN)
{
if (response == RESULT_OK) {
TorVpnService.start(this);
}
else if (response == VPNEnableActivity.ACTIVITY_RESULT_VPN_DENIED)
{
mBtnVPN.setChecked(false);
Prefs.putUseVpn(false);
}
}
else if (request == REQUEST_VPN_APPS_SELECT)
{
if (response == RESULT_OK &&
torStatus == TorServiceConstants.STATUS_ON)
refreshVPNApps();
}
IntentResult scanResult = IntentIntegrator.parseActivityResult(request, response, data);
if (scanResult != null) {
// handle scan result
String results = scanResult.getContents();
if (results != null && results.length() > 0)
{
try {
int urlIdx = results.indexOf("://");
if (urlIdx!=-1)
{
results = URLDecoder.decode(results, "UTF-8");
results = results.substring(urlIdx+3);
showAlert(getString(R.string.bridges_updated),getString(R.string.restart_orbot_to_use_this_bridge_) + results,false);
setNewBridges(results);
}
else
{
JSONArray bridgeJson = new JSONArray(results);
StringBuffer bridgeLines = new StringBuffer();
for (int i = 0; i < bridgeJson.length(); i++)
{
String bridgeLine = bridgeJson.getString(i);
bridgeLines.append(bridgeLine).append("\n");
}
setNewBridges(bridgeLines.toString());
}
} catch (Exception e) {
Log.e(TAG,"unsupported",e);
}
}
}
}
public void promptSetupBridges ()
{
if (mBtnBridges.isChecked())
{
Prefs.putBridgesEnabled(true);
startActivity(new Intent(this, BridgeWizardActivity.class));
}
else
{
enableBridges(false);
}
}
private void enableBridges (boolean enable)
{
Prefs.putBridgesEnabled(enable);
if (torStatus == TorServiceConstants.STATUS_ON)
{
String bridgeList = Prefs.getBridgesList();
if (bridgeList != null && bridgeList.length() > 0)
{
requestTorRereadConfig ();
}
}
}
private void requestTorRereadConfig() {
sendIntentToService(TorServiceConstants.CMD_SIGNAL_HUP);
}