1 /* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.networkstack.tethering; 18 19 import static android.content.pm.PackageManager.GET_ACTIVITIES; 20 import static android.hardware.usb.UsbManager.USB_CONFIGURED; 21 import static android.hardware.usb.UsbManager.USB_CONNECTED; 22 import static android.hardware.usb.UsbManager.USB_FUNCTION_NCM; 23 import static android.hardware.usb.UsbManager.USB_FUNCTION_RNDIS; 24 import static android.net.ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED; 25 import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED; 26 import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED; 27 import static android.net.RouteInfo.RTN_UNICAST; 28 import static android.net.TetheringManager.ACTION_TETHER_STATE_CHANGED; 29 import static android.net.TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY; 30 import static android.net.TetheringManager.EXTRA_ACTIVE_TETHER; 31 import static android.net.TetheringManager.EXTRA_AVAILABLE_TETHER; 32 import static android.net.TetheringManager.TETHERING_ETHERNET; 33 import static android.net.TetheringManager.TETHERING_NCM; 34 import static android.net.TetheringManager.TETHERING_USB; 35 import static android.net.TetheringManager.TETHERING_WIFI; 36 import static android.net.TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR; 37 import static android.net.TetheringManager.TETHER_ERROR_NO_ERROR; 38 import static android.net.TetheringManager.TETHER_ERROR_UNKNOWN_IFACE; 39 import static android.net.TetheringManager.TETHER_HARDWARE_OFFLOAD_FAILED; 40 import static android.net.TetheringManager.TETHER_HARDWARE_OFFLOAD_STARTED; 41 import static android.net.TetheringManager.TETHER_HARDWARE_OFFLOAD_STOPPED; 42 import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS; 43 import static android.net.shared.Inet4AddressUtils.intToInet4AddressHTH; 44 import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_INTERFACE_NAME; 45 import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_MODE; 46 import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_STATE; 47 import static android.net.wifi.WifiManager.IFACE_IP_MODE_LOCAL_ONLY; 48 import static android.net.wifi.WifiManager.IFACE_IP_MODE_TETHERED; 49 import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLED; 50 import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID; 51 52 import static com.android.networkstack.tethering.TetheringNotificationUpdater.DOWNSTREAM_NONE; 53 import static com.android.networkstack.tethering.UpstreamNetworkMonitor.EVENT_ON_CAPABILITIES; 54 55 import static org.junit.Assert.assertArrayEquals; 56 import static org.junit.Assert.assertEquals; 57 import static org.junit.Assert.assertFalse; 58 import static org.junit.Assert.assertTrue; 59 import static org.junit.Assert.fail; 60 import static org.mockito.ArgumentMatchers.argThat; 61 import static org.mockito.ArgumentMatchers.notNull; 62 import static org.mockito.Matchers.anyInt; 63 import static org.mockito.Matchers.anyString; 64 import static org.mockito.Matchers.eq; 65 import static org.mockito.Mockito.any; 66 import static org.mockito.Mockito.doThrow; 67 import static org.mockito.Mockito.mock; 68 import static org.mockito.Mockito.never; 69 import static org.mockito.Mockito.reset; 70 import static org.mockito.Mockito.spy; 71 import static org.mockito.Mockito.timeout; 72 import static org.mockito.Mockito.times; 73 import static org.mockito.Mockito.verify; 74 import static org.mockito.Mockito.verifyNoMoreInteractions; 75 import static org.mockito.Mockito.when; 76 77 import android.app.usage.NetworkStatsManager; 78 import android.bluetooth.BluetoothAdapter; 79 import android.content.BroadcastReceiver; 80 import android.content.ContentResolver; 81 import android.content.Context; 82 import android.content.Intent; 83 import android.content.IntentFilter; 84 import android.content.pm.ApplicationInfo; 85 import android.content.pm.PackageManager; 86 import android.content.res.Resources; 87 import android.hardware.usb.UsbManager; 88 import android.net.ConnectivityManager; 89 import android.net.EthernetManager; 90 import android.net.EthernetManager.TetheredInterfaceCallback; 91 import android.net.EthernetManager.TetheredInterfaceRequest; 92 import android.net.IIntResultListener; 93 import android.net.INetd; 94 import android.net.ITetheringEventCallback; 95 import android.net.InetAddresses; 96 import android.net.InterfaceConfigurationParcel; 97 import android.net.IpPrefix; 98 import android.net.LinkAddress; 99 import android.net.LinkProperties; 100 import android.net.MacAddress; 101 import android.net.Network; 102 import android.net.NetworkCapabilities; 103 import android.net.NetworkRequest; 104 import android.net.RouteInfo; 105 import android.net.TetherStatesParcel; 106 import android.net.TetheredClient; 107 import android.net.TetheringCallbackStartedParcel; 108 import android.net.TetheringConfigurationParcel; 109 import android.net.TetheringRequestParcel; 110 import android.net.dhcp.DhcpServerCallbacks; 111 import android.net.dhcp.DhcpServingParamsParcel; 112 import android.net.dhcp.IDhcpServer; 113 import android.net.ip.IpNeighborMonitor; 114 import android.net.ip.IpServer; 115 import android.net.ip.RouterAdvertisementDaemon; 116 import android.net.util.InterfaceParams; 117 import android.net.util.NetworkConstants; 118 import android.net.util.SharedLog; 119 import android.net.wifi.WifiConfiguration; 120 import android.net.wifi.WifiManager; 121 import android.net.wifi.p2p.WifiP2pGroup; 122 import android.net.wifi.p2p.WifiP2pInfo; 123 import android.net.wifi.p2p.WifiP2pManager; 124 import android.os.Bundle; 125 import android.os.Handler; 126 import android.os.Looper; 127 import android.os.PersistableBundle; 128 import android.os.RemoteException; 129 import android.os.UserHandle; 130 import android.os.UserManager; 131 import android.os.test.TestLooper; 132 import android.provider.Settings; 133 import android.telephony.CarrierConfigManager; 134 import android.telephony.PhoneStateListener; 135 import android.telephony.TelephonyManager; 136 import android.test.mock.MockContentResolver; 137 138 import androidx.annotation.NonNull; 139 import androidx.test.filters.SmallTest; 140 import androidx.test.runner.AndroidJUnit4; 141 142 import com.android.internal.util.ArrayUtils; 143 import com.android.internal.util.StateMachine; 144 import com.android.internal.util.test.BroadcastInterceptingContext; 145 import com.android.internal.util.test.FakeSettingsProvider; 146 import com.android.testutils.MiscAssertsKt; 147 148 import org.junit.After; 149 import org.junit.AfterClass; 150 import org.junit.Before; 151 import org.junit.BeforeClass; 152 import org.junit.Test; 153 import org.junit.runner.RunWith; 154 import org.mockito.ArgumentCaptor; 155 import org.mockito.Mock; 156 import org.mockito.MockitoAnnotations; 157 158 import java.io.FileDescriptor; 159 import java.io.PrintWriter; 160 import java.net.Inet4Address; 161 import java.net.Inet6Address; 162 import java.util.ArrayList; 163 import java.util.Arrays; 164 import java.util.Collection; 165 import java.util.List; 166 import java.util.Vector; 167 168 @RunWith(AndroidJUnit4.class) 169 @SmallTest 170 public class TetheringTest { 171 private static final int IFINDEX_OFFSET = 100; 172 173 private static final String TEST_MOBILE_IFNAME = "test_rmnet_data0"; 174 private static final String TEST_XLAT_MOBILE_IFNAME = "v4-test_rmnet_data0"; 175 private static final String TEST_USB_IFNAME = "test_rndis0"; 176 private static final String TEST_WIFI_IFNAME = "test_wlan0"; 177 private static final String TEST_WLAN_IFNAME = "test_wlan1"; 178 private static final String TEST_P2P_IFNAME = "test_p2p-p2p0-0"; 179 private static final String TEST_NCM_IFNAME = "test_ncm0"; 180 private static final String TEST_ETH_IFNAME = "test_eth0"; 181 private static final String TETHERING_NAME = "Tethering"; 182 private static final String[] PROVISIONING_APP_NAME = {"some", "app"}; 183 private static final String PROVISIONING_NO_UI_APP_NAME = "no_ui_app"; 184 185 private static final int DHCPSERVER_START_TIMEOUT_MS = 1000; 186 187 @Mock private ApplicationInfo mApplicationInfo; 188 @Mock private Context mContext; 189 @Mock private NetworkStatsManager mStatsManager; 190 @Mock private OffloadHardwareInterface mOffloadHardwareInterface; 191 @Mock private OffloadHardwareInterface.ForwardedStats mForwardedStats; 192 @Mock private Resources mResources; 193 @Mock private TelephonyManager mTelephonyManager; 194 @Mock private UsbManager mUsbManager; 195 @Mock private WifiManager mWifiManager; 196 @Mock private CarrierConfigManager mCarrierConfigManager; 197 @Mock private UpstreamNetworkMonitor mUpstreamNetworkMonitor; 198 @Mock private IPv6TetheringCoordinator mIPv6TetheringCoordinator; 199 @Mock private RouterAdvertisementDaemon mRouterAdvertisementDaemon; 200 @Mock private IpNeighborMonitor mIpNeighborMonitor; 201 @Mock private IDhcpServer mDhcpServer; 202 @Mock private INetd mNetd; 203 @Mock private UserManager mUserManager; 204 @Mock private NetworkRequest mNetworkRequest; 205 @Mock private ConnectivityManager mCm; 206 @Mock private EthernetManager mEm; 207 @Mock private TetheringNotificationUpdater mNotificationUpdater; 208 @Mock private BpfCoordinator mBpfCoordinator; 209 @Mock private PackageManager mPackageManager; 210 211 private final MockIpServerDependencies mIpServerDependencies = 212 spy(new MockIpServerDependencies()); 213 private final MockTetheringDependencies mTetheringDependencies = 214 new MockTetheringDependencies(); 215 216 // Like so many Android system APIs, these cannot be mocked because it is marked final. 217 // We have to use the real versions. 218 private final PersistableBundle mCarrierConfig = new PersistableBundle(); 219 private final TestLooper mLooper = new TestLooper(); 220 221 private Vector<Intent> mIntents; 222 private BroadcastInterceptingContext mServiceContext; 223 private MockContentResolver mContentResolver; 224 private BroadcastReceiver mBroadcastReceiver; 225 private Tethering mTethering; 226 private PhoneStateListener mPhoneStateListener; 227 private InterfaceConfigurationParcel mInterfaceConfiguration; 228 private TetheringConfiguration mConfig; 229 private EntitlementManager mEntitleMgr; 230 private OffloadController mOffloadCtrl; 231 232 private class TestContext extends BroadcastInterceptingContext { TestContext(Context base)233 TestContext(Context base) { 234 super(base); 235 } 236 237 @Override getApplicationInfo()238 public ApplicationInfo getApplicationInfo() { 239 return mApplicationInfo; 240 } 241 242 @Override getContentResolver()243 public ContentResolver getContentResolver() { 244 return mContentResolver; 245 } 246 247 @Override getPackageName()248 public String getPackageName() { 249 return "TetheringTest"; 250 } 251 252 @Override getResources()253 public Resources getResources() { 254 return mResources; 255 } 256 257 @Override getSystemService(String name)258 public Object getSystemService(String name) { 259 if (Context.WIFI_SERVICE.equals(name)) return mWifiManager; 260 if (Context.USB_SERVICE.equals(name)) return mUsbManager; 261 if (Context.TELEPHONY_SERVICE.equals(name)) return mTelephonyManager; 262 if (Context.USER_SERVICE.equals(name)) return mUserManager; 263 if (Context.NETWORK_STATS_SERVICE.equals(name)) return mStatsManager; 264 if (Context.CONNECTIVITY_SERVICE.equals(name)) return mCm; 265 if (Context.ETHERNET_SERVICE.equals(name)) return mEm; 266 return super.getSystemService(name); 267 } 268 269 @Override getPackageManager()270 public PackageManager getPackageManager() { 271 return mPackageManager; 272 } 273 274 @Override getSystemServiceName(Class<?> serviceClass)275 public String getSystemServiceName(Class<?> serviceClass) { 276 if (TelephonyManager.class.equals(serviceClass)) return Context.TELEPHONY_SERVICE; 277 return super.getSystemServiceName(serviceClass); 278 } 279 } 280 281 public class MockIpServerDependencies extends IpServer.Dependencies { 282 @Override getRouterAdvertisementDaemon( InterfaceParams ifParams)283 public RouterAdvertisementDaemon getRouterAdvertisementDaemon( 284 InterfaceParams ifParams) { 285 return mRouterAdvertisementDaemon; 286 } 287 288 @Override getInterfaceParams(String ifName)289 public InterfaceParams getInterfaceParams(String ifName) { 290 assertTrue("Non-mocked interface " + ifName, 291 ifName.equals(TEST_USB_IFNAME) 292 || ifName.equals(TEST_WLAN_IFNAME) 293 || ifName.equals(TEST_MOBILE_IFNAME) 294 || ifName.equals(TEST_P2P_IFNAME) 295 || ifName.equals(TEST_NCM_IFNAME) 296 || ifName.equals(TEST_ETH_IFNAME)); 297 final String[] ifaces = new String[] { 298 TEST_USB_IFNAME, TEST_WLAN_IFNAME, TEST_MOBILE_IFNAME, TEST_P2P_IFNAME, 299 TEST_NCM_IFNAME, TEST_ETH_IFNAME}; 300 return new InterfaceParams(ifName, ArrayUtils.indexOf(ifaces, ifName) + IFINDEX_OFFSET, 301 MacAddress.ALL_ZEROS_ADDRESS); 302 } 303 304 @Override makeDhcpServer(String ifName, DhcpServingParamsParcel params, DhcpServerCallbacks cb)305 public void makeDhcpServer(String ifName, DhcpServingParamsParcel params, 306 DhcpServerCallbacks cb) { 307 new Thread(() -> { 308 try { 309 cb.onDhcpServerCreated(STATUS_SUCCESS, mDhcpServer); 310 } catch (RemoteException e) { 311 fail(e.getMessage()); 312 } 313 }).run(); 314 } 315 getIpNeighborMonitor(Handler h, SharedLog l, IpNeighborMonitor.NeighborEventConsumer c)316 public IpNeighborMonitor getIpNeighborMonitor(Handler h, SharedLog l, 317 IpNeighborMonitor.NeighborEventConsumer c) { 318 return mIpNeighborMonitor; 319 } 320 } 321 322 // MyTetheringConfiguration is used to override static method for testing. 323 private class MyTetheringConfiguration extends TetheringConfiguration { MyTetheringConfiguration(Context ctx, SharedLog log, int id)324 MyTetheringConfiguration(Context ctx, SharedLog log, int id) { 325 super(ctx, log, id); 326 } 327 328 @Override getDeviceConfigProperty(final String name)329 protected String getDeviceConfigProperty(final String name) { 330 return null; 331 } 332 333 @Override getResourcesForSubIdWrapper(Context ctx, int subId)334 protected Resources getResourcesForSubIdWrapper(Context ctx, int subId) { 335 return mResources; 336 } 337 } 338 339 public class MockTetheringDependencies extends TetheringDependencies { 340 StateMachine mUpstreamNetworkMonitorSM; 341 ArrayList<IpServer> mIpv6CoordinatorNotifyList; 342 reset()343 public void reset() { 344 mUpstreamNetworkMonitorSM = null; 345 mIpv6CoordinatorNotifyList = null; 346 } 347 348 @Override getBpfCoordinator( BpfCoordinator.Dependencies deps)349 public BpfCoordinator getBpfCoordinator( 350 BpfCoordinator.Dependencies deps) { 351 return mBpfCoordinator; 352 } 353 354 @Override getOffloadHardwareInterface(Handler h, SharedLog log)355 public OffloadHardwareInterface getOffloadHardwareInterface(Handler h, SharedLog log) { 356 return mOffloadHardwareInterface; 357 } 358 359 @Override getOffloadController(Handler h, SharedLog log, OffloadController.Dependencies deps)360 public OffloadController getOffloadController(Handler h, SharedLog log, 361 OffloadController.Dependencies deps) { 362 mOffloadCtrl = spy(super.getOffloadController(h, log, deps)); 363 // Return real object here instead of mock because 364 // testReportFailCallbackIfOffloadNotSupported depend on real OffloadController object. 365 return mOffloadCtrl; 366 } 367 368 @Override getUpstreamNetworkMonitor(Context ctx, StateMachine target, SharedLog log, int what)369 public UpstreamNetworkMonitor getUpstreamNetworkMonitor(Context ctx, 370 StateMachine target, SharedLog log, int what) { 371 mUpstreamNetworkMonitorSM = target; 372 return mUpstreamNetworkMonitor; 373 } 374 375 @Override getIPv6TetheringCoordinator( ArrayList<IpServer> notifyList, SharedLog log)376 public IPv6TetheringCoordinator getIPv6TetheringCoordinator( 377 ArrayList<IpServer> notifyList, SharedLog log) { 378 mIpv6CoordinatorNotifyList = notifyList; 379 return mIPv6TetheringCoordinator; 380 } 381 382 @Override getIpServerDependencies()383 public IpServer.Dependencies getIpServerDependencies() { 384 return mIpServerDependencies; 385 } 386 387 @Override getDefaultNetworkRequest()388 public NetworkRequest getDefaultNetworkRequest() { 389 return mNetworkRequest; 390 } 391 392 @Override getEntitlementManager(Context ctx, Handler h, SharedLog log, Runnable callback)393 public EntitlementManager getEntitlementManager(Context ctx, Handler h, SharedLog log, 394 Runnable callback) { 395 mEntitleMgr = spy(super.getEntitlementManager(ctx, h, log, callback)); 396 return mEntitleMgr; 397 } 398 399 @Override isTetheringSupported()400 public boolean isTetheringSupported() { 401 return true; 402 } 403 404 @Override generateTetheringConfiguration(Context ctx, SharedLog log, int subId)405 public TetheringConfiguration generateTetheringConfiguration(Context ctx, SharedLog log, 406 int subId) { 407 mConfig = spy(new MyTetheringConfiguration(ctx, log, subId)); 408 return mConfig; 409 } 410 411 @Override getINetd(Context context)412 public INetd getINetd(Context context) { 413 return mNetd; 414 } 415 416 @Override getTetheringLooper()417 public Looper getTetheringLooper() { 418 return mLooper.getLooper(); 419 } 420 421 @Override getContext()422 public Context getContext() { 423 return mServiceContext; 424 } 425 426 @Override getBluetoothAdapter()427 public BluetoothAdapter getBluetoothAdapter() { 428 // TODO: add test for bluetooth tethering. 429 return null; 430 } 431 432 @Override getNotificationUpdater(Context ctx, Looper looper)433 public TetheringNotificationUpdater getNotificationUpdater(Context ctx, Looper looper) { 434 return mNotificationUpdater; 435 } 436 437 @Override isTetheringDenied()438 public boolean isTetheringDenied() { 439 return false; 440 } 441 } 442 buildMobileUpstreamState(boolean withIPv4, boolean withIPv6, boolean with464xlat)443 private static UpstreamNetworkState buildMobileUpstreamState(boolean withIPv4, 444 boolean withIPv6, boolean with464xlat) { 445 final LinkProperties prop = new LinkProperties(); 446 prop.setInterfaceName(TEST_MOBILE_IFNAME); 447 448 if (withIPv4) { 449 prop.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), 450 InetAddresses.parseNumericAddress("10.0.0.1"), 451 TEST_MOBILE_IFNAME, RTN_UNICAST)); 452 } 453 454 if (withIPv6) { 455 prop.addDnsServer(InetAddresses.parseNumericAddress("2001:db8::2")); 456 prop.addLinkAddress( 457 new LinkAddress(InetAddresses.parseNumericAddress("2001:db8::"), 458 NetworkConstants.RFC7421_PREFIX_LENGTH)); 459 prop.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), 460 InetAddresses.parseNumericAddress("2001:db8::1"), 461 TEST_MOBILE_IFNAME, RTN_UNICAST)); 462 } 463 464 if (with464xlat) { 465 final LinkProperties stackedLink = new LinkProperties(); 466 stackedLink.setInterfaceName(TEST_XLAT_MOBILE_IFNAME); 467 stackedLink.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), 468 InetAddresses.parseNumericAddress("192.0.0.1"), 469 TEST_XLAT_MOBILE_IFNAME, RTN_UNICAST)); 470 471 prop.addStackedLink(stackedLink); 472 } 473 474 475 final NetworkCapabilities capabilities = new NetworkCapabilities() 476 .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR); 477 return new UpstreamNetworkState(prop, capabilities, new Network(100)); 478 } 479 buildMobileIPv4UpstreamState()480 private static UpstreamNetworkState buildMobileIPv4UpstreamState() { 481 return buildMobileUpstreamState(true, false, false); 482 } 483 buildMobileIPv6UpstreamState()484 private static UpstreamNetworkState buildMobileIPv6UpstreamState() { 485 return buildMobileUpstreamState(false, true, false); 486 } 487 buildMobileDualStackUpstreamState()488 private static UpstreamNetworkState buildMobileDualStackUpstreamState() { 489 return buildMobileUpstreamState(true, true, false); 490 } 491 buildMobile464xlatUpstreamState()492 private static UpstreamNetworkState buildMobile464xlatUpstreamState() { 493 return buildMobileUpstreamState(false, true, true); 494 } 495 496 // See FakeSettingsProvider#clearSettingsProvider() that this needs to be called before and 497 // after use. 498 @BeforeClass setupOnce()499 public static void setupOnce() { 500 FakeSettingsProvider.clearSettingsProvider(); 501 } 502 503 @AfterClass tearDownOnce()504 public static void tearDownOnce() { 505 FakeSettingsProvider.clearSettingsProvider(); 506 } 507 508 @Before setUp()509 public void setUp() throws Exception { 510 MockitoAnnotations.initMocks(this); 511 when(mResources.getStringArray(R.array.config_tether_dhcp_range)) 512 .thenReturn(new String[0]); 513 when(mResources.getBoolean(R.bool.config_tether_enable_legacy_dhcp_server)).thenReturn( 514 false); 515 when(mNetd.interfaceGetList()) 516 .thenReturn(new String[] { 517 TEST_MOBILE_IFNAME, TEST_WLAN_IFNAME, TEST_USB_IFNAME, TEST_P2P_IFNAME, 518 TEST_NCM_IFNAME, TEST_ETH_IFNAME}); 519 when(mResources.getString(R.string.config_wifi_tether_enable)).thenReturn(""); 520 mInterfaceConfiguration = new InterfaceConfigurationParcel(); 521 mInterfaceConfiguration.flags = new String[0]; 522 when(mRouterAdvertisementDaemon.start()) 523 .thenReturn(true); 524 initOffloadConfiguration(true /* offloadConfig */, true /* offloadControl */, 525 0 /* defaultDisabled */); 526 when(mOffloadHardwareInterface.getForwardedStats(any())).thenReturn(mForwardedStats); 527 528 mServiceContext = new TestContext(mContext); 529 mContentResolver = new MockContentResolver(mServiceContext); 530 mContentResolver.addProvider(Settings.AUTHORITY, new FakeSettingsProvider()); 531 setTetheringSupported(true /* supported */); 532 mIntents = new Vector<>(); 533 mBroadcastReceiver = new BroadcastReceiver() { 534 @Override 535 public void onReceive(Context context, Intent intent) { 536 mIntents.addElement(intent); 537 } 538 }; 539 mServiceContext.registerReceiver(mBroadcastReceiver, 540 new IntentFilter(ACTION_TETHER_STATE_CHANGED)); 541 mTethering = makeTethering(); 542 verify(mStatsManager, times(1)).registerNetworkStatsProvider(anyString(), any()); 543 verify(mNetd).registerUnsolicitedEventListener(any()); 544 final ArgumentCaptor<PhoneStateListener> phoneListenerCaptor = 545 ArgumentCaptor.forClass(PhoneStateListener.class); 546 verify(mTelephonyManager).listen(phoneListenerCaptor.capture(), 547 eq(PhoneStateListener.LISTEN_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGE)); 548 verify(mWifiManager).registerSoftApCallback(any(), any()); 549 mPhoneStateListener = phoneListenerCaptor.getValue(); 550 } 551 setTetheringSupported(final boolean supported)552 private void setTetheringSupported(final boolean supported) { 553 Settings.Global.putInt(mContentResolver, Settings.Global.TETHER_SUPPORTED, 554 supported ? 1 : 0); 555 when(mUserManager.hasUserRestriction( 556 UserManager.DISALLOW_CONFIG_TETHERING)).thenReturn(!supported); 557 // Setup tetherable configuration. 558 when(mResources.getStringArray(R.array.config_tether_usb_regexs)) 559 .thenReturn(new String[] { "test_rndis\\d" }); 560 when(mResources.getStringArray(R.array.config_tether_wifi_regexs)) 561 .thenReturn(new String[]{ "test_wlan\\d" }); 562 when(mResources.getStringArray(R.array.config_tether_wifi_p2p_regexs)) 563 .thenReturn(new String[]{ "test_p2p-p2p\\d-.*" }); 564 when(mResources.getStringArray(R.array.config_tether_bluetooth_regexs)) 565 .thenReturn(new String[0]); 566 when(mResources.getStringArray(R.array.config_tether_ncm_regexs)) 567 .thenReturn(new String[] { "test_ncm\\d" }); 568 when(mResources.getIntArray(R.array.config_tether_upstream_types)).thenReturn(new int[0]); 569 when(mResources.getBoolean(R.bool.config_tether_upstream_automatic)).thenReturn(true); 570 } 571 initTetheringUpstream(UpstreamNetworkState upstreamState)572 private void initTetheringUpstream(UpstreamNetworkState upstreamState) { 573 when(mUpstreamNetworkMonitor.getCurrentPreferredUpstream()).thenReturn(upstreamState); 574 when(mUpstreamNetworkMonitor.selectPreferredUpstreamType(any())).thenReturn(upstreamState); 575 } 576 makeTethering()577 private Tethering makeTethering() { 578 mTetheringDependencies.reset(); 579 return new Tethering(mTetheringDependencies); 580 } 581 createTetheringRequestParcel(final int type)582 private TetheringRequestParcel createTetheringRequestParcel(final int type) { 583 return createTetheringRequestParcel(type, null, null, false); 584 } 585 createTetheringRequestParcel(final int type, final LinkAddress serverAddr, final LinkAddress clientAddr, final boolean exempt)586 private TetheringRequestParcel createTetheringRequestParcel(final int type, 587 final LinkAddress serverAddr, final LinkAddress clientAddr, final boolean exempt) { 588 final TetheringRequestParcel request = new TetheringRequestParcel(); 589 request.tetheringType = type; 590 request.localIPv4Address = serverAddr; 591 request.staticClientAddress = clientAddr; 592 request.exemptFromEntitlementCheck = exempt; 593 request.showProvisioningUi = false; 594 595 return request; 596 } 597 598 @After tearDown()599 public void tearDown() { 600 mServiceContext.unregisterReceiver(mBroadcastReceiver); 601 } 602 sendWifiApStateChanged(int state)603 private void sendWifiApStateChanged(int state) { 604 final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION); 605 intent.putExtra(EXTRA_WIFI_AP_STATE, state); 606 mServiceContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 607 } 608 sendWifiApStateChanged(int state, String ifname, int ipmode)609 private void sendWifiApStateChanged(int state, String ifname, int ipmode) { 610 final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION); 611 intent.putExtra(EXTRA_WIFI_AP_STATE, state); 612 intent.putExtra(EXTRA_WIFI_AP_INTERFACE_NAME, ifname); 613 intent.putExtra(EXTRA_WIFI_AP_MODE, ipmode); 614 mServiceContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 615 } 616 617 private static final String[] P2P_RECEIVER_PERMISSIONS_FOR_BROADCAST = { 618 android.Manifest.permission.ACCESS_FINE_LOCATION, 619 android.Manifest.permission.ACCESS_WIFI_STATE 620 }; 621 sendWifiP2pConnectionChanged( boolean isGroupFormed, boolean isGroupOwner, String ifname)622 private void sendWifiP2pConnectionChanged( 623 boolean isGroupFormed, boolean isGroupOwner, String ifname) { 624 WifiP2pGroup group = null; 625 WifiP2pInfo p2pInfo = new WifiP2pInfo(); 626 p2pInfo.groupFormed = isGroupFormed; 627 if (isGroupFormed) { 628 p2pInfo.isGroupOwner = isGroupOwner; 629 group = mock(WifiP2pGroup.class); 630 when(group.isGroupOwner()).thenReturn(isGroupOwner); 631 when(group.getInterface()).thenReturn(ifname); 632 } 633 634 final Intent intent = mock(Intent.class); 635 when(intent.getAction()).thenReturn(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); 636 when(intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_INFO)).thenReturn(p2pInfo); 637 when(intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_GROUP)).thenReturn(group); 638 639 mServiceContext.sendBroadcastAsUserMultiplePermissions(intent, UserHandle.ALL, 640 P2P_RECEIVER_PERMISSIONS_FOR_BROADCAST); 641 } 642 sendUsbBroadcast(boolean connected, boolean configured, boolean function, int type)643 private void sendUsbBroadcast(boolean connected, boolean configured, boolean function, 644 int type) { 645 final Intent intent = new Intent(UsbManager.ACTION_USB_STATE); 646 intent.putExtra(USB_CONNECTED, connected); 647 intent.putExtra(USB_CONFIGURED, configured); 648 if (type == TETHERING_USB) { 649 intent.putExtra(USB_FUNCTION_RNDIS, function); 650 } else { 651 intent.putExtra(USB_FUNCTION_NCM, function); 652 } 653 mServiceContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 654 } 655 sendConfigurationChanged()656 private void sendConfigurationChanged() { 657 final Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED); 658 mServiceContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 659 } 660 verifyInterfaceServingModeStarted(String ifname)661 private void verifyInterfaceServingModeStarted(String ifname) throws Exception { 662 verify(mNetd, times(1)).interfaceSetCfg(any(InterfaceConfigurationParcel.class)); 663 verify(mNetd, times(1)).tetherInterfaceAdd(ifname); 664 verify(mNetd, times(1)).networkAddInterface(INetd.LOCAL_NET_ID, ifname); 665 verify(mNetd, times(2)).networkAddRoute(eq(INetd.LOCAL_NET_ID), eq(ifname), 666 anyString(), anyString()); 667 } 668 verifyTetheringBroadcast(String ifname, String whichExtra)669 private void verifyTetheringBroadcast(String ifname, String whichExtra) { 670 // Verify that ifname is in the whichExtra array of the tether state changed broadcast. 671 final Intent bcast = mIntents.get(0); 672 assertEquals(ACTION_TETHER_STATE_CHANGED, bcast.getAction()); 673 final ArrayList<String> ifnames = bcast.getStringArrayListExtra(whichExtra); 674 assertTrue(ifnames.contains(ifname)); 675 mIntents.remove(bcast); 676 } 677 failingLocalOnlyHotspotLegacyApBroadcast( boolean emulateInterfaceStatusChanged)678 public void failingLocalOnlyHotspotLegacyApBroadcast( 679 boolean emulateInterfaceStatusChanged) throws Exception { 680 // Emulate externally-visible WifiManager effects, causing the 681 // per-interface state machine to start up, and telling us that 682 // hotspot mode is to be started. 683 if (emulateInterfaceStatusChanged) { 684 mTethering.interfaceStatusChanged(TEST_WLAN_IFNAME, true); 685 } 686 sendWifiApStateChanged(WIFI_AP_STATE_ENABLED); 687 mLooper.dispatchAll(); 688 689 // If, and only if, Tethering received an interface status changed then 690 // it creates a IpServer and sends out a broadcast indicating that the 691 // interface is "available". 692 if (emulateInterfaceStatusChanged) { 693 // There is 1 IpServer state change event: STATE_AVAILABLE 694 verify(mNotificationUpdater, times(1)).onDownstreamChanged(DOWNSTREAM_NONE); 695 verifyTetheringBroadcast(TEST_WLAN_IFNAME, EXTRA_AVAILABLE_TETHER); 696 verify(mWifiManager).updateInterfaceIpState( 697 TEST_WLAN_IFNAME, WifiManager.IFACE_IP_MODE_UNSPECIFIED); 698 } 699 verifyNoMoreInteractions(mNetd); 700 verifyNoMoreInteractions(mWifiManager); 701 } 702 prepareNcmTethering()703 private void prepareNcmTethering() { 704 // Emulate startTethering(TETHERING_NCM) called 705 mTethering.startTethering(createTetheringRequestParcel(TETHERING_NCM), null); 706 mLooper.dispatchAll(); 707 verify(mUsbManager, times(1)).setCurrentFunctions(UsbManager.FUNCTION_NCM); 708 709 mTethering.interfaceStatusChanged(TEST_NCM_IFNAME, true); 710 } 711 prepareUsbTethering(UpstreamNetworkState upstreamState)712 private void prepareUsbTethering(UpstreamNetworkState upstreamState) { 713 initTetheringUpstream(upstreamState); 714 715 // Emulate pressing the USB tethering button in Settings UI. 716 mTethering.startTethering(createTetheringRequestParcel(TETHERING_USB), null); 717 mLooper.dispatchAll(); 718 verify(mUsbManager, times(1)).setCurrentFunctions(UsbManager.FUNCTION_RNDIS); 719 720 mTethering.interfaceStatusChanged(TEST_USB_IFNAME, true); 721 } 722 723 @Test testUsbConfiguredBroadcastStartsTethering()724 public void testUsbConfiguredBroadcastStartsTethering() throws Exception { 725 UpstreamNetworkState upstreamState = buildMobileIPv4UpstreamState(); 726 prepareUsbTethering(upstreamState); 727 728 // This should produce no activity of any kind. 729 verifyNoMoreInteractions(mNetd); 730 731 // Pretend we then receive USB configured broadcast. 732 sendUsbBroadcast(true, true, true, TETHERING_USB); 733 mLooper.dispatchAll(); 734 // Now we should see the start of tethering mechanics (in this case: 735 // tetherMatchingInterfaces() which starts by fetching all interfaces). 736 verify(mNetd, times(1)).interfaceGetList(); 737 738 // UpstreamNetworkMonitor should receive selected upstream 739 verify(mUpstreamNetworkMonitor, times(1)).getCurrentPreferredUpstream(); 740 verify(mUpstreamNetworkMonitor, times(1)).setCurrentUpstream(upstreamState.network); 741 } 742 743 @Test failingLocalOnlyHotspotLegacyApBroadcastWithIfaceStatusChanged()744 public void failingLocalOnlyHotspotLegacyApBroadcastWithIfaceStatusChanged() throws Exception { 745 failingLocalOnlyHotspotLegacyApBroadcast(true); 746 } 747 748 @Test failingLocalOnlyHotspotLegacyApBroadcastSansIfaceStatusChanged()749 public void failingLocalOnlyHotspotLegacyApBroadcastSansIfaceStatusChanged() throws Exception { 750 failingLocalOnlyHotspotLegacyApBroadcast(false); 751 } 752 workingLocalOnlyHotspotEnrichedApBroadcast( boolean emulateInterfaceStatusChanged)753 public void workingLocalOnlyHotspotEnrichedApBroadcast( 754 boolean emulateInterfaceStatusChanged) throws Exception { 755 // Emulate externally-visible WifiManager effects, causing the 756 // per-interface state machine to start up, and telling us that 757 // hotspot mode is to be started. 758 if (emulateInterfaceStatusChanged) { 759 mTethering.interfaceStatusChanged(TEST_WLAN_IFNAME, true); 760 } 761 sendWifiApStateChanged(WIFI_AP_STATE_ENABLED, TEST_WLAN_IFNAME, IFACE_IP_MODE_LOCAL_ONLY); 762 mLooper.dispatchAll(); 763 764 verifyInterfaceServingModeStarted(TEST_WLAN_IFNAME); 765 verifyTetheringBroadcast(TEST_WLAN_IFNAME, EXTRA_AVAILABLE_TETHER); 766 verify(mNetd, times(1)).ipfwdEnableForwarding(TETHERING_NAME); 767 verify(mNetd, times(1)).tetherStartWithConfiguration(any()); 768 verifyNoMoreInteractions(mNetd); 769 verify(mWifiManager).updateInterfaceIpState( 770 TEST_WLAN_IFNAME, WifiManager.IFACE_IP_MODE_UNSPECIFIED); 771 verify(mWifiManager).updateInterfaceIpState( 772 TEST_WLAN_IFNAME, WifiManager.IFACE_IP_MODE_LOCAL_ONLY); 773 verifyNoMoreInteractions(mWifiManager); 774 verifyTetheringBroadcast(TEST_WLAN_IFNAME, EXTRA_ACTIVE_LOCAL_ONLY); 775 verify(mUpstreamNetworkMonitor, times(1)).startObserveAllNetworks(); 776 // There are 2 IpServer state change events: STATE_AVAILABLE -> STATE_LOCAL_ONLY 777 verify(mNotificationUpdater, times(2)).onDownstreamChanged(DOWNSTREAM_NONE); 778 779 // Emulate externally-visible WifiManager effects, when hotspot mode 780 // is being torn down. 781 sendWifiApStateChanged(WifiManager.WIFI_AP_STATE_DISABLED); 782 mTethering.interfaceRemoved(TEST_WLAN_IFNAME); 783 mLooper.dispatchAll(); 784 785 verify(mNetd, times(1)).tetherApplyDnsInterfaces(); 786 verify(mNetd, times(1)).tetherInterfaceRemove(TEST_WLAN_IFNAME); 787 verify(mNetd, times(1)).networkRemoveInterface(INetd.LOCAL_NET_ID, TEST_WLAN_IFNAME); 788 // interfaceSetCfg() called once for enabling and twice disabling IPv4. 789 verify(mNetd, times(3)).interfaceSetCfg(any(InterfaceConfigurationParcel.class)); 790 verify(mNetd, times(1)).tetherStop(); 791 verify(mNetd, times(1)).ipfwdDisableForwarding(TETHERING_NAME); 792 verify(mWifiManager, times(3)).updateInterfaceIpState( 793 TEST_WLAN_IFNAME, WifiManager.IFACE_IP_MODE_UNSPECIFIED); 794 verifyNoMoreInteractions(mNetd); 795 verifyNoMoreInteractions(mWifiManager); 796 // Asking for the last error after the per-interface state machine 797 // has been reaped yields an unknown interface error. 798 assertEquals(TETHER_ERROR_UNKNOWN_IFACE, mTethering.getLastTetherError(TEST_WLAN_IFNAME)); 799 } 800 801 /** 802 * Send CMD_IPV6_TETHER_UPDATE to IpServers as would be done by IPv6TetheringCoordinator. 803 */ sendIPv6TetherUpdates(UpstreamNetworkState upstreamState)804 private void sendIPv6TetherUpdates(UpstreamNetworkState upstreamState) { 805 // IPv6TetheringCoordinator must have been notified of downstream 806 verify(mIPv6TetheringCoordinator, times(1)).addActiveDownstream( 807 argThat(sm -> sm.linkProperties().getInterfaceName().equals(TEST_USB_IFNAME)), 808 eq(IpServer.STATE_TETHERED)); 809 810 for (IpServer ipSrv : mTetheringDependencies.mIpv6CoordinatorNotifyList) { 811 UpstreamNetworkState ipv6OnlyState = buildMobileUpstreamState(false, true, false); 812 ipSrv.sendMessage(IpServer.CMD_IPV6_TETHER_UPDATE, 0, 0, 813 upstreamState.linkProperties.isIpv6Provisioned() 814 ? ipv6OnlyState.linkProperties 815 : null); 816 } 817 mLooper.dispatchAll(); 818 } 819 runUsbTethering(UpstreamNetworkState upstreamState)820 private void runUsbTethering(UpstreamNetworkState upstreamState) { 821 prepareUsbTethering(upstreamState); 822 sendUsbBroadcast(true, true, true, TETHERING_USB); 823 mLooper.dispatchAll(); 824 } 825 826 @Test workingMobileUsbTethering_IPv4()827 public void workingMobileUsbTethering_IPv4() throws Exception { 828 UpstreamNetworkState upstreamState = buildMobileIPv4UpstreamState(); 829 runUsbTethering(upstreamState); 830 831 verify(mNetd, times(1)).tetherAddForward(TEST_USB_IFNAME, TEST_MOBILE_IFNAME); 832 verify(mNetd, times(1)).ipfwdAddInterfaceForward(TEST_USB_IFNAME, TEST_MOBILE_IFNAME); 833 834 sendIPv6TetherUpdates(upstreamState); 835 verify(mRouterAdvertisementDaemon, never()).buildNewRa(any(), notNull()); 836 verify(mDhcpServer, timeout(DHCPSERVER_START_TIMEOUT_MS).times(1)).startWithCallbacks( 837 any(), any()); 838 } 839 840 @Test workingMobileUsbTethering_IPv4LegacyDhcp()841 public void workingMobileUsbTethering_IPv4LegacyDhcp() { 842 when(mResources.getBoolean(R.bool.config_tether_enable_legacy_dhcp_server)).thenReturn( 843 true); 844 sendConfigurationChanged(); 845 final UpstreamNetworkState upstreamState = buildMobileIPv4UpstreamState(); 846 runUsbTethering(upstreamState); 847 sendIPv6TetherUpdates(upstreamState); 848 849 verify(mIpServerDependencies, never()).makeDhcpServer(any(), any(), any()); 850 } 851 852 @Test workingMobileUsbTethering_IPv6()853 public void workingMobileUsbTethering_IPv6() throws Exception { 854 UpstreamNetworkState upstreamState = buildMobileIPv6UpstreamState(); 855 runUsbTethering(upstreamState); 856 857 verify(mNetd, times(1)).tetherAddForward(TEST_USB_IFNAME, TEST_MOBILE_IFNAME); 858 verify(mNetd, times(1)).ipfwdAddInterfaceForward(TEST_USB_IFNAME, TEST_MOBILE_IFNAME); 859 860 sendIPv6TetherUpdates(upstreamState); 861 verify(mRouterAdvertisementDaemon, times(1)).buildNewRa(any(), notNull()); 862 verify(mNetd, times(1)).tetherApplyDnsInterfaces(); 863 } 864 865 @Test workingMobileUsbTethering_DualStack()866 public void workingMobileUsbTethering_DualStack() throws Exception { 867 UpstreamNetworkState upstreamState = buildMobileDualStackUpstreamState(); 868 runUsbTethering(upstreamState); 869 870 verify(mNetd, times(1)).tetherAddForward(TEST_USB_IFNAME, TEST_MOBILE_IFNAME); 871 verify(mNetd, times(1)).ipfwdAddInterfaceForward(TEST_USB_IFNAME, TEST_MOBILE_IFNAME); 872 verify(mRouterAdvertisementDaemon, times(1)).start(); 873 verify(mDhcpServer, timeout(DHCPSERVER_START_TIMEOUT_MS).times(1)).startWithCallbacks( 874 any(), any()); 875 876 sendIPv6TetherUpdates(upstreamState); 877 verify(mRouterAdvertisementDaemon, times(1)).buildNewRa(any(), notNull()); 878 verify(mNetd, times(1)).tetherApplyDnsInterfaces(); 879 } 880 881 @Test workingMobileUsbTethering_MultipleUpstreams()882 public void workingMobileUsbTethering_MultipleUpstreams() throws Exception { 883 UpstreamNetworkState upstreamState = buildMobile464xlatUpstreamState(); 884 runUsbTethering(upstreamState); 885 886 verify(mNetd, times(1)).tetherAddForward(TEST_USB_IFNAME, TEST_XLAT_MOBILE_IFNAME); 887 verify(mNetd, times(1)).tetherAddForward(TEST_USB_IFNAME, TEST_MOBILE_IFNAME); 888 verify(mDhcpServer, timeout(DHCPSERVER_START_TIMEOUT_MS).times(1)).startWithCallbacks( 889 any(), any()); 890 verify(mNetd, times(1)).ipfwdAddInterfaceForward(TEST_USB_IFNAME, TEST_XLAT_MOBILE_IFNAME); 891 verify(mNetd, times(1)).ipfwdAddInterfaceForward(TEST_USB_IFNAME, TEST_MOBILE_IFNAME); 892 893 sendIPv6TetherUpdates(upstreamState); 894 verify(mRouterAdvertisementDaemon, times(1)).buildNewRa(any(), notNull()); 895 verify(mNetd, times(1)).tetherApplyDnsInterfaces(); 896 } 897 898 @Test workingMobileUsbTethering_v6Then464xlat()899 public void workingMobileUsbTethering_v6Then464xlat() throws Exception { 900 // Setup IPv6 901 UpstreamNetworkState upstreamState = buildMobileIPv6UpstreamState(); 902 runUsbTethering(upstreamState); 903 904 verify(mNetd, times(1)).tetherAddForward(TEST_USB_IFNAME, TEST_MOBILE_IFNAME); 905 verify(mDhcpServer, timeout(DHCPSERVER_START_TIMEOUT_MS).times(1)).startWithCallbacks( 906 any(), any()); 907 verify(mNetd, times(1)).ipfwdAddInterfaceForward(TEST_USB_IFNAME, TEST_MOBILE_IFNAME); 908 909 // Then 464xlat comes up 910 upstreamState = buildMobile464xlatUpstreamState(); 911 initTetheringUpstream(upstreamState); 912 913 // Upstream LinkProperties changed: UpstreamNetworkMonitor sends EVENT_ON_LINKPROPERTIES. 914 mTetheringDependencies.mUpstreamNetworkMonitorSM.sendMessage( 915 Tethering.TetherMainSM.EVENT_UPSTREAM_CALLBACK, 916 UpstreamNetworkMonitor.EVENT_ON_LINKPROPERTIES, 917 0, 918 upstreamState); 919 mLooper.dispatchAll(); 920 921 // Forwarding is added for 464xlat 922 verify(mNetd, times(1)).tetherAddForward(TEST_USB_IFNAME, TEST_XLAT_MOBILE_IFNAME); 923 verify(mNetd, times(1)).ipfwdAddInterfaceForward(TEST_USB_IFNAME, TEST_XLAT_MOBILE_IFNAME); 924 // Forwarding was not re-added for v6 (still times(1)) 925 verify(mNetd, times(1)).tetherAddForward(TEST_USB_IFNAME, TEST_MOBILE_IFNAME); 926 verify(mNetd, times(1)).ipfwdAddInterfaceForward(TEST_USB_IFNAME, TEST_MOBILE_IFNAME); 927 // DHCP not restarted on downstream (still times(1)) 928 verify(mDhcpServer, timeout(DHCPSERVER_START_TIMEOUT_MS).times(1)).startWithCallbacks( 929 any(), any()); 930 } 931 932 @Test configTetherUpstreamAutomaticIgnoresConfigTetherUpstreamTypes()933 public void configTetherUpstreamAutomaticIgnoresConfigTetherUpstreamTypes() throws Exception { 934 when(mResources.getBoolean(R.bool.config_tether_upstream_automatic)).thenReturn(true); 935 sendConfigurationChanged(); 936 937 // Setup IPv6 938 final UpstreamNetworkState upstreamState = buildMobileIPv6UpstreamState(); 939 runUsbTethering(upstreamState); 940 941 // UpstreamNetworkMonitor should choose upstream automatically 942 // (in this specific case: choose the default network). 943 verify(mUpstreamNetworkMonitor, times(1)).getCurrentPreferredUpstream(); 944 verify(mUpstreamNetworkMonitor, never()).selectPreferredUpstreamType(any()); 945 946 verify(mUpstreamNetworkMonitor, times(1)).setCurrentUpstream(upstreamState.network); 947 } 948 runNcmTethering()949 private void runNcmTethering() { 950 prepareNcmTethering(); 951 sendUsbBroadcast(true, true, true, TETHERING_NCM); 952 mLooper.dispatchAll(); 953 } 954 955 @Test workingNcmTethering()956 public void workingNcmTethering() throws Exception { 957 runNcmTethering(); 958 959 verify(mDhcpServer, timeout(DHCPSERVER_START_TIMEOUT_MS).times(1)).startWithCallbacks( 960 any(), any()); 961 } 962 963 @Test workingNcmTethering_LegacyDhcp()964 public void workingNcmTethering_LegacyDhcp() { 965 when(mResources.getBoolean(R.bool.config_tether_enable_legacy_dhcp_server)).thenReturn( 966 true); 967 sendConfigurationChanged(); 968 runNcmTethering(); 969 970 verify(mIpServerDependencies, never()).makeDhcpServer(any(), any(), any()); 971 } 972 973 @Test workingLocalOnlyHotspotEnrichedApBroadcastWithIfaceChanged()974 public void workingLocalOnlyHotspotEnrichedApBroadcastWithIfaceChanged() throws Exception { 975 workingLocalOnlyHotspotEnrichedApBroadcast(true); 976 } 977 978 @Test workingLocalOnlyHotspotEnrichedApBroadcastSansIfaceChanged()979 public void workingLocalOnlyHotspotEnrichedApBroadcastSansIfaceChanged() throws Exception { 980 workingLocalOnlyHotspotEnrichedApBroadcast(false); 981 } 982 983 // TODO: Test with and without interfaceStatusChanged(). 984 @Test failingWifiTetheringLegacyApBroadcast()985 public void failingWifiTetheringLegacyApBroadcast() throws Exception { 986 when(mWifiManager.startSoftAp(any(WifiConfiguration.class))).thenReturn(true); 987 988 // Emulate pressing the WiFi tethering button. 989 mTethering.startTethering(createTetheringRequestParcel(TETHERING_WIFI), null); 990 mLooper.dispatchAll(); 991 verify(mWifiManager, times(1)).startSoftAp(null); 992 verifyNoMoreInteractions(mWifiManager); 993 verifyNoMoreInteractions(mNetd); 994 995 // Emulate externally-visible WifiManager effects, causing the 996 // per-interface state machine to start up, and telling us that 997 // tethering mode is to be started. 998 mTethering.interfaceStatusChanged(TEST_WLAN_IFNAME, true); 999 sendWifiApStateChanged(WIFI_AP_STATE_ENABLED); 1000 mLooper.dispatchAll(); 1001 1002 // There is 1 IpServer state change event: STATE_AVAILABLE 1003 verify(mNotificationUpdater, times(1)).onDownstreamChanged(DOWNSTREAM_NONE); 1004 verifyTetheringBroadcast(TEST_WLAN_IFNAME, EXTRA_AVAILABLE_TETHER); 1005 verify(mWifiManager).updateInterfaceIpState( 1006 TEST_WLAN_IFNAME, WifiManager.IFACE_IP_MODE_UNSPECIFIED); 1007 verifyNoMoreInteractions(mNetd); 1008 verifyNoMoreInteractions(mWifiManager); 1009 } 1010 1011 // TODO: Test with and without interfaceStatusChanged(). 1012 @Test workingWifiTetheringEnrichedApBroadcast()1013 public void workingWifiTetheringEnrichedApBroadcast() throws Exception { 1014 when(mWifiManager.startSoftAp(any(WifiConfiguration.class))).thenReturn(true); 1015 1016 // Emulate pressing the WiFi tethering button. 1017 mTethering.startTethering(createTetheringRequestParcel(TETHERING_WIFI), null); 1018 mLooper.dispatchAll(); 1019 verify(mWifiManager, times(1)).startSoftAp(null); 1020 verifyNoMoreInteractions(mWifiManager); 1021 verifyNoMoreInteractions(mNetd); 1022 1023 // Emulate externally-visible WifiManager effects, causing the 1024 // per-interface state machine to start up, and telling us that 1025 // tethering mode is to be started. 1026 mTethering.interfaceStatusChanged(TEST_WLAN_IFNAME, true); 1027 sendWifiApStateChanged(WIFI_AP_STATE_ENABLED, TEST_WLAN_IFNAME, IFACE_IP_MODE_TETHERED); 1028 mLooper.dispatchAll(); 1029 1030 verifyInterfaceServingModeStarted(TEST_WLAN_IFNAME); 1031 verifyTetheringBroadcast(TEST_WLAN_IFNAME, EXTRA_AVAILABLE_TETHER); 1032 verify(mNetd, times(1)).ipfwdEnableForwarding(TETHERING_NAME); 1033 verify(mNetd, times(1)).tetherStartWithConfiguration(any()); 1034 verify(mNetd, times(2)).networkAddRoute(eq(INetd.LOCAL_NET_ID), eq(TEST_WLAN_IFNAME), 1035 anyString(), anyString()); 1036 verifyNoMoreInteractions(mNetd); 1037 verify(mWifiManager).updateInterfaceIpState( 1038 TEST_WLAN_IFNAME, WifiManager.IFACE_IP_MODE_UNSPECIFIED); 1039 verify(mWifiManager).updateInterfaceIpState( 1040 TEST_WLAN_IFNAME, WifiManager.IFACE_IP_MODE_TETHERED); 1041 verifyNoMoreInteractions(mWifiManager); 1042 verifyTetheringBroadcast(TEST_WLAN_IFNAME, EXTRA_ACTIVE_TETHER); 1043 verify(mUpstreamNetworkMonitor, times(1)).startObserveAllNetworks(); 1044 // In tethering mode, in the default configuration, an explicit request 1045 // for a mobile network is also made. 1046 verify(mUpstreamNetworkMonitor, times(1)).registerMobileNetworkRequest(); 1047 // There are 2 IpServer state change events: STATE_AVAILABLE -> STATE_TETHERED 1048 verify(mNotificationUpdater, times(1)).onDownstreamChanged(DOWNSTREAM_NONE); 1049 verify(mNotificationUpdater, times(1)).onDownstreamChanged(eq(1 << TETHERING_WIFI)); 1050 1051 ///// 1052 // We do not currently emulate any upstream being found. 1053 // 1054 // This is why there are no calls to verify mNetd.tetherAddForward() or 1055 // mNetd.ipfwdAddInterfaceForward(). 1056 ///// 1057 1058 // Emulate pressing the WiFi tethering button. 1059 mTethering.stopTethering(TETHERING_WIFI); 1060 mLooper.dispatchAll(); 1061 verify(mWifiManager, times(1)).stopSoftAp(); 1062 verifyNoMoreInteractions(mWifiManager); 1063 verifyNoMoreInteractions(mNetd); 1064 1065 // Emulate externally-visible WifiManager effects, when tethering mode 1066 // is being torn down. 1067 sendWifiApStateChanged(WifiManager.WIFI_AP_STATE_DISABLED); 1068 mTethering.interfaceRemoved(TEST_WLAN_IFNAME); 1069 mLooper.dispatchAll(); 1070 1071 verify(mNetd, times(1)).tetherApplyDnsInterfaces(); 1072 verify(mNetd, times(1)).tetherInterfaceRemove(TEST_WLAN_IFNAME); 1073 verify(mNetd, times(1)).networkRemoveInterface(INetd.LOCAL_NET_ID, TEST_WLAN_IFNAME); 1074 // interfaceSetCfg() called once for enabling and twice for disabling IPv4. 1075 verify(mNetd, times(3)).interfaceSetCfg(any(InterfaceConfigurationParcel.class)); 1076 verify(mNetd, times(1)).tetherStop(); 1077 verify(mNetd, times(1)).ipfwdDisableForwarding(TETHERING_NAME); 1078 verify(mWifiManager, times(3)).updateInterfaceIpState( 1079 TEST_WLAN_IFNAME, WifiManager.IFACE_IP_MODE_UNSPECIFIED); 1080 verifyNoMoreInteractions(mNetd); 1081 verifyNoMoreInteractions(mWifiManager); 1082 // Asking for the last error after the per-interface state machine 1083 // has been reaped yields an unknown interface error. 1084 assertEquals(TETHER_ERROR_UNKNOWN_IFACE, mTethering.getLastTetherError(TEST_WLAN_IFNAME)); 1085 } 1086 1087 // TODO: Test with and without interfaceStatusChanged(). 1088 @Test failureEnablingIpForwarding()1089 public void failureEnablingIpForwarding() throws Exception { 1090 when(mWifiManager.startSoftAp(any(WifiConfiguration.class))).thenReturn(true); 1091 doThrow(new RemoteException()).when(mNetd).ipfwdEnableForwarding(TETHERING_NAME); 1092 1093 // Emulate pressing the WiFi tethering button. 1094 mTethering.startTethering(createTetheringRequestParcel(TETHERING_WIFI), null); 1095 mLooper.dispatchAll(); 1096 verify(mWifiManager, times(1)).startSoftAp(null); 1097 verifyNoMoreInteractions(mWifiManager); 1098 verifyNoMoreInteractions(mNetd); 1099 1100 // Emulate externally-visible WifiManager effects, causing the 1101 // per-interface state machine to start up, and telling us that 1102 // tethering mode is to be started. 1103 mTethering.interfaceStatusChanged(TEST_WLAN_IFNAME, true); 1104 sendWifiApStateChanged(WIFI_AP_STATE_ENABLED, TEST_WLAN_IFNAME, IFACE_IP_MODE_TETHERED); 1105 mLooper.dispatchAll(); 1106 1107 // We verify get/set called three times here: twice for setup and once during 1108 // teardown because all events happen over the course of the single 1109 // dispatchAll() above. Note that once the IpServer IPv4 address config 1110 // code is refactored the two calls during shutdown will revert to one. 1111 verify(mNetd, times(3)).interfaceSetCfg(argThat(p -> TEST_WLAN_IFNAME.equals(p.ifName))); 1112 verify(mNetd, times(1)).tetherInterfaceAdd(TEST_WLAN_IFNAME); 1113 verify(mNetd, times(1)).networkAddInterface(INetd.LOCAL_NET_ID, TEST_WLAN_IFNAME); 1114 verify(mNetd, times(2)).networkAddRoute(eq(INetd.LOCAL_NET_ID), eq(TEST_WLAN_IFNAME), 1115 anyString(), anyString()); 1116 verify(mWifiManager).updateInterfaceIpState( 1117 TEST_WLAN_IFNAME, WifiManager.IFACE_IP_MODE_UNSPECIFIED); 1118 verify(mWifiManager).updateInterfaceIpState( 1119 TEST_WLAN_IFNAME, WifiManager.IFACE_IP_MODE_TETHERED); 1120 // There are 3 IpServer state change event: 1121 // STATE_AVAILABLE -> STATE_TETHERED -> STATE_AVAILABLE. 1122 verify(mNotificationUpdater, times(2)).onDownstreamChanged(DOWNSTREAM_NONE); 1123 verify(mNotificationUpdater, times(1)).onDownstreamChanged(eq(1 << TETHERING_WIFI)); 1124 verifyTetheringBroadcast(TEST_WLAN_IFNAME, EXTRA_AVAILABLE_TETHER); 1125 // This is called, but will throw. 1126 verify(mNetd, times(1)).ipfwdEnableForwarding(TETHERING_NAME); 1127 // This never gets called because of the exception thrown above. 1128 verify(mNetd, times(0)).tetherStartWithConfiguration(any()); 1129 // When the main state machine transitions to an error state it tells 1130 // downstream interfaces, which causes us to tell Wi-Fi about the error 1131 // so it can take down AP mode. 1132 verify(mNetd, times(1)).tetherApplyDnsInterfaces(); 1133 verify(mNetd, times(1)).tetherInterfaceRemove(TEST_WLAN_IFNAME); 1134 verify(mNetd, times(1)).networkRemoveInterface(INetd.LOCAL_NET_ID, TEST_WLAN_IFNAME); 1135 verify(mWifiManager).updateInterfaceIpState( 1136 TEST_WLAN_IFNAME, WifiManager.IFACE_IP_MODE_CONFIGURATION_ERROR); 1137 1138 verifyNoMoreInteractions(mWifiManager); 1139 verifyNoMoreInteractions(mNetd); 1140 } 1141 runUserRestrictionsChange( boolean currentDisallow, boolean nextDisallow, boolean isTetheringActive, int expectedInteractionsWithShowNotification)1142 private void runUserRestrictionsChange( 1143 boolean currentDisallow, boolean nextDisallow, boolean isTetheringActive, 1144 int expectedInteractionsWithShowNotification) throws Exception { 1145 final Bundle newRestrictions = new Bundle(); 1146 newRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_TETHERING, nextDisallow); 1147 final Tethering mockTethering = mock(Tethering.class); 1148 when(mockTethering.isTetheringActive()).thenReturn(isTetheringActive); 1149 when(mUserManager.getUserRestrictions()).thenReturn(newRestrictions); 1150 1151 final Tethering.UserRestrictionActionListener ural = 1152 new Tethering.UserRestrictionActionListener( 1153 mUserManager, mockTethering, mNotificationUpdater); 1154 ural.mDisallowTethering = currentDisallow; 1155 1156 ural.onUserRestrictionsChanged(); 1157 1158 verify(mNotificationUpdater, times(expectedInteractionsWithShowNotification)) 1159 .notifyTetheringDisabledByRestriction(); 1160 verify(mockTethering, times(expectedInteractionsWithShowNotification)).untetherAll(); 1161 } 1162 1163 @Test testDisallowTetheringWhenTetheringIsNotActive()1164 public void testDisallowTetheringWhenTetheringIsNotActive() throws Exception { 1165 final boolean isTetheringActive = false; 1166 final boolean currDisallow = false; 1167 final boolean nextDisallow = true; 1168 final int expectedInteractionsWithShowNotification = 0; 1169 1170 runUserRestrictionsChange(currDisallow, nextDisallow, isTetheringActive, 1171 expectedInteractionsWithShowNotification); 1172 } 1173 1174 @Test testDisallowTetheringWhenTetheringIsActive()1175 public void testDisallowTetheringWhenTetheringIsActive() throws Exception { 1176 final boolean isTetheringActive = true; 1177 final boolean currDisallow = false; 1178 final boolean nextDisallow = true; 1179 final int expectedInteractionsWithShowNotification = 1; 1180 1181 runUserRestrictionsChange(currDisallow, nextDisallow, isTetheringActive, 1182 expectedInteractionsWithShowNotification); 1183 } 1184 1185 @Test testAllowTetheringWhenTetheringIsNotActive()1186 public void testAllowTetheringWhenTetheringIsNotActive() throws Exception { 1187 final boolean isTetheringActive = false; 1188 final boolean currDisallow = true; 1189 final boolean nextDisallow = false; 1190 final int expectedInteractionsWithShowNotification = 0; 1191 1192 runUserRestrictionsChange(currDisallow, nextDisallow, isTetheringActive, 1193 expectedInteractionsWithShowNotification); 1194 } 1195 1196 @Test testAllowTetheringWhenTetheringIsActive()1197 public void testAllowTetheringWhenTetheringIsActive() throws Exception { 1198 final boolean isTetheringActive = true; 1199 final boolean currDisallow = true; 1200 final boolean nextDisallow = false; 1201 final int expectedInteractionsWithShowNotification = 0; 1202 1203 runUserRestrictionsChange(currDisallow, nextDisallow, isTetheringActive, 1204 expectedInteractionsWithShowNotification); 1205 } 1206 1207 @Test testDisallowTetheringUnchanged()1208 public void testDisallowTetheringUnchanged() throws Exception { 1209 final boolean isTetheringActive = true; 1210 final int expectedInteractionsWithShowNotification = 0; 1211 boolean currDisallow = true; 1212 boolean nextDisallow = true; 1213 1214 runUserRestrictionsChange(currDisallow, nextDisallow, isTetheringActive, 1215 expectedInteractionsWithShowNotification); 1216 1217 currDisallow = false; 1218 nextDisallow = false; 1219 1220 runUserRestrictionsChange(currDisallow, nextDisallow, isTetheringActive, 1221 expectedInteractionsWithShowNotification); 1222 } 1223 1224 private class TestTetheringEventCallback extends ITetheringEventCallback.Stub { 1225 private final ArrayList<Network> mActualUpstreams = new ArrayList<>(); 1226 private final ArrayList<TetheringConfigurationParcel> mTetheringConfigs = 1227 new ArrayList<>(); 1228 private final ArrayList<TetherStatesParcel> mTetherStates = new ArrayList<>(); 1229 private final ArrayList<Integer> mOffloadStatus = new ArrayList<>(); 1230 1231 // This function will remove the recorded callbacks, so it must be called once for 1232 // each callback. If this is called after multiple callback, the order matters. 1233 // onCallbackCreated counts as the first call to expectUpstreamChanged with 1234 // @see onCallbackCreated. expectUpstreamChanged(Network... networks)1235 public void expectUpstreamChanged(Network... networks) { 1236 if (networks == null) { 1237 assertNoUpstreamChangeCallback(); 1238 return; 1239 } 1240 1241 final ArrayList<Network> expectedUpstreams = 1242 new ArrayList<Network>(Arrays.asList(networks)); 1243 for (Network upstream : expectedUpstreams) { 1244 // throws OOB if no expectations 1245 assertEquals(mActualUpstreams.remove(0), upstream); 1246 } 1247 assertNoUpstreamChangeCallback(); 1248 } 1249 1250 // This function will remove the recorded callbacks, so it must be called once 1251 // for each callback. If this is called after multiple callback, the order matters. 1252 // onCallbackCreated counts as the first call to onConfigurationChanged with 1253 // @see onCallbackCreated. expectConfigurationChanged(TetheringConfigurationParcel... tetherConfigs)1254 public void expectConfigurationChanged(TetheringConfigurationParcel... tetherConfigs) { 1255 final ArrayList<TetheringConfigurationParcel> expectedTetherConfig = 1256 new ArrayList<TetheringConfigurationParcel>(Arrays.asList(tetherConfigs)); 1257 for (TetheringConfigurationParcel config : expectedTetherConfig) { 1258 // throws OOB if no expectations 1259 final TetheringConfigurationParcel actualConfig = mTetheringConfigs.remove(0); 1260 assertTetherConfigParcelEqual(actualConfig, config); 1261 } 1262 assertNoConfigChangeCallback(); 1263 } 1264 expectOffloadStatusChanged(final int expectedStatus)1265 public void expectOffloadStatusChanged(final int expectedStatus) { 1266 assertOffloadStatusChangedCallback(); 1267 assertEquals(mOffloadStatus.remove(0), new Integer(expectedStatus)); 1268 } 1269 pollTetherStatesChanged()1270 public TetherStatesParcel pollTetherStatesChanged() { 1271 assertStateChangeCallback(); 1272 return mTetherStates.remove(0); 1273 } 1274 1275 @Override onUpstreamChanged(Network network)1276 public void onUpstreamChanged(Network network) { 1277 mActualUpstreams.add(network); 1278 } 1279 1280 @Override onConfigurationChanged(TetheringConfigurationParcel config)1281 public void onConfigurationChanged(TetheringConfigurationParcel config) { 1282 mTetheringConfigs.add(config); 1283 } 1284 1285 @Override onTetherStatesChanged(TetherStatesParcel states)1286 public void onTetherStatesChanged(TetherStatesParcel states) { 1287 mTetherStates.add(states); 1288 } 1289 1290 @Override onTetherClientsChanged(List<TetheredClient> clients)1291 public void onTetherClientsChanged(List<TetheredClient> clients) { 1292 // TODO: check this 1293 } 1294 1295 @Override onOffloadStatusChanged(final int status)1296 public void onOffloadStatusChanged(final int status) { 1297 mOffloadStatus.add(status); 1298 } 1299 1300 @Override onCallbackStarted(TetheringCallbackStartedParcel parcel)1301 public void onCallbackStarted(TetheringCallbackStartedParcel parcel) { 1302 mActualUpstreams.add(parcel.upstreamNetwork); 1303 mTetheringConfigs.add(parcel.config); 1304 mTetherStates.add(parcel.states); 1305 mOffloadStatus.add(parcel.offloadStatus); 1306 } 1307 1308 @Override onCallbackStopped(int errorCode)1309 public void onCallbackStopped(int errorCode) { } 1310 assertNoUpstreamChangeCallback()1311 public void assertNoUpstreamChangeCallback() { 1312 assertTrue(mActualUpstreams.isEmpty()); 1313 } 1314 assertNoConfigChangeCallback()1315 public void assertNoConfigChangeCallback() { 1316 assertTrue(mTetheringConfigs.isEmpty()); 1317 } 1318 assertNoStateChangeCallback()1319 public void assertNoStateChangeCallback() { 1320 assertTrue(mTetherStates.isEmpty()); 1321 } 1322 assertStateChangeCallback()1323 public void assertStateChangeCallback() { 1324 assertFalse(mTetherStates.isEmpty()); 1325 } 1326 assertOffloadStatusChangedCallback()1327 public void assertOffloadStatusChangedCallback() { 1328 assertFalse(mOffloadStatus.isEmpty()); 1329 } 1330 assertNoCallback()1331 public void assertNoCallback() { 1332 assertNoUpstreamChangeCallback(); 1333 assertNoConfigChangeCallback(); 1334 assertNoStateChangeCallback(); 1335 } 1336 assertTetherConfigParcelEqual(@onNull TetheringConfigurationParcel actual, @NonNull TetheringConfigurationParcel expect)1337 private void assertTetherConfigParcelEqual(@NonNull TetheringConfigurationParcel actual, 1338 @NonNull TetheringConfigurationParcel expect) { 1339 assertEquals(actual.subId, expect.subId); 1340 assertArrayEquals(actual.tetherableUsbRegexs, expect.tetherableUsbRegexs); 1341 assertArrayEquals(actual.tetherableWifiRegexs, expect.tetherableWifiRegexs); 1342 assertArrayEquals(actual.tetherableBluetoothRegexs, expect.tetherableBluetoothRegexs); 1343 assertEquals(actual.isDunRequired, expect.isDunRequired); 1344 assertEquals(actual.chooseUpstreamAutomatically, expect.chooseUpstreamAutomatically); 1345 assertArrayEquals(actual.preferredUpstreamIfaceTypes, 1346 expect.preferredUpstreamIfaceTypes); 1347 assertArrayEquals(actual.legacyDhcpRanges, expect.legacyDhcpRanges); 1348 assertArrayEquals(actual.defaultIPv4DNS, expect.defaultIPv4DNS); 1349 assertEquals(actual.enableLegacyDhcpServer, expect.enableLegacyDhcpServer); 1350 assertArrayEquals(actual.provisioningApp, expect.provisioningApp); 1351 assertEquals(actual.provisioningAppNoUi, expect.provisioningAppNoUi); 1352 assertEquals(actual.provisioningCheckPeriod, expect.provisioningCheckPeriod); 1353 } 1354 } 1355 assertTetherStatesNotNullButEmpty(final TetherStatesParcel parcel)1356 private void assertTetherStatesNotNullButEmpty(final TetherStatesParcel parcel) { 1357 assertFalse(parcel == null); 1358 assertEquals(0, parcel.availableList.length); 1359 assertEquals(0, parcel.tetheredList.length); 1360 assertEquals(0, parcel.localOnlyList.length); 1361 assertEquals(0, parcel.erroredIfaceList.length); 1362 assertEquals(0, parcel.lastErrorList.length); 1363 MiscAssertsKt.assertFieldCountEquals(5, TetherStatesParcel.class); 1364 } 1365 1366 @Test testRegisterTetheringEventCallback()1367 public void testRegisterTetheringEventCallback() throws Exception { 1368 TestTetheringEventCallback callback = new TestTetheringEventCallback(); 1369 TestTetheringEventCallback callback2 = new TestTetheringEventCallback(); 1370 1371 // 1. Register one callback before running any tethering. 1372 mTethering.registerTetheringEventCallback(callback); 1373 mLooper.dispatchAll(); 1374 callback.expectUpstreamChanged(new Network[] {null}); 1375 callback.expectConfigurationChanged( 1376 mTethering.getTetheringConfiguration().toStableParcelable()); 1377 TetherStatesParcel tetherState = callback.pollTetherStatesChanged(); 1378 assertTetherStatesNotNullButEmpty(tetherState); 1379 callback.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_STOPPED); 1380 // 2. Enable wifi tethering. 1381 UpstreamNetworkState upstreamState = buildMobileDualStackUpstreamState(); 1382 initTetheringUpstream(upstreamState); 1383 when(mWifiManager.startSoftAp(any(WifiConfiguration.class))).thenReturn(true); 1384 mTethering.interfaceStatusChanged(TEST_WLAN_IFNAME, true); 1385 mLooper.dispatchAll(); 1386 tetherState = callback.pollTetherStatesChanged(); 1387 assertArrayEquals(tetherState.availableList, new String[] {TEST_WLAN_IFNAME}); 1388 1389 mTethering.startTethering(createTetheringRequestParcel(TETHERING_WIFI), null); 1390 sendWifiApStateChanged(WIFI_AP_STATE_ENABLED, TEST_WLAN_IFNAME, IFACE_IP_MODE_TETHERED); 1391 mLooper.dispatchAll(); 1392 tetherState = callback.pollTetherStatesChanged(); 1393 assertArrayEquals(tetherState.tetheredList, new String[] {TEST_WLAN_IFNAME}); 1394 callback.expectUpstreamChanged(upstreamState.network); 1395 callback.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_STARTED); 1396 1397 // 3. Register second callback. 1398 mTethering.registerTetheringEventCallback(callback2); 1399 mLooper.dispatchAll(); 1400 callback2.expectUpstreamChanged(upstreamState.network); 1401 callback2.expectConfigurationChanged( 1402 mTethering.getTetheringConfiguration().toStableParcelable()); 1403 tetherState = callback2.pollTetherStatesChanged(); 1404 assertEquals(tetherState.tetheredList, new String[] {TEST_WLAN_IFNAME}); 1405 callback2.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_STARTED); 1406 1407 // 4. Unregister first callback and disable wifi tethering 1408 mTethering.unregisterTetheringEventCallback(callback); 1409 mLooper.dispatchAll(); 1410 mTethering.stopTethering(TETHERING_WIFI); 1411 sendWifiApStateChanged(WifiManager.WIFI_AP_STATE_DISABLED); 1412 mLooper.dispatchAll(); 1413 tetherState = callback2.pollTetherStatesChanged(); 1414 assertArrayEquals(tetherState.availableList, new String[] {TEST_WLAN_IFNAME}); 1415 mLooper.dispatchAll(); 1416 callback2.expectUpstreamChanged(new Network[] {null}); 1417 callback2.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_STOPPED); 1418 callback.assertNoCallback(); 1419 } 1420 1421 @Test testReportFailCallbackIfOffloadNotSupported()1422 public void testReportFailCallbackIfOffloadNotSupported() throws Exception { 1423 final UpstreamNetworkState upstreamState = buildMobileDualStackUpstreamState(); 1424 TestTetheringEventCallback callback = new TestTetheringEventCallback(); 1425 mTethering.registerTetheringEventCallback(callback); 1426 mLooper.dispatchAll(); 1427 callback.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_STOPPED); 1428 1429 // 1. Offload fail if no OffloadConfig. 1430 initOffloadConfiguration(false /* offloadConfig */, true /* offloadControl */, 1431 0 /* defaultDisabled */); 1432 runUsbTethering(upstreamState); 1433 callback.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_FAILED); 1434 runStopUSBTethering(); 1435 callback.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_STOPPED); 1436 reset(mUsbManager); 1437 // 2. Offload fail if no OffloadControl. 1438 initOffloadConfiguration(true /* offloadConfig */, false /* offloadControl */, 1439 0 /* defaultDisabled */); 1440 runUsbTethering(upstreamState); 1441 callback.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_FAILED); 1442 runStopUSBTethering(); 1443 callback.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_STOPPED); 1444 reset(mUsbManager); 1445 // 3. Offload fail if disabled by settings. 1446 initOffloadConfiguration(true /* offloadConfig */, true /* offloadControl */, 1447 1 /* defaultDisabled */); 1448 runUsbTethering(upstreamState); 1449 callback.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_FAILED); 1450 runStopUSBTethering(); 1451 callback.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_STOPPED); 1452 } 1453 runStopUSBTethering()1454 private void runStopUSBTethering() { 1455 mTethering.stopTethering(TETHERING_USB); 1456 mLooper.dispatchAll(); 1457 mTethering.interfaceRemoved(TEST_USB_IFNAME); 1458 mLooper.dispatchAll(); 1459 } 1460 initOffloadConfiguration(final boolean offloadConfig, final boolean offloadControl, final int defaultDisabled)1461 private void initOffloadConfiguration(final boolean offloadConfig, 1462 final boolean offloadControl, final int defaultDisabled) { 1463 when(mOffloadHardwareInterface.initOffloadConfig()).thenReturn(offloadConfig); 1464 when(mOffloadHardwareInterface.initOffloadControl(any())).thenReturn(offloadControl); 1465 when(mOffloadHardwareInterface.getDefaultTetherOffloadDisabled()).thenReturn( 1466 defaultDisabled); 1467 } 1468 1469 @Test testMultiSimAware()1470 public void testMultiSimAware() throws Exception { 1471 final TetheringConfiguration initailConfig = mTethering.getTetheringConfiguration(); 1472 assertEquals(INVALID_SUBSCRIPTION_ID, initailConfig.activeDataSubId); 1473 1474 final int fakeSubId = 1234; 1475 mPhoneStateListener.onActiveDataSubscriptionIdChanged(fakeSubId); 1476 final TetheringConfiguration newConfig = mTethering.getTetheringConfiguration(); 1477 assertEquals(fakeSubId, newConfig.activeDataSubId); 1478 verify(mNotificationUpdater, times(1)).onActiveDataSubscriptionIdChanged(eq(fakeSubId)); 1479 } 1480 1481 @Test testNoDuplicatedEthernetRequest()1482 public void testNoDuplicatedEthernetRequest() throws Exception { 1483 final TetheredInterfaceRequest mockRequest = mock(TetheredInterfaceRequest.class); 1484 when(mEm.requestTetheredInterface(any(), any())).thenReturn(mockRequest); 1485 mTethering.startTethering(createTetheringRequestParcel(TETHERING_ETHERNET), null); 1486 mLooper.dispatchAll(); 1487 verify(mEm, times(1)).requestTetheredInterface(any(), any()); 1488 mTethering.startTethering(createTetheringRequestParcel(TETHERING_ETHERNET), null); 1489 mLooper.dispatchAll(); 1490 verifyNoMoreInteractions(mEm); 1491 mTethering.stopTethering(TETHERING_ETHERNET); 1492 mLooper.dispatchAll(); 1493 verify(mockRequest, times(1)).release(); 1494 mTethering.stopTethering(TETHERING_ETHERNET); 1495 mLooper.dispatchAll(); 1496 verifyNoMoreInteractions(mEm); 1497 } 1498 workingWifiP2pGroupOwner( boolean emulateInterfaceStatusChanged)1499 private void workingWifiP2pGroupOwner( 1500 boolean emulateInterfaceStatusChanged) throws Exception { 1501 if (emulateInterfaceStatusChanged) { 1502 mTethering.interfaceStatusChanged(TEST_P2P_IFNAME, true); 1503 } 1504 sendWifiP2pConnectionChanged(true, true, TEST_P2P_IFNAME); 1505 mLooper.dispatchAll(); 1506 1507 verifyInterfaceServingModeStarted(TEST_P2P_IFNAME); 1508 verifyTetheringBroadcast(TEST_P2P_IFNAME, EXTRA_AVAILABLE_TETHER); 1509 verify(mNetd, times(1)).ipfwdEnableForwarding(TETHERING_NAME); 1510 verify(mNetd, times(1)).tetherStartWithConfiguration(any()); 1511 verifyNoMoreInteractions(mNetd); 1512 verifyTetheringBroadcast(TEST_P2P_IFNAME, EXTRA_ACTIVE_LOCAL_ONLY); 1513 verify(mUpstreamNetworkMonitor, times(1)).startObserveAllNetworks(); 1514 // There are 2 IpServer state change events: STATE_AVAILABLE -> STATE_LOCAL_ONLY 1515 verify(mNotificationUpdater, times(2)).onDownstreamChanged(DOWNSTREAM_NONE); 1516 1517 assertEquals(TETHER_ERROR_NO_ERROR, mTethering.getLastTetherError(TEST_P2P_IFNAME)); 1518 1519 // Emulate externally-visible WifiP2pManager effects, when wifi p2p group 1520 // is being removed. 1521 sendWifiP2pConnectionChanged(false, true, TEST_P2P_IFNAME); 1522 mTethering.interfaceRemoved(TEST_P2P_IFNAME); 1523 mLooper.dispatchAll(); 1524 1525 verify(mNetd, times(1)).tetherApplyDnsInterfaces(); 1526 verify(mNetd, times(1)).tetherInterfaceRemove(TEST_P2P_IFNAME); 1527 verify(mNetd, times(1)).networkRemoveInterface(INetd.LOCAL_NET_ID, TEST_P2P_IFNAME); 1528 // interfaceSetCfg() called once for enabling and twice for disabling IPv4. 1529 verify(mNetd, times(3)).interfaceSetCfg(any(InterfaceConfigurationParcel.class)); 1530 verify(mNetd, times(1)).tetherStop(); 1531 verify(mNetd, times(1)).ipfwdDisableForwarding(TETHERING_NAME); 1532 verify(mUpstreamNetworkMonitor, never()).getCurrentPreferredUpstream(); 1533 verify(mUpstreamNetworkMonitor, never()).selectPreferredUpstreamType(any()); 1534 verifyNoMoreInteractions(mNetd); 1535 // Asking for the last error after the per-interface state machine 1536 // has been reaped yields an unknown interface error. 1537 assertEquals(TETHER_ERROR_UNKNOWN_IFACE, mTethering.getLastTetherError(TEST_P2P_IFNAME)); 1538 } 1539 workingWifiP2pGroupClient( boolean emulateInterfaceStatusChanged)1540 private void workingWifiP2pGroupClient( 1541 boolean emulateInterfaceStatusChanged) throws Exception { 1542 if (emulateInterfaceStatusChanged) { 1543 mTethering.interfaceStatusChanged(TEST_P2P_IFNAME, true); 1544 } 1545 sendWifiP2pConnectionChanged(true, false, TEST_P2P_IFNAME); 1546 mLooper.dispatchAll(); 1547 1548 verify(mNetd, never()).interfaceSetCfg(any(InterfaceConfigurationParcel.class)); 1549 verify(mNetd, never()).tetherInterfaceAdd(TEST_P2P_IFNAME); 1550 verify(mNetd, never()).networkAddInterface(INetd.LOCAL_NET_ID, TEST_P2P_IFNAME); 1551 verify(mNetd, never()).ipfwdEnableForwarding(TETHERING_NAME); 1552 verify(mNetd, never()).tetherStartWithConfiguration(any()); 1553 1554 // Emulate externally-visible WifiP2pManager effects, when wifi p2p group 1555 // is being removed. 1556 sendWifiP2pConnectionChanged(false, false, TEST_P2P_IFNAME); 1557 mTethering.interfaceRemoved(TEST_P2P_IFNAME); 1558 mLooper.dispatchAll(); 1559 1560 verify(mNetd, never()).tetherApplyDnsInterfaces(); 1561 verify(mNetd, never()).tetherInterfaceRemove(TEST_P2P_IFNAME); 1562 verify(mNetd, never()).networkRemoveInterface(INetd.LOCAL_NET_ID, TEST_P2P_IFNAME); 1563 verify(mNetd, never()).interfaceSetCfg(any(InterfaceConfigurationParcel.class)); 1564 verify(mNetd, never()).tetherStop(); 1565 verify(mNetd, never()).ipfwdDisableForwarding(TETHERING_NAME); 1566 verifyNoMoreInteractions(mNetd); 1567 // Asking for the last error after the per-interface state machine 1568 // has been reaped yields an unknown interface error. 1569 assertEquals(TETHER_ERROR_UNKNOWN_IFACE, mTethering.getLastTetherError(TEST_P2P_IFNAME)); 1570 } 1571 1572 @Test workingWifiP2pGroupOwnerWithIfaceChanged()1573 public void workingWifiP2pGroupOwnerWithIfaceChanged() throws Exception { 1574 workingWifiP2pGroupOwner(true); 1575 } 1576 1577 @Test workingWifiP2pGroupOwnerSansIfaceChanged()1578 public void workingWifiP2pGroupOwnerSansIfaceChanged() throws Exception { 1579 workingWifiP2pGroupOwner(false); 1580 } 1581 workingWifiP2pGroupOwnerLegacyMode( boolean emulateInterfaceStatusChanged)1582 private void workingWifiP2pGroupOwnerLegacyMode( 1583 boolean emulateInterfaceStatusChanged) throws Exception { 1584 // change to legacy mode and update tethering information by chaning SIM 1585 when(mResources.getStringArray(R.array.config_tether_wifi_p2p_regexs)) 1586 .thenReturn(new String[]{}); 1587 final int fakeSubId = 1234; 1588 mPhoneStateListener.onActiveDataSubscriptionIdChanged(fakeSubId); 1589 1590 if (emulateInterfaceStatusChanged) { 1591 mTethering.interfaceStatusChanged(TEST_P2P_IFNAME, true); 1592 } 1593 sendWifiP2pConnectionChanged(true, true, TEST_P2P_IFNAME); 1594 mLooper.dispatchAll(); 1595 1596 verify(mNetd, never()).interfaceSetCfg(any(InterfaceConfigurationParcel.class)); 1597 verify(mNetd, never()).tetherInterfaceAdd(TEST_P2P_IFNAME); 1598 verify(mNetd, never()).networkAddInterface(INetd.LOCAL_NET_ID, TEST_P2P_IFNAME); 1599 verify(mNetd, never()).ipfwdEnableForwarding(TETHERING_NAME); 1600 verify(mNetd, never()).tetherStartWithConfiguration(any()); 1601 assertEquals(TETHER_ERROR_UNKNOWN_IFACE, mTethering.getLastTetherError(TEST_P2P_IFNAME)); 1602 } 1603 @Test workingWifiP2pGroupOwnerLegacyModeWithIfaceChanged()1604 public void workingWifiP2pGroupOwnerLegacyModeWithIfaceChanged() throws Exception { 1605 workingWifiP2pGroupOwnerLegacyMode(true); 1606 } 1607 1608 @Test workingWifiP2pGroupOwnerLegacyModeSansIfaceChanged()1609 public void workingWifiP2pGroupOwnerLegacyModeSansIfaceChanged() throws Exception { 1610 workingWifiP2pGroupOwnerLegacyMode(false); 1611 } 1612 1613 @Test workingWifiP2pGroupClientWithIfaceChanged()1614 public void workingWifiP2pGroupClientWithIfaceChanged() throws Exception { 1615 workingWifiP2pGroupClient(true); 1616 } 1617 1618 @Test workingWifiP2pGroupClientSansIfaceChanged()1619 public void workingWifiP2pGroupClientSansIfaceChanged() throws Exception { 1620 workingWifiP2pGroupClient(false); 1621 } 1622 setDataSaverEnabled(boolean enabled)1623 private void setDataSaverEnabled(boolean enabled) { 1624 final Intent intent = new Intent(ACTION_RESTRICT_BACKGROUND_CHANGED); 1625 mServiceContext.sendBroadcastAsUser(intent, UserHandle.ALL); 1626 1627 final int status = enabled ? RESTRICT_BACKGROUND_STATUS_ENABLED 1628 : RESTRICT_BACKGROUND_STATUS_DISABLED; 1629 when(mCm.getRestrictBackgroundStatus()).thenReturn(status); 1630 mLooper.dispatchAll(); 1631 } 1632 1633 @Test testDataSaverChanged()1634 public void testDataSaverChanged() { 1635 // Start Tethering. 1636 final UpstreamNetworkState upstreamState = buildMobileIPv4UpstreamState(); 1637 runUsbTethering(upstreamState); 1638 assertContains(Arrays.asList(mTethering.getTetheredIfaces()), TEST_USB_IFNAME); 1639 // Data saver is ON. 1640 setDataSaverEnabled(true); 1641 // Verify that tethering should be disabled. 1642 verify(mUsbManager, times(1)).setCurrentFunctions(UsbManager.FUNCTION_NONE); 1643 mTethering.interfaceRemoved(TEST_USB_IFNAME); 1644 mLooper.dispatchAll(); 1645 assertEquals(mTethering.getTetheredIfaces(), new String[0]); 1646 reset(mUsbManager); 1647 1648 runUsbTethering(upstreamState); 1649 // Verify that user can start tethering again without turning OFF data saver. 1650 assertContains(Arrays.asList(mTethering.getTetheredIfaces()), TEST_USB_IFNAME); 1651 1652 // If data saver is keep ON with change event, tethering should not be OFF this time. 1653 setDataSaverEnabled(true); 1654 verify(mUsbManager, times(0)).setCurrentFunctions(UsbManager.FUNCTION_NONE); 1655 assertContains(Arrays.asList(mTethering.getTetheredIfaces()), TEST_USB_IFNAME); 1656 1657 // If data saver is turned OFF, it should not change tethering. 1658 setDataSaverEnabled(false); 1659 verify(mUsbManager, times(0)).setCurrentFunctions(UsbManager.FUNCTION_NONE); 1660 assertContains(Arrays.asList(mTethering.getTetheredIfaces()), TEST_USB_IFNAME); 1661 } 1662 assertContains(Collection<T> collection, T element)1663 private static <T> void assertContains(Collection<T> collection, T element) { 1664 assertTrue(element + " not found in " + collection, collection.contains(element)); 1665 } 1666 1667 private class ResultListener extends IIntResultListener.Stub { 1668 private final int mExpectedResult; 1669 private boolean mHasResult = false; ResultListener(final int expectedResult)1670 ResultListener(final int expectedResult) { 1671 mExpectedResult = expectedResult; 1672 } 1673 1674 @Override onResult(final int resultCode)1675 public void onResult(final int resultCode) { 1676 mHasResult = true; 1677 if (resultCode != mExpectedResult) { 1678 fail("expected result: " + mExpectedResult + " but actual result: " + resultCode); 1679 } 1680 } 1681 assertHasResult()1682 public void assertHasResult() { 1683 if (!mHasResult) fail("No callback result"); 1684 } 1685 } 1686 1687 @Test testMultipleStartTethering()1688 public void testMultipleStartTethering() throws Exception { 1689 final LinkAddress serverLinkAddr = new LinkAddress("192.168.20.1/24"); 1690 final LinkAddress clientLinkAddr = new LinkAddress("192.168.20.42/24"); 1691 final String serverAddr = "192.168.20.1"; 1692 final ResultListener firstResult = new ResultListener(TETHER_ERROR_NO_ERROR); 1693 final ResultListener secondResult = new ResultListener(TETHER_ERROR_NO_ERROR); 1694 final ResultListener thirdResult = new ResultListener(TETHER_ERROR_NO_ERROR); 1695 1696 // Enable USB tethering and check that Tethering starts USB. 1697 mTethering.startTethering(createTetheringRequestParcel(TETHERING_USB, 1698 null, null, false), firstResult); 1699 mLooper.dispatchAll(); 1700 firstResult.assertHasResult(); 1701 verify(mUsbManager, times(1)).setCurrentFunctions(UsbManager.FUNCTION_RNDIS); 1702 verifyNoMoreInteractions(mUsbManager); 1703 1704 // Enable USB tethering again with the same request and expect no change to USB. 1705 mTethering.startTethering(createTetheringRequestParcel(TETHERING_USB, 1706 null, null, false), secondResult); 1707 mLooper.dispatchAll(); 1708 secondResult.assertHasResult(); 1709 verify(mUsbManager, never()).setCurrentFunctions(UsbManager.FUNCTION_NONE); 1710 reset(mUsbManager); 1711 1712 // Enable USB tethering with a different request and expect that USB is stopped and 1713 // started. 1714 mTethering.startTethering(createTetheringRequestParcel(TETHERING_USB, 1715 serverLinkAddr, clientLinkAddr, false), thirdResult); 1716 mLooper.dispatchAll(); 1717 thirdResult.assertHasResult(); 1718 verify(mUsbManager, times(1)).setCurrentFunctions(UsbManager.FUNCTION_NONE); 1719 verify(mUsbManager, times(1)).setCurrentFunctions(UsbManager.FUNCTION_RNDIS); 1720 1721 // Expect that when USB comes up, the DHCP server is configured with the requested address. 1722 mTethering.interfaceStatusChanged(TEST_USB_IFNAME, true); 1723 sendUsbBroadcast(true, true, true, TETHERING_USB); 1724 mLooper.dispatchAll(); 1725 verify(mDhcpServer, timeout(DHCPSERVER_START_TIMEOUT_MS).times(1)).startWithCallbacks( 1726 any(), any()); 1727 verify(mNetd).interfaceSetCfg(argThat(cfg -> serverAddr.equals(cfg.ipv4Addr))); 1728 } 1729 1730 @Test testRequestStaticIp()1731 public void testRequestStaticIp() throws Exception { 1732 final LinkAddress serverLinkAddr = new LinkAddress("192.168.0.123/24"); 1733 final LinkAddress clientLinkAddr = new LinkAddress("192.168.0.42/24"); 1734 final String serverAddr = "192.168.0.123"; 1735 final int clientAddrParceled = 0xc0a8002a; 1736 final ArgumentCaptor<DhcpServingParamsParcel> dhcpParamsCaptor = 1737 ArgumentCaptor.forClass(DhcpServingParamsParcel.class); 1738 mTethering.startTethering(createTetheringRequestParcel(TETHERING_USB, 1739 serverLinkAddr, clientLinkAddr, false), null); 1740 mLooper.dispatchAll(); 1741 verify(mUsbManager, times(1)).setCurrentFunctions(UsbManager.FUNCTION_RNDIS); 1742 mTethering.interfaceStatusChanged(TEST_USB_IFNAME, true); 1743 sendUsbBroadcast(true, true, true, TETHERING_USB); 1744 mLooper.dispatchAll(); 1745 verify(mNetd).interfaceSetCfg(argThat(cfg -> serverAddr.equals(cfg.ipv4Addr))); 1746 verify(mIpServerDependencies, times(1)).makeDhcpServer(any(), dhcpParamsCaptor.capture(), 1747 any()); 1748 final DhcpServingParamsParcel params = dhcpParamsCaptor.getValue(); 1749 assertEquals(serverAddr, intToInet4AddressHTH(params.serverAddr).getHostAddress()); 1750 assertEquals(24, params.serverAddrPrefixLength); 1751 assertEquals(clientAddrParceled, params.singleClientAddr); 1752 } 1753 1754 @Test testUpstreamNetworkChanged()1755 public void testUpstreamNetworkChanged() { 1756 final Tethering.TetherMainSM stateMachine = (Tethering.TetherMainSM) 1757 mTetheringDependencies.mUpstreamNetworkMonitorSM; 1758 final UpstreamNetworkState upstreamState = buildMobileIPv4UpstreamState(); 1759 initTetheringUpstream(upstreamState); 1760 stateMachine.chooseUpstreamType(true); 1761 1762 verify(mUpstreamNetworkMonitor, times(1)).setCurrentUpstream(eq(upstreamState.network)); 1763 verify(mNotificationUpdater, times(1)).onUpstreamCapabilitiesChanged(any()); 1764 } 1765 1766 @Test testUpstreamCapabilitiesChanged()1767 public void testUpstreamCapabilitiesChanged() { 1768 final Tethering.TetherMainSM stateMachine = (Tethering.TetherMainSM) 1769 mTetheringDependencies.mUpstreamNetworkMonitorSM; 1770 final UpstreamNetworkState upstreamState = buildMobileIPv4UpstreamState(); 1771 initTetheringUpstream(upstreamState); 1772 stateMachine.chooseUpstreamType(true); 1773 1774 stateMachine.handleUpstreamNetworkMonitorCallback(EVENT_ON_CAPABILITIES, upstreamState); 1775 // Should have two onUpstreamCapabilitiesChanged(). 1776 // One is called by reportUpstreamChanged(). One is called by EVENT_ON_CAPABILITIES. 1777 verify(mNotificationUpdater, times(2)).onUpstreamCapabilitiesChanged(any()); 1778 reset(mNotificationUpdater); 1779 1780 // Verify that onUpstreamCapabilitiesChanged won't be called if not current upstream network 1781 // capabilities changed. 1782 final UpstreamNetworkState upstreamState2 = new UpstreamNetworkState( 1783 upstreamState.linkProperties, upstreamState.networkCapabilities, new Network(101)); 1784 stateMachine.handleUpstreamNetworkMonitorCallback(EVENT_ON_CAPABILITIES, upstreamState2); 1785 verify(mNotificationUpdater, never()).onUpstreamCapabilitiesChanged(any()); 1786 } 1787 1788 @Test testDumpTetheringLog()1789 public void testDumpTetheringLog() throws Exception { 1790 final FileDescriptor mockFd = mock(FileDescriptor.class); 1791 final PrintWriter mockPw = mock(PrintWriter.class); 1792 runUsbTethering(null); 1793 mLooper.startAutoDispatch(); 1794 mTethering.dump(mockFd, mockPw, new String[0]); 1795 verify(mConfig).dump(any()); 1796 verify(mEntitleMgr).dump(any()); 1797 verify(mOffloadCtrl).dump(any()); 1798 mLooper.stopAutoDispatch(); 1799 } 1800 1801 @Test testExemptFromEntitlementCheck()1802 public void testExemptFromEntitlementCheck() throws Exception { 1803 setupForRequiredProvisioning(); 1804 final TetheringRequestParcel wifiNotExemptRequest = 1805 createTetheringRequestParcel(TETHERING_WIFI, null, null, false); 1806 mTethering.startTethering(wifiNotExemptRequest, null); 1807 mLooper.dispatchAll(); 1808 verify(mEntitleMgr).startProvisioningIfNeeded(TETHERING_WIFI, false); 1809 verify(mEntitleMgr, never()).setExemptedDownstreamType(TETHERING_WIFI); 1810 assertFalse(mEntitleMgr.isCellularUpstreamPermitted()); 1811 mTethering.stopTethering(TETHERING_WIFI); 1812 mLooper.dispatchAll(); 1813 verify(mEntitleMgr).stopProvisioningIfNeeded(TETHERING_WIFI); 1814 reset(mEntitleMgr); 1815 1816 setupForRequiredProvisioning(); 1817 final TetheringRequestParcel wifiExemptRequest = 1818 createTetheringRequestParcel(TETHERING_WIFI, null, null, true); 1819 mTethering.startTethering(wifiExemptRequest, null); 1820 mLooper.dispatchAll(); 1821 verify(mEntitleMgr, never()).startProvisioningIfNeeded(TETHERING_WIFI, false); 1822 verify(mEntitleMgr).setExemptedDownstreamType(TETHERING_WIFI); 1823 assertTrue(mEntitleMgr.isCellularUpstreamPermitted()); 1824 mTethering.stopTethering(TETHERING_WIFI); 1825 mLooper.dispatchAll(); 1826 verify(mEntitleMgr).stopProvisioningIfNeeded(TETHERING_WIFI); 1827 reset(mEntitleMgr); 1828 1829 // If one app enables tethering without provisioning check first, then another app enables 1830 // tethering of the same type but does not disable the provisioning check. 1831 setupForRequiredProvisioning(); 1832 mTethering.startTethering(wifiExemptRequest, null); 1833 mLooper.dispatchAll(); 1834 verify(mEntitleMgr, never()).startProvisioningIfNeeded(TETHERING_WIFI, false); 1835 verify(mEntitleMgr).setExemptedDownstreamType(TETHERING_WIFI); 1836 assertTrue(mEntitleMgr.isCellularUpstreamPermitted()); 1837 reset(mEntitleMgr); 1838 setupForRequiredProvisioning(); 1839 mTethering.startTethering(wifiNotExemptRequest, null); 1840 mLooper.dispatchAll(); 1841 verify(mEntitleMgr).startProvisioningIfNeeded(TETHERING_WIFI, false); 1842 verify(mEntitleMgr, never()).setExemptedDownstreamType(TETHERING_WIFI); 1843 assertFalse(mEntitleMgr.isCellularUpstreamPermitted()); 1844 mTethering.stopTethering(TETHERING_WIFI); 1845 mLooper.dispatchAll(); 1846 verify(mEntitleMgr).stopProvisioningIfNeeded(TETHERING_WIFI); 1847 reset(mEntitleMgr); 1848 } 1849 setupForRequiredProvisioning()1850 private void setupForRequiredProvisioning() { 1851 // Produce some acceptable looking provision app setting if requested. 1852 when(mResources.getStringArray(R.array.config_mobile_hotspot_provision_app)) 1853 .thenReturn(PROVISIONING_APP_NAME); 1854 when(mResources.getString(R.string.config_mobile_hotspot_provision_app_no_ui)) 1855 .thenReturn(PROVISIONING_NO_UI_APP_NAME); 1856 // Act like the CarrierConfigManager is present and ready unless told otherwise. 1857 when(mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE)) 1858 .thenReturn(mCarrierConfigManager); 1859 when(mCarrierConfigManager.getConfigForSubId(anyInt())).thenReturn(mCarrierConfig); 1860 mCarrierConfig.putBoolean(CarrierConfigManager.KEY_REQUIRE_ENTITLEMENT_CHECKS_BOOL, true); 1861 mCarrierConfig.putBoolean(CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL, true); 1862 sendConfigurationChanged(); 1863 } 1864 buildV4WifiUpstreamState(final String ipv4Address, final int prefixLength, final Network network)1865 private static UpstreamNetworkState buildV4WifiUpstreamState(final String ipv4Address, 1866 final int prefixLength, final Network network) { 1867 final LinkProperties prop = new LinkProperties(); 1868 prop.setInterfaceName(TEST_WIFI_IFNAME); 1869 1870 prop.addLinkAddress( 1871 new LinkAddress(InetAddresses.parseNumericAddress(ipv4Address), 1872 prefixLength)); 1873 1874 final NetworkCapabilities capabilities = new NetworkCapabilities() 1875 .addTransportType(NetworkCapabilities.TRANSPORT_WIFI); 1876 return new UpstreamNetworkState(prop, capabilities, network); 1877 } 1878 1879 @Test testHandleIpConflict()1880 public void testHandleIpConflict() throws Exception { 1881 final Network wifiNetwork = new Network(200); 1882 final Network[] allNetworks = { wifiNetwork }; 1883 when(mCm.getAllNetworks()).thenReturn(allNetworks); 1884 UpstreamNetworkState upstreamNetwork = null; 1885 runUsbTethering(upstreamNetwork); 1886 final ArgumentCaptor<InterfaceConfigurationParcel> ifaceConfigCaptor = 1887 ArgumentCaptor.forClass(InterfaceConfigurationParcel.class); 1888 verify(mNetd).interfaceSetCfg(ifaceConfigCaptor.capture()); 1889 final String ipv4Address = ifaceConfigCaptor.getValue().ipv4Addr; 1890 verify(mDhcpServer, timeout(DHCPSERVER_START_TIMEOUT_MS).times(1)).startWithCallbacks( 1891 any(), any()); 1892 reset(mNetd, mUsbManager); 1893 upstreamNetwork = buildV4WifiUpstreamState(ipv4Address, 30, wifiNetwork); 1894 mTetheringDependencies.mUpstreamNetworkMonitorSM.sendMessage( 1895 Tethering.TetherMainSM.EVENT_UPSTREAM_CALLBACK, 1896 UpstreamNetworkMonitor.EVENT_ON_LINKPROPERTIES, 1897 0, 1898 upstreamNetwork); 1899 mLooper.dispatchAll(); 1900 // verify turn off usb tethering 1901 verify(mUsbManager).setCurrentFunctions(UsbManager.FUNCTION_NONE); 1902 mTethering.interfaceRemoved(TEST_USB_IFNAME); 1903 mLooper.dispatchAll(); 1904 // verify restart usb tethering 1905 verify(mUsbManager).setCurrentFunctions(UsbManager.FUNCTION_RNDIS); 1906 } 1907 1908 @Test testNoAddressAvailable()1909 public void testNoAddressAvailable() throws Exception { 1910 final Network wifiNetwork = new Network(200); 1911 final Network[] allNetworks = { wifiNetwork }; 1912 when(mCm.getAllNetworks()).thenReturn(allNetworks); 1913 final String upstreamAddress = "192.168.0.100"; 1914 runUsbTethering(null); 1915 verify(mDhcpServer, timeout(DHCPSERVER_START_TIMEOUT_MS).times(1)).startWithCallbacks( 1916 any(), any()); 1917 reset(mUsbManager); 1918 final TetheredInterfaceRequest mockRequest = mock(TetheredInterfaceRequest.class); 1919 when(mEm.requestTetheredInterface(any(), any())).thenReturn(mockRequest); 1920 final ArgumentCaptor<TetheredInterfaceCallback> callbackCaptor = 1921 ArgumentCaptor.forClass(TetheredInterfaceCallback.class); 1922 mTethering.startTethering(createTetheringRequestParcel(TETHERING_ETHERNET), null); 1923 mLooper.dispatchAll(); 1924 verify(mEm).requestTetheredInterface(any(), callbackCaptor.capture()); 1925 TetheredInterfaceCallback ethCallback = callbackCaptor.getValue(); 1926 ethCallback.onAvailable(TEST_ETH_IFNAME); 1927 mLooper.dispatchAll(); 1928 reset(mUsbManager, mEm); 1929 1930 final UpstreamNetworkState upstreamNetwork = buildV4WifiUpstreamState( 1931 upstreamAddress, 16, wifiNetwork); 1932 mTetheringDependencies.mUpstreamNetworkMonitorSM.sendMessage( 1933 Tethering.TetherMainSM.EVENT_UPSTREAM_CALLBACK, 1934 UpstreamNetworkMonitor.EVENT_ON_LINKPROPERTIES, 1935 0, 1936 upstreamNetwork); 1937 mLooper.dispatchAll(); 1938 // verify turn off usb tethering 1939 verify(mUsbManager).setCurrentFunctions(UsbManager.FUNCTION_NONE); 1940 // verify turn off ethernet tethering 1941 verify(mockRequest).release(); 1942 mTethering.interfaceRemoved(TEST_USB_IFNAME); 1943 ethCallback.onUnavailable(); 1944 mLooper.dispatchAll(); 1945 // verify restart usb tethering 1946 verify(mUsbManager).setCurrentFunctions(UsbManager.FUNCTION_RNDIS); 1947 // verify restart ethernet tethering 1948 verify(mEm).requestTetheredInterface(any(), callbackCaptor.capture()); 1949 ethCallback = callbackCaptor.getValue(); 1950 ethCallback.onAvailable(TEST_ETH_IFNAME); 1951 1952 reset(mUsbManager, mEm); 1953 when(mNetd.interfaceGetList()) 1954 .thenReturn(new String[] { 1955 TEST_MOBILE_IFNAME, TEST_WLAN_IFNAME, TEST_USB_IFNAME, TEST_P2P_IFNAME, 1956 TEST_NCM_IFNAME, TEST_ETH_IFNAME}); 1957 1958 mTethering.interfaceStatusChanged(TEST_USB_IFNAME, true); 1959 sendUsbBroadcast(true, true, true, TETHERING_USB); 1960 mLooper.dispatchAll(); 1961 assertContains(Arrays.asList(mTethering.getTetherableIfaces()), TEST_USB_IFNAME); 1962 assertContains(Arrays.asList(mTethering.getTetherableIfaces()), TEST_ETH_IFNAME); 1963 assertEquals(TETHER_ERROR_IFACE_CFG_ERROR, mTethering.getLastTetherError(TEST_USB_IFNAME)); 1964 assertEquals(TETHER_ERROR_IFACE_CFG_ERROR, mTethering.getLastTetherError(TEST_ETH_IFNAME)); 1965 } 1966 1967 @Test testProvisioningNeededButUnavailable()1968 public void testProvisioningNeededButUnavailable() throws Exception { 1969 assertTrue(mTethering.isTetheringSupported()); 1970 verify(mPackageManager, never()).getPackageInfo(PROVISIONING_APP_NAME[0], GET_ACTIVITIES); 1971 1972 setupForRequiredProvisioning(); 1973 assertTrue(mTethering.isTetheringSupported()); 1974 verify(mPackageManager).getPackageInfo(PROVISIONING_APP_NAME[0], GET_ACTIVITIES); 1975 reset(mPackageManager); 1976 1977 doThrow(PackageManager.NameNotFoundException.class).when(mPackageManager).getPackageInfo( 1978 PROVISIONING_APP_NAME[0], GET_ACTIVITIES); 1979 setupForRequiredProvisioning(); 1980 assertFalse(mTethering.isTetheringSupported()); 1981 verify(mPackageManager).getPackageInfo(PROVISIONING_APP_NAME[0], GET_ACTIVITIES); 1982 } 1983 1984 // TODO: Test that a request for hotspot mode doesn't interfere with an 1985 // already operating tethering mode interface. 1986 } 1987