This repository has been archived by the owner on Nov 8, 2023. It is now read-only.
/
Tethering.java
2035 lines (1826 loc) · 86 KB
/
Tethering.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) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.connectivity;
import static android.hardware.usb.UsbManager.USB_CONFIGURED;
import static android.hardware.usb.UsbManager.USB_CONNECTED;
import static android.hardware.usb.UsbManager.USB_FUNCTION_RNDIS;
import static android.net.ConnectivityManager.getNetworkTypeName;
import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_INTERFACE_NAME;
import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_MODE;
import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_STATE;
import static android.net.wifi.WifiManager.IFACE_IP_MODE_CONFIGURATION_ERROR;
import static android.net.wifi.WifiManager.IFACE_IP_MODE_LOCAL_ONLY;
import static android.net.wifi.WifiManager.IFACE_IP_MODE_TETHERED;
import static android.net.wifi.WifiManager.IFACE_IP_MODE_UNSPECIFIED;
import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLED;
import static com.android.server.ConnectivityService.SHORT_ARG;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothPan;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothProfile.ServiceListener;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.hardware.usb.UsbManager;
import android.net.ConnectivityManager;
import android.net.INetworkPolicyManager;
import android.net.INetworkStatsService;
import android.net.IpPrefix;
import android.net.LinkAddress;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.net.NetworkState;
import android.net.NetworkUtils;
import android.net.RouteInfo;
import android.net.util.PrefixUtils;
import android.net.util.SharedLog;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.INetworkManagementService;
import android.os.Looper;
import android.os.Message;
import android.os.Parcel;
import android.os.RemoteException;
import android.os.ResultReceiver;
import android.os.UserHandle;
import android.os.UserManager;
import android.os.UserManagerInternal;
import android.os.UserManagerInternal.UserRestrictionsListener;
import android.provider.Settings;
import android.telephony.CarrierConfigManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Log;
import android.util.SparseArray;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
import com.android.internal.notification.SystemNotificationChannels;
import com.android.internal.telephony.IccCardConstants;
import com.android.internal.telephony.TelephonyIntents;
import com.android.internal.util.DumpUtils;
import com.android.internal.util.IndentingPrintWriter;
import com.android.internal.util.MessageUtils;
import com.android.internal.util.Protocol;
import com.android.internal.util.State;
import com.android.internal.util.StateMachine;
import com.android.server.LocalServices;
import com.android.server.connectivity.tethering.IControlsTethering;
import com.android.server.connectivity.tethering.IPv6TetheringCoordinator;
import com.android.server.connectivity.tethering.OffloadController;
import com.android.server.connectivity.tethering.SimChangeListener;
import com.android.server.connectivity.tethering.TetherInterfaceStateMachine;
import com.android.server.connectivity.tethering.TetheringConfiguration;
import com.android.server.connectivity.tethering.TetheringDependencies;
import com.android.server.connectivity.tethering.UpstreamNetworkMonitor;
import com.android.server.net.BaseNetworkObserver;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @hide
*
* This class holds much of the business logic to allow Android devices
* to act as IP gateways via USB, BT, and WiFi interfaces.
*/
public class Tethering extends BaseNetworkObserver {
private final static String TAG = Tethering.class.getSimpleName();
private final static boolean DBG = false;
private final static boolean VDBG = false;
protected static final String DISABLE_PROVISIONING_SYSPROP_KEY = "net.tethering.noprovisioning";
private static final Class[] messageClasses = {
Tethering.class, TetherMasterSM.class, TetherInterfaceStateMachine.class
};
private static final SparseArray<String> sMagicDecoderRing =
MessageUtils.findMessageNames(messageClasses);
// {@link ComponentName} of the Service used to run tether provisioning.
private static final ComponentName TETHER_SERVICE = ComponentName.unflattenFromString(Resources
.getSystem().getString(com.android.internal.R.string.config_wifi_tether_enable));
private static class TetherState {
public final TetherInterfaceStateMachine stateMachine;
public int lastState;
public int lastError;
public TetherState(TetherInterfaceStateMachine sm) {
stateMachine = sm;
// Assume all state machines start out available and with no errors.
lastState = IControlsTethering.STATE_AVAILABLE;
lastError = ConnectivityManager.TETHER_ERROR_NO_ERROR;
}
public boolean isCurrentlyServing() {
switch (lastState) {
case IControlsTethering.STATE_TETHERED:
case IControlsTethering.STATE_LOCAL_ONLY:
return true;
default:
return false;
}
}
}
private final SharedLog mLog = new SharedLog(TAG);
// used to synchronize public access to members
private final Object mPublicSync;
private final Context mContext;
private final ArrayMap<String, TetherState> mTetherStates;
private final BroadcastReceiver mStateReceiver;
private final INetworkManagementService mNMService;
private final INetworkStatsService mStatsService;
private final INetworkPolicyManager mPolicyManager;
private final Looper mLooper;
private final MockableSystemProperties mSystemProperties;
private final StateMachine mTetherMasterSM;
private final OffloadController mOffloadController;
private final UpstreamNetworkMonitor mUpstreamNetworkMonitor;
// TODO: Figure out how to merge this and other downstream-tracking objects
// into a single coherent structure.
private final HashSet<TetherInterfaceStateMachine> mForwardedDownstreams;
private final SimChangeListener mSimChange;
private volatile TetheringConfiguration mConfig;
private String mCurrentUpstreamIface;
private Notification.Builder mTetheredNotificationBuilder;
private int mLastNotificationId;
private boolean mRndisEnabled; // track the RNDIS function enabled state
private boolean mUsbTetherRequested; // true if USB tethering should be started
// when RNDIS is enabled
// True iff. WiFi tethering should be started when soft AP is ready.
private boolean mWifiTetherRequested;
public Tethering(Context context, INetworkManagementService nmService,
INetworkStatsService statsService, INetworkPolicyManager policyManager,
Looper looper, MockableSystemProperties systemProperties,
TetheringDependencies deps) {
mLog.mark("constructed");
mContext = context;
mNMService = nmService;
mStatsService = statsService;
mPolicyManager = policyManager;
mLooper = looper;
mSystemProperties = systemProperties;
mPublicSync = new Object();
mTetherStates = new ArrayMap<>();
mTetherMasterSM = new TetherMasterSM("TetherMaster", mLooper);
mTetherMasterSM.start();
final Handler smHandler = mTetherMasterSM.getHandler();
mOffloadController = new OffloadController(smHandler,
deps.getOffloadHardwareInterface(smHandler, mLog),
mContext.getContentResolver(), mNMService,
mLog);
mUpstreamNetworkMonitor = new UpstreamNetworkMonitor(
mContext, mTetherMasterSM, mLog, TetherMasterSM.EVENT_UPSTREAM_CALLBACK);
mForwardedDownstreams = new HashSet<>();
mSimChange = new SimChangeListener(
mContext, smHandler, () -> reevaluateSimCardProvisioning());
mStateReceiver = new StateReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_STATE);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
mContext.registerReceiver(mStateReceiver, filter, null, smHandler);
filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_SHARED);
filter.addAction(Intent.ACTION_MEDIA_UNSHARED);
filter.addDataScheme("file");
mContext.registerReceiver(mStateReceiver, filter, null, smHandler);
UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
// this check is useful only for some unit tests; example: ConnectivityServiceTest
if (userManager != null) {
userManager.addUserRestrictionsListener(new TetheringUserRestrictionListener(this));
}
// load device config info
updateConfiguration();
}
// We can't do this once in the Tethering() constructor and cache the value, because the
// CONNECTIVITY_SERVICE is registered only after the Tethering() constructor has completed.
private ConnectivityManager getConnectivityManager() {
return (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
}
private WifiManager getWifiManager() {
return (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
}
// NOTE: This is always invoked on the mLooper thread.
private void updateConfiguration() {
mConfig = new TetheringConfiguration(mContext, mLog);
mUpstreamNetworkMonitor.updateMobileRequiresDun(mConfig.isDunRequired);
}
private void maybeUpdateConfiguration() {
final int dunCheck = TetheringConfiguration.checkDunRequired(mContext);
if (dunCheck == mConfig.dunCheck) return;
updateConfiguration();
}
@Override
public void interfaceStatusChanged(String iface, boolean up) {
// Never called directly: only called from interfaceLinkStateChanged.
// See NetlinkHandler.cpp:71.
if (VDBG) Log.d(TAG, "interfaceStatusChanged " + iface + ", " + up);
synchronized (mPublicSync) {
if (up) {
maybeTrackNewInterfaceLocked(iface);
} else {
if (ifaceNameToType(iface) == ConnectivityManager.TETHERING_BLUETOOTH) {
stopTrackingInterfaceLocked(iface);
} else {
// Ignore usb0 down after enabling RNDIS.
// We will handle disconnect in interfaceRemoved.
// Similarly, ignore interface down for WiFi. We monitor WiFi AP status
// through the WifiManager.WIFI_AP_STATE_CHANGED_ACTION intent.
if (VDBG) Log.d(TAG, "ignore interface down for " + iface);
}
}
}
}
@Override
public void interfaceLinkStateChanged(String iface, boolean up) {
interfaceStatusChanged(iface, up);
}
private int ifaceNameToType(String iface) {
final TetheringConfiguration cfg = mConfig;
if (cfg.isWifi(iface)) {
return ConnectivityManager.TETHERING_WIFI;
} else if (cfg.isUsb(iface)) {
return ConnectivityManager.TETHERING_USB;
} else if (cfg.isBluetooth(iface)) {
return ConnectivityManager.TETHERING_BLUETOOTH;
}
return ConnectivityManager.TETHERING_INVALID;
}
@Override
public void interfaceAdded(String iface) {
if (VDBG) Log.d(TAG, "interfaceAdded " + iface);
synchronized (mPublicSync) {
maybeTrackNewInterfaceLocked(iface);
}
}
@Override
public void interfaceRemoved(String iface) {
if (VDBG) Log.d(TAG, "interfaceRemoved " + iface);
synchronized (mPublicSync) {
stopTrackingInterfaceLocked(iface);
}
}
public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi) {
if (!isTetherProvisioningRequired()) {
enableTetheringInternal(type, true, receiver);
return;
}
if (showProvisioningUi) {
runUiTetherProvisioningAndEnable(type, receiver);
} else {
runSilentTetherProvisioningAndEnable(type, receiver);
}
}
public void stopTethering(int type) {
enableTetheringInternal(type, false, null);
if (isTetherProvisioningRequired()) {
cancelTetherProvisioningRechecks(type);
}
}
/**
* Check if the device requires a provisioning check in order to enable tethering.
*
* @return a boolean - {@code true} indicating tether provisioning is required by the carrier.
*/
@VisibleForTesting
protected boolean isTetherProvisioningRequired() {
String[] provisionApp = mContext.getResources().getStringArray(
com.android.internal.R.array.config_mobile_hotspot_provision_app);
if (mSystemProperties.getBoolean(DISABLE_PROVISIONING_SYSPROP_KEY, false)
|| provisionApp == null) {
return false;
}
// Check carrier config for entitlement checks
final CarrierConfigManager configManager = (CarrierConfigManager) mContext
.getSystemService(Context.CARRIER_CONFIG_SERVICE);
if (configManager != null && configManager.getConfig() != null) {
// we do have a CarrierConfigManager and it has a config.
boolean isEntitlementCheckRequired = configManager.getConfig().getBoolean(
CarrierConfigManager.KEY_REQUIRE_ENTITLEMENT_CHECKS_BOOL);
if (!isEntitlementCheckRequired) {
return false;
}
}
return (provisionApp.length == 2);
}
// Used by the SIM card change observation code.
// TODO: De-duplicate above code.
private boolean hasMobileHotspotProvisionApp() {
try {
if (!mContext.getResources().getString(com.android.internal.R.string.
config_mobile_hotspot_provision_app_no_ui).isEmpty()) {
Log.d(TAG, "re-evaluate provisioning");
return true;
}
} catch (Resources.NotFoundException e) {}
Log.d(TAG, "no prov-check needed for new SIM");
return false;
}
/**
* Enables or disables tethering for the given type. This should only be called once
* provisioning has succeeded or is not necessary. It will also schedule provisioning rechecks
* for the specified interface.
*/
private void enableTetheringInternal(int type, boolean enable, ResultReceiver receiver) {
boolean isProvisioningRequired = enable && isTetherProvisioningRequired();
int result;
switch (type) {
case ConnectivityManager.TETHERING_WIFI:
result = setWifiTethering(enable);
if (isProvisioningRequired && result == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
scheduleProvisioningRechecks(type);
}
sendTetherResult(receiver, result);
break;
case ConnectivityManager.TETHERING_USB:
result = setUsbTethering(enable);
if (isProvisioningRequired && result == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
scheduleProvisioningRechecks(type);
}
sendTetherResult(receiver, result);
break;
case ConnectivityManager.TETHERING_BLUETOOTH:
setBluetoothTethering(enable, receiver);
break;
default:
Log.w(TAG, "Invalid tether type.");
sendTetherResult(receiver, ConnectivityManager.TETHER_ERROR_UNKNOWN_IFACE);
}
}
private void sendTetherResult(ResultReceiver receiver, int result) {
if (receiver != null) {
receiver.send(result, null);
}
}
private int setWifiTethering(final boolean enable) {
int rval = ConnectivityManager.TETHER_ERROR_MASTER_ERROR;
final long ident = Binder.clearCallingIdentity();
try {
synchronized (mPublicSync) {
mWifiTetherRequested = enable;
final WifiManager mgr = getWifiManager();
if ((enable && mgr.startSoftAp(null /* use existing wifi config */)) ||
(!enable && mgr.stopSoftAp())) {
rval = ConnectivityManager.TETHER_ERROR_NO_ERROR;
}
}
} finally {
Binder.restoreCallingIdentity(ident);
}
return rval;
}
private void setBluetoothTethering(final boolean enable, final ResultReceiver receiver) {
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter == null || !adapter.isEnabled()) {
Log.w(TAG, "Tried to enable bluetooth tethering with null or disabled adapter. null: " +
(adapter == null));
sendTetherResult(receiver, ConnectivityManager.TETHER_ERROR_SERVICE_UNAVAIL);
return;
}
adapter.getProfileProxy(mContext, new ServiceListener() {
@Override
public void onServiceDisconnected(int profile) { }
@Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
((BluetoothPan) proxy).setBluetoothTethering(enable);
// TODO: Enabling bluetooth tethering can fail asynchronously here.
// We should figure out a way to bubble up that failure instead of sending success.
int result = ((BluetoothPan) proxy).isTetheringOn() == enable ?
ConnectivityManager.TETHER_ERROR_NO_ERROR :
ConnectivityManager.TETHER_ERROR_MASTER_ERROR;
sendTetherResult(receiver, result);
if (enable && isTetherProvisioningRequired()) {
scheduleProvisioningRechecks(ConnectivityManager.TETHERING_BLUETOOTH);
}
adapter.closeProfileProxy(BluetoothProfile.PAN, proxy);
}
}, BluetoothProfile.PAN);
}
private void runUiTetherProvisioningAndEnable(int type, ResultReceiver receiver) {
ResultReceiver proxyReceiver = getProxyReceiver(type, receiver);
sendUiTetherProvisionIntent(type, proxyReceiver);
}
private void sendUiTetherProvisionIntent(int type, ResultReceiver receiver) {
Intent intent = new Intent(Settings.ACTION_TETHER_PROVISIONING);
intent.putExtra(ConnectivityManager.EXTRA_ADD_TETHER_TYPE, type);
intent.putExtra(ConnectivityManager.EXTRA_PROVISION_CALLBACK, receiver);
final long ident = Binder.clearCallingIdentity();
try {
mContext.startActivityAsUser(intent, UserHandle.CURRENT);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
/**
* Creates a proxy {@link ResultReceiver} which enables tethering if the provisioning result
* is successful before firing back up to the wrapped receiver.
*
* @param type The type of tethering being enabled.
* @param receiver A ResultReceiver which will be called back with an int resultCode.
* @return The proxy receiver.
*/
private ResultReceiver getProxyReceiver(final int type, final ResultReceiver receiver) {
ResultReceiver rr = new ResultReceiver(null) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// If provisioning is successful, enable tethering, otherwise just send the error.
if (resultCode == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
enableTetheringInternal(type, true, receiver);
} else {
sendTetherResult(receiver, resultCode);
}
}
};
// The following is necessary to avoid unmarshalling issues when sending the receiver
// across processes.
Parcel parcel = Parcel.obtain();
rr.writeToParcel(parcel,0);
parcel.setDataPosition(0);
ResultReceiver receiverForSending = ResultReceiver.CREATOR.createFromParcel(parcel);
parcel.recycle();
return receiverForSending;
}
private void scheduleProvisioningRechecks(int type) {
Intent intent = new Intent();
intent.putExtra(ConnectivityManager.EXTRA_ADD_TETHER_TYPE, type);
intent.putExtra(ConnectivityManager.EXTRA_SET_ALARM, true);
intent.setComponent(TETHER_SERVICE);
final long ident = Binder.clearCallingIdentity();
try {
mContext.startServiceAsUser(intent, UserHandle.CURRENT);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
private void runSilentTetherProvisioningAndEnable(int type, ResultReceiver receiver) {
ResultReceiver proxyReceiver = getProxyReceiver(type, receiver);
sendSilentTetherProvisionIntent(type, proxyReceiver);
}
private void sendSilentTetherProvisionIntent(int type, ResultReceiver receiver) {
Intent intent = new Intent();
intent.putExtra(ConnectivityManager.EXTRA_ADD_TETHER_TYPE, type);
intent.putExtra(ConnectivityManager.EXTRA_RUN_PROVISION, true);
intent.putExtra(ConnectivityManager.EXTRA_PROVISION_CALLBACK, receiver);
intent.setComponent(TETHER_SERVICE);
final long ident = Binder.clearCallingIdentity();
try {
mContext.startServiceAsUser(intent, UserHandle.CURRENT);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
private void cancelTetherProvisioningRechecks(int type) {
if (getConnectivityManager().isTetheringSupported()) {
Intent intent = new Intent();
intent.putExtra(ConnectivityManager.EXTRA_REM_TETHER_TYPE, type);
intent.setComponent(TETHER_SERVICE);
final long ident = Binder.clearCallingIdentity();
try {
mContext.startServiceAsUser(intent, UserHandle.CURRENT);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
}
// Used by the SIM card change observation code.
// TODO: De-duplicate with above code, where possible.
private void startProvisionIntent(int tetherType) {
final Intent startProvIntent = new Intent();
startProvIntent.putExtra(ConnectivityManager.EXTRA_ADD_TETHER_TYPE, tetherType);
startProvIntent.putExtra(ConnectivityManager.EXTRA_RUN_PROVISION, true);
startProvIntent.setComponent(TETHER_SERVICE);
mContext.startServiceAsUser(startProvIntent, UserHandle.CURRENT);
}
public int tether(String iface) {
return tether(iface, IControlsTethering.STATE_TETHERED);
}
private int tether(String iface, int requestedState) {
if (DBG) Log.d(TAG, "Tethering " + iface);
synchronized (mPublicSync) {
TetherState tetherState = mTetherStates.get(iface);
if (tetherState == null) {
Log.e(TAG, "Tried to Tether an unknown iface: " + iface + ", ignoring");
return ConnectivityManager.TETHER_ERROR_UNKNOWN_IFACE;
}
// Ignore the error status of the interface. If the interface is available,
// the errors are referring to past tethering attempts anyway.
if (tetherState.lastState != IControlsTethering.STATE_AVAILABLE) {
Log.e(TAG, "Tried to Tether an unavailable iface: " + iface + ", ignoring");
return ConnectivityManager.TETHER_ERROR_UNAVAIL_IFACE;
}
// NOTE: If a CMD_TETHER_REQUESTED message is already in the TISM's
// queue but not yet processed, this will be a no-op and it will not
// return an error.
//
// TODO: reexamine the threading and messaging model.
tetherState.stateMachine.sendMessage(
TetherInterfaceStateMachine.CMD_TETHER_REQUESTED, requestedState);
return ConnectivityManager.TETHER_ERROR_NO_ERROR;
}
}
public int untether(String iface) {
if (DBG) Log.d(TAG, "Untethering " + iface);
synchronized (mPublicSync) {
TetherState tetherState = mTetherStates.get(iface);
if (tetherState == null) {
Log.e(TAG, "Tried to Untether an unknown iface :" + iface + ", ignoring");
return ConnectivityManager.TETHER_ERROR_UNKNOWN_IFACE;
}
if (!tetherState.isCurrentlyServing()) {
Log.e(TAG, "Tried to untether an inactive iface :" + iface + ", ignoring");
return ConnectivityManager.TETHER_ERROR_UNAVAIL_IFACE;
}
tetherState.stateMachine.sendMessage(
TetherInterfaceStateMachine.CMD_TETHER_UNREQUESTED);
return ConnectivityManager.TETHER_ERROR_NO_ERROR;
}
}
public void untetherAll() {
stopTethering(ConnectivityManager.TETHERING_WIFI);
stopTethering(ConnectivityManager.TETHERING_USB);
stopTethering(ConnectivityManager.TETHERING_BLUETOOTH);
}
public int getLastTetherError(String iface) {
synchronized (mPublicSync) {
TetherState tetherState = mTetherStates.get(iface);
if (tetherState == null) {
Log.e(TAG, "Tried to getLastTetherError on an unknown iface :" + iface +
", ignoring");
return ConnectivityManager.TETHER_ERROR_UNKNOWN_IFACE;
}
return tetherState.lastError;
}
}
// TODO: Figure out how to update for local hotspot mode interfaces.
private void sendTetherStateChangedBroadcast() {
if (!getConnectivityManager().isTetheringSupported()) return;
final ArrayList<String> availableList = new ArrayList<>();
final ArrayList<String> tetherList = new ArrayList<>();
final ArrayList<String> localOnlyList = new ArrayList<>();
final ArrayList<String> erroredList = new ArrayList<>();
boolean wifiTethered = false;
boolean usbTethered = false;
boolean bluetoothTethered = false;
final TetheringConfiguration cfg = mConfig;
synchronized (mPublicSync) {
for (int i = 0; i < mTetherStates.size(); i++) {
TetherState tetherState = mTetherStates.valueAt(i);
String iface = mTetherStates.keyAt(i);
if (tetherState.lastError != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
erroredList.add(iface);
} else if (tetherState.lastState == IControlsTethering.STATE_AVAILABLE) {
availableList.add(iface);
} else if (tetherState.lastState == IControlsTethering.STATE_LOCAL_ONLY) {
localOnlyList.add(iface);
} else if (tetherState.lastState == IControlsTethering.STATE_TETHERED) {
if (cfg.isUsb(iface)) {
usbTethered = true;
} else if (cfg.isWifi(iface)) {
wifiTethered = true;
} else if (cfg.isBluetooth(iface)) {
bluetoothTethered = true;
}
tetherList.add(iface);
}
}
}
final Intent bcast = new Intent(ConnectivityManager.ACTION_TETHER_STATE_CHANGED);
bcast.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
bcast.putStringArrayListExtra(ConnectivityManager.EXTRA_AVAILABLE_TETHER, availableList);
bcast.putStringArrayListExtra(ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY, localOnlyList);
bcast.putStringArrayListExtra(ConnectivityManager.EXTRA_ACTIVE_TETHER, tetherList);
bcast.putStringArrayListExtra(ConnectivityManager.EXTRA_ERRORED_TETHER, erroredList);
mContext.sendStickyBroadcastAsUser(bcast, UserHandle.ALL);
if (DBG) {
Log.d(TAG, String.format(
"sendTetherStateChangedBroadcast %s=[%s] %s=[%s] %s=[%s] %s=[%s]",
"avail", TextUtils.join(",", availableList),
"local_only", TextUtils.join(",", localOnlyList),
"tether", TextUtils.join(",", tetherList),
"error", TextUtils.join(",", erroredList)));
}
if (usbTethered) {
if (wifiTethered || bluetoothTethered) {
showTetheredNotification(SystemMessage.NOTE_TETHER_GENERAL);
} else {
showTetheredNotification(SystemMessage.NOTE_TETHER_USB);
}
} else if (wifiTethered) {
if (bluetoothTethered) {
showTetheredNotification(SystemMessage.NOTE_TETHER_GENERAL);
} else {
/* We now have a status bar icon for WifiTethering, so drop the notification */
clearTetheredNotification();
}
} else if (bluetoothTethered) {
showTetheredNotification(SystemMessage.NOTE_TETHER_BLUETOOTH);
} else {
clearTetheredNotification();
}
}
private void showTetheredNotification(int id) {
showTetheredNotification(id, true);
}
@VisibleForTesting
protected void showTetheredNotification(int id, boolean tetheringOn) {
NotificationManager notificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager == null) {
return;
}
int icon = 0;
switch(id) {
case SystemMessage.NOTE_TETHER_USB:
icon = com.android.internal.R.drawable.stat_sys_tether_usb;
break;
case SystemMessage.NOTE_TETHER_BLUETOOTH:
icon = com.android.internal.R.drawable.stat_sys_tether_bluetooth;
break;
case SystemMessage.NOTE_TETHER_GENERAL:
default:
icon = com.android.internal.R.drawable.stat_sys_tether_general;
break;
}
if (mLastNotificationId != 0) {
if (mLastNotificationId == icon) {
return;
}
notificationManager.cancelAsUser(null, mLastNotificationId,
UserHandle.ALL);
mLastNotificationId = 0;
}
Intent intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.TetherSettings");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
PendingIntent pi = PendingIntent.getActivityAsUser(mContext, 0, intent, 0,
null, UserHandle.CURRENT);
Resources r = Resources.getSystem();
final CharSequence title;
final CharSequence message;
if (tetheringOn) {
title = r.getText(com.android.internal.R.string.tethered_notification_title);
message = r.getText(com.android.internal.R.string.tethered_notification_message);
} else {
title = r.getText(com.android.internal.R.string.disable_tether_notification_title);
message = r.getText(com.android.internal.R.string.disable_tether_notification_message);
}
if (mTetheredNotificationBuilder == null) {
mTetheredNotificationBuilder =
new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
mTetheredNotificationBuilder.setWhen(0)
.setOngoing(true)
.setColor(mContext.getColor(
com.android.internal.R.color.system_notification_accent_color))
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setCategory(Notification.CATEGORY_STATUS);
}
mTetheredNotificationBuilder.setSmallIcon(icon)
.setContentTitle(title)
.setContentText(message)
.setContentIntent(pi);
mLastNotificationId = id;
notificationManager.notifyAsUser(null, mLastNotificationId,
mTetheredNotificationBuilder.buildInto(new Notification()), UserHandle.ALL);
}
@VisibleForTesting
protected void clearTetheredNotification() {
NotificationManager notificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null && mLastNotificationId != 0) {
notificationManager.cancelAsUser(null, mLastNotificationId,
UserHandle.ALL);
mLastNotificationId = 0;
}
}
private class StateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context content, Intent intent) {
final String action = intent.getAction();
if (action == null) return;
if (action.equals(UsbManager.ACTION_USB_STATE)) {
handleUsbAction(intent);
} else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
handleConnectivityAction(intent);
} else if (action.equals(WifiManager.WIFI_AP_STATE_CHANGED_ACTION)) {
handleWifiApAction(intent);
} else if (action.equals(Intent.ACTION_CONFIGURATION_CHANGED)) {
updateConfiguration();
}
}
private void handleConnectivityAction(Intent intent) {
final NetworkInfo networkInfo = (NetworkInfo)intent.getParcelableExtra(
ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo == null ||
networkInfo.getDetailedState() == NetworkInfo.DetailedState.FAILED) {
return;
}
if (VDBG) Log.d(TAG, "Tethering got CONNECTIVITY_ACTION: " + networkInfo.toString());
mTetherMasterSM.sendMessage(TetherMasterSM.CMD_UPSTREAM_CHANGED);
}
private void handleUsbAction(Intent intent) {
final boolean usbConnected = intent.getBooleanExtra(USB_CONNECTED, false);
final boolean usbConfigured = intent.getBooleanExtra(USB_CONFIGURED, false);
final boolean rndisEnabled = intent.getBooleanExtra(USB_FUNCTION_RNDIS, false);
mLog.log(String.format("USB bcast connected:%s configured:%s rndis:%s",
usbConnected, usbConfigured, rndisEnabled));
// There are three types of ACTION_USB_STATE:
//
// - DISCONNECTED (USB_CONNECTED and USB_CONFIGURED are 0)
// Meaning: USB connection has ended either because of
// software reset or hard unplug.
//
// - CONNECTED (USB_CONNECTED is 1, USB_CONFIGURED is 0)
// Meaning: the first stage of USB protocol handshake has
// occurred but it is not complete.
//
// - CONFIGURED (USB_CONNECTED and USB_CONFIGURED are 1)
// Meaning: the USB handshake is completely done and all the
// functions are ready to use.
//
// For more explanation, see b/62552150 .
synchronized (Tethering.this.mPublicSync) {
// Always record the state of RNDIS.
// TODO: consider:
// final boolean disconnected = !usbConnected;
// if (disconnected) {
// mRndisEnabled = false;
// mUsbTetherRequested = false;
// return;
// }
// final boolean configured = usbConnected && usbConfigured;
// mRndisEnabled = configured ? rndisEnabled : false;
// if (!configured) return;
mRndisEnabled = rndisEnabled;
if (usbConnected && !usbConfigured) {
// Nothing to do here (only CONNECTED, not yet CONFIGURED).
return;
}
// start tethering if we have a request pending
if (usbConfigured && mRndisEnabled && mUsbTetherRequested) {
tetherMatchingInterfaces(
IControlsTethering.STATE_TETHERED,
ConnectivityManager.TETHERING_USB);
}
// TODO: Figure out how to remove the need for this variable.
mUsbTetherRequested = false;
}
}
private void handleWifiApAction(Intent intent) {
final int curState = intent.getIntExtra(EXTRA_WIFI_AP_STATE, WIFI_AP_STATE_DISABLED);
final String ifname = intent.getStringExtra(EXTRA_WIFI_AP_INTERFACE_NAME);
final int ipmode = intent.getIntExtra(EXTRA_WIFI_AP_MODE, IFACE_IP_MODE_UNSPECIFIED);
synchronized (Tethering.this.mPublicSync) {
switch (curState) {
case WifiManager.WIFI_AP_STATE_ENABLING:
// We can see this state on the way to both enabled and failure states.
break;
case WifiManager.WIFI_AP_STATE_ENABLED:
enableWifiIpServingLocked(ifname, ipmode);
break;
case WifiManager.WIFI_AP_STATE_DISABLED:
case WifiManager.WIFI_AP_STATE_DISABLING:
case WifiManager.WIFI_AP_STATE_FAILED:
default:
disableWifiIpServingLocked(ifname, curState);
break;
}
}
}
}
@VisibleForTesting
protected static class TetheringUserRestrictionListener implements UserRestrictionsListener {
private final Tethering mWrapper;
public TetheringUserRestrictionListener(Tethering wrapper) {
mWrapper = wrapper;
}
public void onUserRestrictionsChanged(int userId,
Bundle newRestrictions,
Bundle prevRestrictions) {
final boolean newlyDisallowed =
newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_TETHERING);
final boolean previouslyDisallowed =
prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_TETHERING);
final boolean tetheringDisallowedChanged = (newlyDisallowed != previouslyDisallowed);
if (!tetheringDisallowedChanged) {
return;
}
mWrapper.clearTetheredNotification();
final boolean isTetheringActiveOnDevice = (mWrapper.getTetheredIfaces().length != 0);
if (newlyDisallowed && isTetheringActiveOnDevice) {
mWrapper.showTetheredNotification(
com.android.internal.R.drawable.stat_sys_tether_general, false);
mWrapper.untetherAll();
}
}
}
private void disableWifiIpServingLocked(String ifname, int apState) {
mLog.log("Canceling WiFi tethering request - AP_STATE=" + apState);
// Regardless of whether we requested this transition, the AP has gone
// down. Don't try to tether again unless we're requested to do so.
// TODO: Remove this altogether, once Wi-Fi reliably gives us an
// interface name with every broadcast.
mWifiTetherRequested = false;
if (!TextUtils.isEmpty(ifname)) {
final TetherState ts = mTetherStates.get(ifname);
if (ts != null) {
ts.stateMachine.unwanted();
return;
}
}
for (int i = 0; i < mTetherStates.size(); i++) {
TetherInterfaceStateMachine tism = mTetherStates.valueAt(i).stateMachine;
if (tism.interfaceType() == ConnectivityManager.TETHERING_WIFI) {
tism.unwanted();
return;
}
}
mLog.log("Error disabling Wi-Fi IP serving; " +
(TextUtils.isEmpty(ifname) ? "no interface name specified"
: "specified interface: " + ifname));
}
private void enableWifiIpServingLocked(String ifname, int wifiIpMode) {
// Map wifiIpMode values to IControlsTethering serving states, inferring
// from mWifiTetherRequested as a final "best guess".
final int ipServingMode;
switch (wifiIpMode) {
case IFACE_IP_MODE_TETHERED:
ipServingMode = IControlsTethering.STATE_TETHERED;
break;
case IFACE_IP_MODE_LOCAL_ONLY:
ipServingMode = IControlsTethering.STATE_LOCAL_ONLY;
break;
default:
mLog.e("Cannot enable IP serving in unknown WiFi mode: " + wifiIpMode);
return;
}
if (!TextUtils.isEmpty(ifname)) {
maybeTrackNewInterfaceLocked(ifname, ConnectivityManager.TETHERING_WIFI);
changeInterfaceState(ifname, ipServingMode);
} else {
mLog.e(String.format(
"Cannot enable IP serving in mode %s on missing interface name",
ipServingMode));
}