Tethering.java revision 255dd04271088590fedc46c8e22b2fd4ab142d39
1/* 2 * Copyright (C) 2010 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 17package com.android.server.connectivity; 18 19import android.app.Notification; 20import android.app.NotificationManager; 21import android.app.PendingIntent; 22import android.content.BroadcastReceiver; 23import android.content.Context; 24import android.content.Intent; 25import android.content.IntentFilter; 26import android.content.pm.PackageManager; 27import android.content.res.Resources; 28import android.hardware.usb.UsbManager; 29import android.net.ConnectivityManager; 30import android.net.INetworkStatsService; 31import android.net.InterfaceConfiguration; 32import android.net.LinkAddress; 33import android.net.LinkProperties; 34import android.net.NetworkInfo; 35import android.net.NetworkUtils; 36import android.net.RouteInfo; 37import android.os.Binder; 38import android.os.INetworkManagementService; 39import android.os.Looper; 40import android.os.Message; 41import android.os.RemoteException; 42import android.os.UserHandle; 43import android.provider.Settings; 44import android.util.Log; 45 46import com.android.internal.telephony.Phone; 47import com.android.internal.telephony.PhoneConstants; 48import com.android.internal.util.IState; 49import com.android.internal.util.State; 50import com.android.internal.util.StateMachine; 51import com.android.server.IoThread; 52import com.android.server.net.BaseNetworkObserver; 53 54import java.io.FileDescriptor; 55import java.io.PrintWriter; 56import java.net.InetAddress; 57import java.net.Inet4Address; 58import java.util.ArrayList; 59import java.util.Collection; 60import java.util.HashMap; 61import java.util.Iterator; 62import java.util.Set; 63 64/** 65 * @hide 66 * 67 * Timeout 68 * 69 * TODO - look for parent classes and code sharing 70 */ 71public class Tethering extends BaseNetworkObserver { 72 73 private Context mContext; 74 private final static String TAG = "Tethering"; 75 private final static boolean DBG = true; 76 private final static boolean VDBG = false; 77 78 // TODO - remove both of these - should be part of interface inspection/selection stuff 79 private String[] mTetherableUsbRegexs; 80 private String[] mTetherableWifiRegexs; 81 private String[] mTetherableBluetoothRegexs; 82 private Collection<Integer> mUpstreamIfaceTypes; 83 84 // used to synchronize public access to members 85 private Object mPublicSync; 86 87 private static final Integer MOBILE_TYPE = new Integer(ConnectivityManager.TYPE_MOBILE); 88 private static final Integer HIPRI_TYPE = new Integer(ConnectivityManager.TYPE_MOBILE_HIPRI); 89 private static final Integer DUN_TYPE = new Integer(ConnectivityManager.TYPE_MOBILE_DUN); 90 91 // if we have to connect to mobile, what APN type should we use? Calculated by examining the 92 // upstream type list and the DUN_REQUIRED secure-setting 93 private int mPreferredUpstreamMobileApn = ConnectivityManager.TYPE_NONE; 94 95 private final INetworkManagementService mNMService; 96 private final INetworkStatsService mStatsService; 97 private Looper mLooper; 98 99 private HashMap<String, TetherInterfaceSM> mIfaces; // all tethered/tetherable ifaces 100 101 private BroadcastReceiver mStateReceiver; 102 103 private static final String USB_NEAR_IFACE_ADDR = "192.168.42.129"; 104 private static final int USB_PREFIX_LENGTH = 24; 105 106 // USB is 192.168.42.1 and 255.255.255.0 107 // Wifi is 192.168.43.1 and 255.255.255.0 108 // BT is limited to max default of 5 connections. 192.168.44.1 to 192.168.48.1 109 // with 255.255.255.0 110 // P2P is 192.168.49.1 and 255.255.255.0 111 112 private String[] mDhcpRange; 113 private static final String[] DHCP_DEFAULT_RANGE = { 114 "192.168.42.2", "192.168.42.254", "192.168.43.2", "192.168.43.254", 115 "192.168.44.2", "192.168.44.254", "192.168.45.2", "192.168.45.254", 116 "192.168.46.2", "192.168.46.254", "192.168.47.2", "192.168.47.254", 117 "192.168.48.2", "192.168.48.254", "192.168.49.2", "192.168.49.254", 118 }; 119 120 private String[] mDefaultDnsServers; 121 private static final String DNS_DEFAULT_SERVER1 = "8.8.8.8"; 122 private static final String DNS_DEFAULT_SERVER2 = "8.8.4.4"; 123 124 private StateMachine mTetherMasterSM; 125 126 private Notification mTetheredNotification; 127 128 private boolean mRndisEnabled; // track the RNDIS function enabled state 129 private boolean mUsbTetherRequested; // true if USB tethering should be started 130 // when RNDIS is enabled 131 132 public Tethering(Context context, INetworkManagementService nmService, 133 INetworkStatsService statsService, Looper looper) { 134 mContext = context; 135 mNMService = nmService; 136 mStatsService = statsService; 137 mLooper = looper; 138 139 mPublicSync = new Object(); 140 141 mIfaces = new HashMap<String, TetherInterfaceSM>(); 142 143 // make our own thread so we don't anr the system 144 mLooper = IoThread.get().getLooper(); 145 mTetherMasterSM = new TetherMasterSM("TetherMaster", mLooper); 146 mTetherMasterSM.start(); 147 148 mStateReceiver = new StateReceiver(); 149 IntentFilter filter = new IntentFilter(); 150 filter.addAction(UsbManager.ACTION_USB_STATE); 151 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); 152 filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED); 153 mContext.registerReceiver(mStateReceiver, filter); 154 155 filter = new IntentFilter(); 156 filter.addAction(Intent.ACTION_MEDIA_SHARED); 157 filter.addAction(Intent.ACTION_MEDIA_UNSHARED); 158 filter.addDataScheme("file"); 159 mContext.registerReceiver(mStateReceiver, filter); 160 161 mDhcpRange = context.getResources().getStringArray( 162 com.android.internal.R.array.config_tether_dhcp_range); 163 if ((mDhcpRange.length == 0) || (mDhcpRange.length % 2 ==1)) { 164 mDhcpRange = DHCP_DEFAULT_RANGE; 165 } 166 167 // load device config info 168 updateConfiguration(); 169 170 // TODO - remove and rely on real notifications of the current iface 171 mDefaultDnsServers = new String[2]; 172 mDefaultDnsServers[0] = DNS_DEFAULT_SERVER1; 173 mDefaultDnsServers[1] = DNS_DEFAULT_SERVER2; 174 } 175 176 // We can't do this once in the Tethering() constructor and cache the value, because the 177 // CONNECTIVITY_SERVICE is registered only after the Tethering() constructor has completed. 178 private ConnectivityManager getConnectivityManager() { 179 return (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 180 } 181 182 void updateConfiguration() { 183 String[] tetherableUsbRegexs = mContext.getResources().getStringArray( 184 com.android.internal.R.array.config_tether_usb_regexs); 185 String[] tetherableWifiRegexs = mContext.getResources().getStringArray( 186 com.android.internal.R.array.config_tether_wifi_regexs); 187 String[] tetherableBluetoothRegexs = mContext.getResources().getStringArray( 188 com.android.internal.R.array.config_tether_bluetooth_regexs); 189 190 int ifaceTypes[] = mContext.getResources().getIntArray( 191 com.android.internal.R.array.config_tether_upstream_types); 192 Collection<Integer> upstreamIfaceTypes = new ArrayList(); 193 for (int i : ifaceTypes) { 194 upstreamIfaceTypes.add(new Integer(i)); 195 } 196 197 synchronized (mPublicSync) { 198 mTetherableUsbRegexs = tetherableUsbRegexs; 199 mTetherableWifiRegexs = tetherableWifiRegexs; 200 mTetherableBluetoothRegexs = tetherableBluetoothRegexs; 201 mUpstreamIfaceTypes = upstreamIfaceTypes; 202 } 203 204 // check if the upstream type list needs to be modified due to secure-settings 205 checkDunRequired(); 206 } 207 208 public void interfaceStatusChanged(String iface, boolean up) { 209 if (VDBG) Log.d(TAG, "interfaceStatusChanged " + iface + ", " + up); 210 boolean found = false; 211 boolean usb = false; 212 synchronized (mPublicSync) { 213 if (isWifi(iface)) { 214 found = true; 215 } else if (isUsb(iface)) { 216 found = true; 217 usb = true; 218 } else if (isBluetooth(iface)) { 219 found = true; 220 } 221 if (found == false) return; 222 223 TetherInterfaceSM sm = mIfaces.get(iface); 224 if (up) { 225 if (sm == null) { 226 sm = new TetherInterfaceSM(iface, mLooper, usb); 227 mIfaces.put(iface, sm); 228 sm.start(); 229 } 230 } else { 231 if (isUsb(iface)) { 232 // ignore usb0 down after enabling RNDIS 233 // we will handle disconnect in interfaceRemoved instead 234 if (VDBG) Log.d(TAG, "ignore interface down for " + iface); 235 } else if (sm != null) { 236 sm.sendMessage(TetherInterfaceSM.CMD_INTERFACE_DOWN); 237 mIfaces.remove(iface); 238 } 239 } 240 } 241 } 242 243 public void interfaceLinkStateChanged(String iface, boolean up) { 244 if (VDBG) Log.d(TAG, "interfaceLinkStateChanged " + iface + ", " + up); 245 interfaceStatusChanged(iface, up); 246 } 247 248 private boolean isUsb(String iface) { 249 synchronized (mPublicSync) { 250 for (String regex : mTetherableUsbRegexs) { 251 if (iface.matches(regex)) return true; 252 } 253 return false; 254 } 255 } 256 257 public boolean isWifi(String iface) { 258 synchronized (mPublicSync) { 259 for (String regex : mTetherableWifiRegexs) { 260 if (iface.matches(regex)) return true; 261 } 262 return false; 263 } 264 } 265 266 public boolean isBluetooth(String iface) { 267 synchronized (mPublicSync) { 268 for (String regex : mTetherableBluetoothRegexs) { 269 if (iface.matches(regex)) return true; 270 } 271 return false; 272 } 273 } 274 275 public void interfaceAdded(String iface) { 276 if (VDBG) Log.d(TAG, "interfaceAdded " + iface); 277 boolean found = false; 278 boolean usb = false; 279 synchronized (mPublicSync) { 280 if (isWifi(iface)) { 281 found = true; 282 } 283 if (isUsb(iface)) { 284 found = true; 285 usb = true; 286 } 287 if (isBluetooth(iface)) { 288 found = true; 289 } 290 if (found == false) { 291 if (VDBG) Log.d(TAG, iface + " is not a tetherable iface, ignoring"); 292 return; 293 } 294 295 TetherInterfaceSM sm = mIfaces.get(iface); 296 if (sm != null) { 297 if (VDBG) Log.d(TAG, "active iface (" + iface + ") reported as added, ignoring"); 298 return; 299 } 300 sm = new TetherInterfaceSM(iface, mLooper, usb); 301 mIfaces.put(iface, sm); 302 sm.start(); 303 } 304 } 305 306 public void interfaceRemoved(String iface) { 307 if (VDBG) Log.d(TAG, "interfaceRemoved " + iface); 308 synchronized (mPublicSync) { 309 TetherInterfaceSM sm = mIfaces.get(iface); 310 if (sm == null) { 311 if (VDBG) { 312 Log.e(TAG, "attempting to remove unknown iface (" + iface + "), ignoring"); 313 } 314 return; 315 } 316 sm.sendMessage(TetherInterfaceSM.CMD_INTERFACE_DOWN); 317 mIfaces.remove(iface); 318 } 319 } 320 321 public int tether(String iface) { 322 if (DBG) Log.d(TAG, "Tethering " + iface); 323 TetherInterfaceSM sm = null; 324 synchronized (mPublicSync) { 325 sm = mIfaces.get(iface); 326 } 327 if (sm == null) { 328 Log.e(TAG, "Tried to Tether an unknown iface :" + iface + ", ignoring"); 329 return ConnectivityManager.TETHER_ERROR_UNKNOWN_IFACE; 330 } 331 if (!sm.isAvailable() && !sm.isErrored()) { 332 Log.e(TAG, "Tried to Tether an unavailable iface :" + iface + ", ignoring"); 333 return ConnectivityManager.TETHER_ERROR_UNAVAIL_IFACE; 334 } 335 sm.sendMessage(TetherInterfaceSM.CMD_TETHER_REQUESTED); 336 return ConnectivityManager.TETHER_ERROR_NO_ERROR; 337 } 338 339 public int untether(String iface) { 340 if (DBG) Log.d(TAG, "Untethering " + iface); 341 TetherInterfaceSM sm = null; 342 synchronized (mPublicSync) { 343 sm = mIfaces.get(iface); 344 } 345 if (sm == null) { 346 Log.e(TAG, "Tried to Untether an unknown iface :" + iface + ", ignoring"); 347 return ConnectivityManager.TETHER_ERROR_UNKNOWN_IFACE; 348 } 349 if (sm.isErrored()) { 350 Log.e(TAG, "Tried to Untethered an errored iface :" + iface + ", ignoring"); 351 return ConnectivityManager.TETHER_ERROR_UNAVAIL_IFACE; 352 } 353 sm.sendMessage(TetherInterfaceSM.CMD_TETHER_UNREQUESTED); 354 return ConnectivityManager.TETHER_ERROR_NO_ERROR; 355 } 356 357 public int getLastTetherError(String iface) { 358 TetherInterfaceSM sm = null; 359 synchronized (mPublicSync) { 360 sm = mIfaces.get(iface); 361 if (sm == null) { 362 Log.e(TAG, "Tried to getLastTetherError on an unknown iface :" + iface + 363 ", ignoring"); 364 return ConnectivityManager.TETHER_ERROR_UNKNOWN_IFACE; 365 } 366 return sm.getLastError(); 367 } 368 } 369 370 // TODO - move all private methods used only by the state machine into the state machine 371 // to clarify what needs synchronized protection. 372 private void sendTetherStateChangedBroadcast() { 373 if (!getConnectivityManager().isTetheringSupported()) return; 374 375 ArrayList<String> availableList = new ArrayList<String>(); 376 ArrayList<String> activeList = new ArrayList<String>(); 377 ArrayList<String> erroredList = new ArrayList<String>(); 378 379 boolean wifiTethered = false; 380 boolean usbTethered = false; 381 boolean bluetoothTethered = false; 382 383 synchronized (mPublicSync) { 384 Set ifaces = mIfaces.keySet(); 385 for (Object iface : ifaces) { 386 TetherInterfaceSM sm = mIfaces.get(iface); 387 if (sm != null) { 388 if (sm.isErrored()) { 389 erroredList.add((String)iface); 390 } else if (sm.isAvailable()) { 391 availableList.add((String)iface); 392 } else if (sm.isTethered()) { 393 if (isUsb((String)iface)) { 394 usbTethered = true; 395 } else if (isWifi((String)iface)) { 396 wifiTethered = true; 397 } else if (isBluetooth((String)iface)) { 398 bluetoothTethered = true; 399 } 400 activeList.add((String)iface); 401 } 402 } 403 } 404 } 405 Intent broadcast = new Intent(ConnectivityManager.ACTION_TETHER_STATE_CHANGED); 406 broadcast.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING | 407 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 408 broadcast.putStringArrayListExtra(ConnectivityManager.EXTRA_AVAILABLE_TETHER, 409 availableList); 410 broadcast.putStringArrayListExtra(ConnectivityManager.EXTRA_ACTIVE_TETHER, activeList); 411 broadcast.putStringArrayListExtra(ConnectivityManager.EXTRA_ERRORED_TETHER, 412 erroredList); 413 mContext.sendStickyBroadcastAsUser(broadcast, UserHandle.ALL); 414 if (DBG) { 415 Log.d(TAG, "sendTetherStateChangedBroadcast " + availableList.size() + ", " + 416 activeList.size() + ", " + erroredList.size()); 417 } 418 419 if (usbTethered) { 420 if (wifiTethered || bluetoothTethered) { 421 showTetheredNotification(com.android.internal.R.drawable.stat_sys_tether_general); 422 } else { 423 showTetheredNotification(com.android.internal.R.drawable.stat_sys_tether_usb); 424 } 425 } else if (wifiTethered) { 426 if (bluetoothTethered) { 427 showTetheredNotification(com.android.internal.R.drawable.stat_sys_tether_general); 428 } else { 429 showTetheredNotification(com.android.internal.R.drawable.stat_sys_tether_wifi); 430 } 431 } else if (bluetoothTethered) { 432 showTetheredNotification(com.android.internal.R.drawable.stat_sys_tether_bluetooth); 433 } else { 434 clearTetheredNotification(); 435 } 436 } 437 438 private void showTetheredNotification(int icon) { 439 NotificationManager notificationManager = 440 (NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE); 441 if (notificationManager == null) { 442 return; 443 } 444 445 if (mTetheredNotification != null) { 446 if (mTetheredNotification.icon == icon) { 447 return; 448 } 449 notificationManager.cancelAsUser(null, mTetheredNotification.icon, 450 UserHandle.ALL); 451 } 452 453 Intent intent = new Intent(); 454 intent.setClassName("com.android.settings", "com.android.settings.TetherSettings"); 455 intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); 456 457 PendingIntent pi = PendingIntent.getActivityAsUser(mContext, 0, intent, 0, 458 null, UserHandle.CURRENT); 459 460 Resources r = Resources.getSystem(); 461 CharSequence title = r.getText(com.android.internal.R.string.tethered_notification_title); 462 CharSequence message = r.getText(com.android.internal.R.string. 463 tethered_notification_message); 464 465 if (mTetheredNotification == null) { 466 mTetheredNotification = new Notification(); 467 mTetheredNotification.when = 0; 468 } 469 mTetheredNotification.icon = icon; 470 mTetheredNotification.defaults &= ~Notification.DEFAULT_SOUND; 471 mTetheredNotification.flags = Notification.FLAG_ONGOING_EVENT; 472 mTetheredNotification.tickerText = title; 473 mTetheredNotification.visibility = Notification.VISIBILITY_PUBLIC; 474 mTetheredNotification.color = mContext.getResources().getColor( 475 com.android.internal.R.color.system_notification_accent_color); 476 mTetheredNotification.setLatestEventInfo(mContext, title, message, pi); 477 mTetheredNotification.category = Notification.CATEGORY_STATUS; 478 479 notificationManager.notifyAsUser(null, mTetheredNotification.icon, 480 mTetheredNotification, UserHandle.ALL); 481 } 482 483 private void clearTetheredNotification() { 484 NotificationManager notificationManager = 485 (NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE); 486 if (notificationManager != null && mTetheredNotification != null) { 487 notificationManager.cancelAsUser(null, mTetheredNotification.icon, 488 UserHandle.ALL); 489 mTetheredNotification = null; 490 } 491 } 492 493 private class StateReceiver extends BroadcastReceiver { 494 @Override 495 public void onReceive(Context content, Intent intent) { 496 String action = intent.getAction(); 497 if (action == null) { return; } 498 if (action.equals(UsbManager.ACTION_USB_STATE)) { 499 synchronized (Tethering.this.mPublicSync) { 500 boolean usbConnected = intent.getBooleanExtra(UsbManager.USB_CONNECTED, false); 501 mRndisEnabled = intent.getBooleanExtra(UsbManager.USB_FUNCTION_RNDIS, false); 502 // start tethering if we have a request pending 503 if (usbConnected && mRndisEnabled && mUsbTetherRequested) { 504 tetherUsb(true); 505 } 506 mUsbTetherRequested = false; 507 } 508 } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { 509 NetworkInfo networkInfo = (NetworkInfo)intent.getParcelableExtra( 510 ConnectivityManager.EXTRA_NETWORK_INFO); 511 if (networkInfo != null && 512 networkInfo.getDetailedState() != NetworkInfo.DetailedState.FAILED) { 513 if (VDBG) Log.d(TAG, "Tethering got CONNECTIVITY_ACTION"); 514 mTetherMasterSM.sendMessage(TetherMasterSM.CMD_UPSTREAM_CHANGED); 515 } 516 } else if (action.equals(Intent.ACTION_CONFIGURATION_CHANGED)) { 517 updateConfiguration(); 518 } 519 } 520 } 521 522 private void tetherUsb(boolean enable) { 523 if (VDBG) Log.d(TAG, "tetherUsb " + enable); 524 525 String[] ifaces = new String[0]; 526 try { 527 ifaces = mNMService.listInterfaces(); 528 } catch (Exception e) { 529 Log.e(TAG, "Error listing Interfaces", e); 530 return; 531 } 532 for (String iface : ifaces) { 533 if (isUsb(iface)) { 534 int result = (enable ? tether(iface) : untether(iface)); 535 if (result == ConnectivityManager.TETHER_ERROR_NO_ERROR) { 536 return; 537 } 538 } 539 } 540 Log.e(TAG, "unable start or stop USB tethering"); 541 } 542 543 // configured when we start tethering and unconfig'd on error or conclusion 544 private boolean configureUsbIface(boolean enabled) { 545 if (VDBG) Log.d(TAG, "configureUsbIface(" + enabled + ")"); 546 547 // toggle the USB interfaces 548 String[] ifaces = new String[0]; 549 try { 550 ifaces = mNMService.listInterfaces(); 551 } catch (Exception e) { 552 Log.e(TAG, "Error listing Interfaces", e); 553 return false; 554 } 555 for (String iface : ifaces) { 556 if (isUsb(iface)) { 557 InterfaceConfiguration ifcg = null; 558 try { 559 ifcg = mNMService.getInterfaceConfig(iface); 560 if (ifcg != null) { 561 InetAddress addr = NetworkUtils.numericToInetAddress(USB_NEAR_IFACE_ADDR); 562 ifcg.setLinkAddress(new LinkAddress(addr, USB_PREFIX_LENGTH)); 563 if (enabled) { 564 ifcg.setInterfaceUp(); 565 } else { 566 ifcg.setInterfaceDown(); 567 } 568 ifcg.clearFlag("running"); 569 mNMService.setInterfaceConfig(iface, ifcg); 570 } 571 } catch (Exception e) { 572 Log.e(TAG, "Error configuring interface " + iface, e); 573 return false; 574 } 575 } 576 } 577 578 return true; 579 } 580 581 // TODO - return copies so people can't tamper 582 public String[] getTetherableUsbRegexs() { 583 return mTetherableUsbRegexs; 584 } 585 586 public String[] getTetherableWifiRegexs() { 587 return mTetherableWifiRegexs; 588 } 589 590 public String[] getTetherableBluetoothRegexs() { 591 return mTetherableBluetoothRegexs; 592 } 593 594 public int setUsbTethering(boolean enable) { 595 if (VDBG) Log.d(TAG, "setUsbTethering(" + enable + ")"); 596 UsbManager usbManager = (UsbManager)mContext.getSystemService(Context.USB_SERVICE); 597 598 synchronized (mPublicSync) { 599 if (enable) { 600 if (mRndisEnabled) { 601 tetherUsb(true); 602 } else { 603 mUsbTetherRequested = true; 604 usbManager.setCurrentFunction(UsbManager.USB_FUNCTION_RNDIS, false); 605 } 606 } else { 607 tetherUsb(false); 608 if (mRndisEnabled) { 609 usbManager.setCurrentFunction(null, false); 610 } 611 mUsbTetherRequested = false; 612 } 613 } 614 return ConnectivityManager.TETHER_ERROR_NO_ERROR; 615 } 616 617 public int[] getUpstreamIfaceTypes() { 618 int values[]; 619 synchronized (mPublicSync) { 620 updateConfiguration(); // TODO - remove? 621 values = new int[mUpstreamIfaceTypes.size()]; 622 Iterator<Integer> iterator = mUpstreamIfaceTypes.iterator(); 623 for (int i=0; i < mUpstreamIfaceTypes.size(); i++) { 624 values[i] = iterator.next(); 625 } 626 } 627 return values; 628 } 629 630 public void checkDunRequired() { 631 int secureSetting = Settings.Global.getInt(mContext.getContentResolver(), 632 Settings.Global.TETHER_DUN_REQUIRED, 2); 633 synchronized (mPublicSync) { 634 // 2 = not set, 0 = DUN not required, 1 = DUN required 635 if (secureSetting != 2) { 636 int requiredApn = (secureSetting == 1 ? 637 ConnectivityManager.TYPE_MOBILE_DUN : 638 ConnectivityManager.TYPE_MOBILE_HIPRI); 639 if (requiredApn == ConnectivityManager.TYPE_MOBILE_DUN) { 640 while (mUpstreamIfaceTypes.contains(MOBILE_TYPE)) { 641 mUpstreamIfaceTypes.remove(MOBILE_TYPE); 642 } 643 while (mUpstreamIfaceTypes.contains(HIPRI_TYPE)) { 644 mUpstreamIfaceTypes.remove(HIPRI_TYPE); 645 } 646 if (mUpstreamIfaceTypes.contains(DUN_TYPE) == false) { 647 mUpstreamIfaceTypes.add(DUN_TYPE); 648 } 649 } else { 650 while (mUpstreamIfaceTypes.contains(DUN_TYPE)) { 651 mUpstreamIfaceTypes.remove(DUN_TYPE); 652 } 653 if (mUpstreamIfaceTypes.contains(MOBILE_TYPE) == false) { 654 mUpstreamIfaceTypes.add(MOBILE_TYPE); 655 } 656 if (mUpstreamIfaceTypes.contains(HIPRI_TYPE) == false) { 657 mUpstreamIfaceTypes.add(HIPRI_TYPE); 658 } 659 } 660 } 661 if (mUpstreamIfaceTypes.contains(DUN_TYPE)) { 662 mPreferredUpstreamMobileApn = ConnectivityManager.TYPE_MOBILE_DUN; 663 } else { 664 mPreferredUpstreamMobileApn = ConnectivityManager.TYPE_MOBILE_HIPRI; 665 } 666 } 667 } 668 669 // TODO review API - maybe return ArrayList<String> here and below? 670 public String[] getTetheredIfaces() { 671 ArrayList<String> list = new ArrayList<String>(); 672 synchronized (mPublicSync) { 673 Set keys = mIfaces.keySet(); 674 for (Object key : keys) { 675 TetherInterfaceSM sm = mIfaces.get(key); 676 if (sm.isTethered()) { 677 list.add((String)key); 678 } 679 } 680 } 681 String[] retVal = new String[list.size()]; 682 for (int i=0; i < list.size(); i++) { 683 retVal[i] = list.get(i); 684 } 685 return retVal; 686 } 687 688 public String[] getTetherableIfaces() { 689 ArrayList<String> list = new ArrayList<String>(); 690 synchronized (mPublicSync) { 691 Set keys = mIfaces.keySet(); 692 for (Object key : keys) { 693 TetherInterfaceSM sm = mIfaces.get(key); 694 if (sm.isAvailable()) { 695 list.add((String)key); 696 } 697 } 698 } 699 String[] retVal = new String[list.size()]; 700 for (int i=0; i < list.size(); i++) { 701 retVal[i] = list.get(i); 702 } 703 return retVal; 704 } 705 706 public String[] getTetheredDhcpRanges() { 707 return mDhcpRange; 708 } 709 710 public String[] getErroredIfaces() { 711 ArrayList<String> list = new ArrayList<String>(); 712 synchronized (mPublicSync) { 713 Set keys = mIfaces.keySet(); 714 for (Object key : keys) { 715 TetherInterfaceSM sm = mIfaces.get(key); 716 if (sm.isErrored()) { 717 list.add((String)key); 718 } 719 } 720 } 721 String[] retVal = new String[list.size()]; 722 for (int i= 0; i< list.size(); i++) { 723 retVal[i] = list.get(i); 724 } 725 return retVal; 726 } 727 728 class TetherInterfaceSM extends StateMachine { 729 // notification from the master SM that it's not in tether mode 730 static final int CMD_TETHER_MODE_DEAD = 1; 731 // request from the user that it wants to tether 732 static final int CMD_TETHER_REQUESTED = 2; 733 // request from the user that it wants to untether 734 static final int CMD_TETHER_UNREQUESTED = 3; 735 // notification that this interface is down 736 static final int CMD_INTERFACE_DOWN = 4; 737 // notification that this interface is up 738 static final int CMD_INTERFACE_UP = 5; 739 // notification from the master SM that it had an error turning on cellular dun 740 static final int CMD_CELL_DUN_ERROR = 6; 741 // notification from the master SM that it had trouble enabling IP Forwarding 742 static final int CMD_IP_FORWARDING_ENABLE_ERROR = 7; 743 // notification from the master SM that it had trouble disabling IP Forwarding 744 static final int CMD_IP_FORWARDING_DISABLE_ERROR = 8; 745 // notification from the master SM that it had trouble staring tethering 746 static final int CMD_START_TETHERING_ERROR = 9; 747 // notification from the master SM that it had trouble stopping tethering 748 static final int CMD_STOP_TETHERING_ERROR = 10; 749 // notification from the master SM that it had trouble setting the DNS forwarders 750 static final int CMD_SET_DNS_FORWARDERS_ERROR = 11; 751 // the upstream connection has changed 752 static final int CMD_TETHER_CONNECTION_CHANGED = 12; 753 754 private State mDefaultState; 755 756 private State mInitialState; 757 private State mStartingState; 758 private State mTetheredState; 759 760 private State mUnavailableState; 761 762 private boolean mAvailable; 763 private boolean mTethered; 764 int mLastError; 765 766 String mIfaceName; 767 String mMyUpstreamIfaceName; // may change over time 768 769 boolean mUsb; 770 771 TetherInterfaceSM(String name, Looper looper, boolean usb) { 772 super(name, looper); 773 mIfaceName = name; 774 mUsb = usb; 775 setLastError(ConnectivityManager.TETHER_ERROR_NO_ERROR); 776 777 mInitialState = new InitialState(); 778 addState(mInitialState); 779 mStartingState = new StartingState(); 780 addState(mStartingState); 781 mTetheredState = new TetheredState(); 782 addState(mTetheredState); 783 mUnavailableState = new UnavailableState(); 784 addState(mUnavailableState); 785 786 setInitialState(mInitialState); 787 } 788 789 public String toString() { 790 String res = new String(); 791 res += mIfaceName + " - "; 792 IState current = getCurrentState(); 793 if (current == mInitialState) res += "InitialState"; 794 if (current == mStartingState) res += "StartingState"; 795 if (current == mTetheredState) res += "TetheredState"; 796 if (current == mUnavailableState) res += "UnavailableState"; 797 if (mAvailable) res += " - Available"; 798 if (mTethered) res += " - Tethered"; 799 res += " - lastError =" + mLastError; 800 return res; 801 } 802 803 public int getLastError() { 804 synchronized (Tethering.this.mPublicSync) { 805 return mLastError; 806 } 807 } 808 809 private void setLastError(int error) { 810 synchronized (Tethering.this.mPublicSync) { 811 mLastError = error; 812 813 if (isErrored()) { 814 if (mUsb) { 815 // note everything's been unwound by this point so nothing to do on 816 // further error.. 817 Tethering.this.configureUsbIface(false); 818 } 819 } 820 } 821 } 822 823 public boolean isAvailable() { 824 synchronized (Tethering.this.mPublicSync) { 825 return mAvailable; 826 } 827 } 828 829 private void setAvailable(boolean available) { 830 synchronized (Tethering.this.mPublicSync) { 831 mAvailable = available; 832 } 833 } 834 835 public boolean isTethered() { 836 synchronized (Tethering.this.mPublicSync) { 837 return mTethered; 838 } 839 } 840 841 private void setTethered(boolean tethered) { 842 synchronized (Tethering.this.mPublicSync) { 843 mTethered = tethered; 844 } 845 } 846 847 public boolean isErrored() { 848 synchronized (Tethering.this.mPublicSync) { 849 return (mLastError != ConnectivityManager.TETHER_ERROR_NO_ERROR); 850 } 851 } 852 853 class InitialState extends State { 854 @Override 855 public void enter() { 856 setAvailable(true); 857 setTethered(false); 858 sendTetherStateChangedBroadcast(); 859 } 860 861 @Override 862 public boolean processMessage(Message message) { 863 if (DBG) Log.d(TAG, "InitialState.processMessage what=" + message.what); 864 boolean retValue = true; 865 switch (message.what) { 866 case CMD_TETHER_REQUESTED: 867 setLastError(ConnectivityManager.TETHER_ERROR_NO_ERROR); 868 mTetherMasterSM.sendMessage(TetherMasterSM.CMD_TETHER_MODE_REQUESTED, 869 TetherInterfaceSM.this); 870 transitionTo(mStartingState); 871 break; 872 case CMD_INTERFACE_DOWN: 873 transitionTo(mUnavailableState); 874 break; 875 default: 876 retValue = false; 877 break; 878 } 879 return retValue; 880 } 881 } 882 883 class StartingState extends State { 884 @Override 885 public void enter() { 886 setAvailable(false); 887 if (mUsb) { 888 if (!Tethering.this.configureUsbIface(true)) { 889 mTetherMasterSM.sendMessage(TetherMasterSM.CMD_TETHER_MODE_UNREQUESTED, 890 TetherInterfaceSM.this); 891 setLastError(ConnectivityManager.TETHER_ERROR_IFACE_CFG_ERROR); 892 893 transitionTo(mInitialState); 894 return; 895 } 896 } 897 sendTetherStateChangedBroadcast(); 898 899 // Skipping StartingState 900 transitionTo(mTetheredState); 901 } 902 @Override 903 public boolean processMessage(Message message) { 904 if (DBG) Log.d(TAG, "StartingState.processMessage what=" + message.what); 905 boolean retValue = true; 906 switch (message.what) { 907 // maybe a parent class? 908 case CMD_TETHER_UNREQUESTED: 909 mTetherMasterSM.sendMessage(TetherMasterSM.CMD_TETHER_MODE_UNREQUESTED, 910 TetherInterfaceSM.this); 911 if (mUsb) { 912 if (!Tethering.this.configureUsbIface(false)) { 913 setLastErrorAndTransitionToInitialState( 914 ConnectivityManager.TETHER_ERROR_IFACE_CFG_ERROR); 915 break; 916 } 917 } 918 transitionTo(mInitialState); 919 break; 920 case CMD_CELL_DUN_ERROR: 921 case CMD_IP_FORWARDING_ENABLE_ERROR: 922 case CMD_IP_FORWARDING_DISABLE_ERROR: 923 case CMD_START_TETHERING_ERROR: 924 case CMD_STOP_TETHERING_ERROR: 925 case CMD_SET_DNS_FORWARDERS_ERROR: 926 setLastErrorAndTransitionToInitialState( 927 ConnectivityManager.TETHER_ERROR_MASTER_ERROR); 928 break; 929 case CMD_INTERFACE_DOWN: 930 mTetherMasterSM.sendMessage(TetherMasterSM.CMD_TETHER_MODE_UNREQUESTED, 931 TetherInterfaceSM.this); 932 transitionTo(mUnavailableState); 933 break; 934 default: 935 retValue = false; 936 } 937 return retValue; 938 } 939 } 940 941 class TetheredState extends State { 942 @Override 943 public void enter() { 944 try { 945 mNMService.tetherInterface(mIfaceName); 946 } catch (Exception e) { 947 Log.e(TAG, "Error Tethering: " + e.toString()); 948 setLastError(ConnectivityManager.TETHER_ERROR_TETHER_IFACE_ERROR); 949 950 transitionTo(mInitialState); 951 return; 952 } 953 if (DBG) Log.d(TAG, "Tethered " + mIfaceName); 954 setAvailable(false); 955 setTethered(true); 956 sendTetherStateChangedBroadcast(); 957 } 958 959 private void cleanupUpstream() { 960 if (mMyUpstreamIfaceName != null) { 961 // note that we don't care about errors here. 962 // sometimes interfaces are gone before we get 963 // to remove their rules, which generates errors. 964 // just do the best we can. 965 try { 966 // about to tear down NAT; gather remaining statistics 967 mStatsService.forceUpdate(); 968 } catch (Exception e) { 969 if (VDBG) Log.e(TAG, "Exception in forceUpdate: " + e.toString()); 970 } 971 try { 972 mNMService.disableNat(mIfaceName, mMyUpstreamIfaceName); 973 } catch (Exception e) { 974 if (VDBG) Log.e(TAG, "Exception in disableNat: " + e.toString()); 975 } 976 mMyUpstreamIfaceName = null; 977 } 978 return; 979 } 980 981 @Override 982 public boolean processMessage(Message message) { 983 if (DBG) Log.d(TAG, "TetheredState.processMessage what=" + message.what); 984 boolean retValue = true; 985 boolean error = false; 986 switch (message.what) { 987 case CMD_TETHER_UNREQUESTED: 988 case CMD_INTERFACE_DOWN: 989 cleanupUpstream(); 990 try { 991 mNMService.untetherInterface(mIfaceName); 992 } catch (Exception e) { 993 setLastErrorAndTransitionToInitialState( 994 ConnectivityManager.TETHER_ERROR_UNTETHER_IFACE_ERROR); 995 break; 996 } 997 mTetherMasterSM.sendMessage(TetherMasterSM.CMD_TETHER_MODE_UNREQUESTED, 998 TetherInterfaceSM.this); 999 if (message.what == CMD_TETHER_UNREQUESTED) { 1000 if (mUsb) { 1001 if (!Tethering.this.configureUsbIface(false)) { 1002 setLastError( 1003 ConnectivityManager.TETHER_ERROR_IFACE_CFG_ERROR); 1004 } 1005 } 1006 transitionTo(mInitialState); 1007 } else if (message.what == CMD_INTERFACE_DOWN) { 1008 transitionTo(mUnavailableState); 1009 } 1010 if (DBG) Log.d(TAG, "Untethered " + mIfaceName); 1011 break; 1012 case CMD_TETHER_CONNECTION_CHANGED: 1013 String newUpstreamIfaceName = (String)(message.obj); 1014 if ((mMyUpstreamIfaceName == null && newUpstreamIfaceName == null) || 1015 (mMyUpstreamIfaceName != null && 1016 mMyUpstreamIfaceName.equals(newUpstreamIfaceName))) { 1017 if (VDBG) Log.d(TAG, "Connection changed noop - dropping"); 1018 break; 1019 } 1020 cleanupUpstream(); 1021 if (newUpstreamIfaceName != null) { 1022 try { 1023 mNMService.enableNat(mIfaceName, newUpstreamIfaceName); 1024 } catch (Exception e) { 1025 Log.e(TAG, "Exception enabling Nat: " + e.toString()); 1026 try { 1027 mNMService.untetherInterface(mIfaceName); 1028 } catch (Exception ee) {} 1029 1030 setLastError(ConnectivityManager.TETHER_ERROR_ENABLE_NAT_ERROR); 1031 transitionTo(mInitialState); 1032 return true; 1033 } 1034 } 1035 mMyUpstreamIfaceName = newUpstreamIfaceName; 1036 break; 1037 case CMD_CELL_DUN_ERROR: 1038 case CMD_IP_FORWARDING_ENABLE_ERROR: 1039 case CMD_IP_FORWARDING_DISABLE_ERROR: 1040 case CMD_START_TETHERING_ERROR: 1041 case CMD_STOP_TETHERING_ERROR: 1042 case CMD_SET_DNS_FORWARDERS_ERROR: 1043 error = true; 1044 // fall through 1045 case CMD_TETHER_MODE_DEAD: 1046 cleanupUpstream(); 1047 try { 1048 mNMService.untetherInterface(mIfaceName); 1049 } catch (Exception e) { 1050 setLastErrorAndTransitionToInitialState( 1051 ConnectivityManager.TETHER_ERROR_UNTETHER_IFACE_ERROR); 1052 break; 1053 } 1054 if (error) { 1055 setLastErrorAndTransitionToInitialState( 1056 ConnectivityManager.TETHER_ERROR_MASTER_ERROR); 1057 break; 1058 } 1059 if (DBG) Log.d(TAG, "Tether lost upstream connection " + mIfaceName); 1060 sendTetherStateChangedBroadcast(); 1061 if (mUsb) { 1062 if (!Tethering.this.configureUsbIface(false)) { 1063 setLastError(ConnectivityManager.TETHER_ERROR_IFACE_CFG_ERROR); 1064 } 1065 } 1066 transitionTo(mInitialState); 1067 break; 1068 default: 1069 retValue = false; 1070 break; 1071 } 1072 return retValue; 1073 } 1074 } 1075 1076 class UnavailableState extends State { 1077 @Override 1078 public void enter() { 1079 setAvailable(false); 1080 setLastError(ConnectivityManager.TETHER_ERROR_NO_ERROR); 1081 setTethered(false); 1082 sendTetherStateChangedBroadcast(); 1083 } 1084 @Override 1085 public boolean processMessage(Message message) { 1086 boolean retValue = true; 1087 switch (message.what) { 1088 case CMD_INTERFACE_UP: 1089 transitionTo(mInitialState); 1090 break; 1091 default: 1092 retValue = false; 1093 break; 1094 } 1095 return retValue; 1096 } 1097 } 1098 1099 void setLastErrorAndTransitionToInitialState(int error) { 1100 setLastError(error); 1101 transitionTo(mInitialState); 1102 } 1103 1104 } 1105 1106 class TetherMasterSM extends StateMachine { 1107 // an interface SM has requested Tethering 1108 static final int CMD_TETHER_MODE_REQUESTED = 1; 1109 // an interface SM has unrequested Tethering 1110 static final int CMD_TETHER_MODE_UNREQUESTED = 2; 1111 // upstream connection change - do the right thing 1112 static final int CMD_UPSTREAM_CHANGED = 3; 1113 // we received notice that the cellular DUN connection is up 1114 static final int CMD_CELL_CONNECTION_RENEW = 4; 1115 // we don't have a valid upstream conn, check again after a delay 1116 static final int CMD_RETRY_UPSTREAM = 5; 1117 1118 // This indicates what a timeout event relates to. A state that 1119 // sends itself a delayed timeout event and handles incoming timeout events 1120 // should inc this when it is entered and whenever it sends a new timeout event. 1121 // We do not flush the old ones. 1122 private int mSequenceNumber; 1123 1124 private State mInitialState; 1125 private State mTetherModeAliveState; 1126 1127 private State mSetIpForwardingEnabledErrorState; 1128 private State mSetIpForwardingDisabledErrorState; 1129 private State mStartTetheringErrorState; 1130 private State mStopTetheringErrorState; 1131 private State mSetDnsForwardersErrorState; 1132 1133 private ArrayList<TetherInterfaceSM> mNotifyList; 1134 1135 private int mCurrentConnectionSequence; 1136 private int mMobileApnReserved = ConnectivityManager.TYPE_NONE; 1137 1138 private String mUpstreamIfaceName = null; 1139 1140 private static final int UPSTREAM_SETTLE_TIME_MS = 10000; 1141 private static final int CELL_CONNECTION_RENEW_MS = 40000; 1142 1143 TetherMasterSM(String name, Looper looper) { 1144 super(name, looper); 1145 1146 //Add states 1147 mInitialState = new InitialState(); 1148 addState(mInitialState); 1149 mTetherModeAliveState = new TetherModeAliveState(); 1150 addState(mTetherModeAliveState); 1151 1152 mSetIpForwardingEnabledErrorState = new SetIpForwardingEnabledErrorState(); 1153 addState(mSetIpForwardingEnabledErrorState); 1154 mSetIpForwardingDisabledErrorState = new SetIpForwardingDisabledErrorState(); 1155 addState(mSetIpForwardingDisabledErrorState); 1156 mStartTetheringErrorState = new StartTetheringErrorState(); 1157 addState(mStartTetheringErrorState); 1158 mStopTetheringErrorState = new StopTetheringErrorState(); 1159 addState(mStopTetheringErrorState); 1160 mSetDnsForwardersErrorState = new SetDnsForwardersErrorState(); 1161 addState(mSetDnsForwardersErrorState); 1162 1163 mNotifyList = new ArrayList<TetherInterfaceSM>(); 1164 setInitialState(mInitialState); 1165 } 1166 1167 class TetherMasterUtilState extends State { 1168 protected final static boolean TRY_TO_SETUP_MOBILE_CONNECTION = true; 1169 protected final static boolean WAIT_FOR_NETWORK_TO_SETTLE = false; 1170 1171 @Override 1172 public boolean processMessage(Message m) { 1173 return false; 1174 } 1175 protected String enableString(int apnType) { 1176 switch (apnType) { 1177 case ConnectivityManager.TYPE_MOBILE_DUN: 1178 return Phone.FEATURE_ENABLE_DUN_ALWAYS; 1179 case ConnectivityManager.TYPE_MOBILE: 1180 case ConnectivityManager.TYPE_MOBILE_HIPRI: 1181 return Phone.FEATURE_ENABLE_HIPRI; 1182 } 1183 return null; 1184 } 1185 protected boolean turnOnUpstreamMobileConnection(int apnType) { 1186 boolean retValue = true; 1187 if (apnType == ConnectivityManager.TYPE_NONE) return false; 1188 if (apnType != mMobileApnReserved) turnOffUpstreamMobileConnection(); 1189 int result = PhoneConstants.APN_REQUEST_FAILED; 1190 String enableString = enableString(apnType); 1191 if (enableString == null) return false; 1192 result = getConnectivityManager().startUsingNetworkFeature( 1193 ConnectivityManager.TYPE_MOBILE, enableString); 1194 switch (result) { 1195 case PhoneConstants.APN_ALREADY_ACTIVE: 1196 case PhoneConstants.APN_REQUEST_STARTED: 1197 mMobileApnReserved = apnType; 1198 Message m = obtainMessage(CMD_CELL_CONNECTION_RENEW); 1199 m.arg1 = ++mCurrentConnectionSequence; 1200 sendMessageDelayed(m, CELL_CONNECTION_RENEW_MS); 1201 break; 1202 case PhoneConstants.APN_REQUEST_FAILED: 1203 default: 1204 retValue = false; 1205 break; 1206 } 1207 1208 return retValue; 1209 } 1210 protected boolean turnOffUpstreamMobileConnection() { 1211 // ignore pending renewal requests 1212 ++mCurrentConnectionSequence; 1213 if (mMobileApnReserved != ConnectivityManager.TYPE_NONE) { 1214 getConnectivityManager().stopUsingNetworkFeature( 1215 ConnectivityManager.TYPE_MOBILE, enableString(mMobileApnReserved)); 1216 mMobileApnReserved = ConnectivityManager.TYPE_NONE; 1217 } 1218 return true; 1219 } 1220 protected boolean turnOnMasterTetherSettings() { 1221 try { 1222 mNMService.setIpForwardingEnabled(true); 1223 } catch (Exception e) { 1224 transitionTo(mSetIpForwardingEnabledErrorState); 1225 return false; 1226 } 1227 try { 1228 mNMService.startTethering(mDhcpRange); 1229 } catch (Exception e) { 1230 try { 1231 mNMService.stopTethering(); 1232 mNMService.startTethering(mDhcpRange); 1233 } catch (Exception ee) { 1234 transitionTo(mStartTetheringErrorState); 1235 return false; 1236 } 1237 } 1238 try { 1239 mNMService.setDnsForwarders(mDefaultDnsServers); 1240 } catch (Exception e) { 1241 transitionTo(mSetDnsForwardersErrorState); 1242 return false; 1243 } 1244 return true; 1245 } 1246 protected boolean turnOffMasterTetherSettings() { 1247 try { 1248 mNMService.stopTethering(); 1249 } catch (Exception e) { 1250 transitionTo(mStopTetheringErrorState); 1251 return false; 1252 } 1253 try { 1254 mNMService.setIpForwardingEnabled(false); 1255 } catch (Exception e) { 1256 transitionTo(mSetIpForwardingDisabledErrorState); 1257 return false; 1258 } 1259 transitionTo(mInitialState); 1260 return true; 1261 } 1262 1263 protected void chooseUpstreamType(boolean tryCell) { 1264 int upType = ConnectivityManager.TYPE_NONE; 1265 String iface = null; 1266 1267 updateConfiguration(); // TODO - remove? 1268 1269 synchronized (mPublicSync) { 1270 if (VDBG) { 1271 Log.d(TAG, "chooseUpstreamType has upstream iface types:"); 1272 for (Integer netType : mUpstreamIfaceTypes) { 1273 Log.d(TAG, " " + netType); 1274 } 1275 } 1276 1277 for (Integer netType : mUpstreamIfaceTypes) { 1278 NetworkInfo info = 1279 getConnectivityManager().getNetworkInfo(netType.intValue()); 1280 if ((info != null) && info.isConnected()) { 1281 upType = netType.intValue(); 1282 break; 1283 } 1284 } 1285 } 1286 1287 if (DBG) { 1288 Log.d(TAG, "chooseUpstreamType(" + tryCell + "), preferredApn =" 1289 + mPreferredUpstreamMobileApn + ", got type=" + upType); 1290 } 1291 1292 // if we're on DUN, put our own grab on it 1293 if (upType == ConnectivityManager.TYPE_MOBILE_DUN || 1294 upType == ConnectivityManager.TYPE_MOBILE_HIPRI) { 1295 turnOnUpstreamMobileConnection(upType); 1296 } else if (upType != ConnectivityManager.TYPE_NONE) { 1297 /* If we've found an active upstream connection that's not DUN/HIPRI 1298 * we should stop any outstanding DUN/HIPRI start requests. 1299 * 1300 * If we found NONE we don't want to do this as we want any previous 1301 * requests to keep trying to bring up something we can use. 1302 */ 1303 turnOffUpstreamMobileConnection(); 1304 } 1305 1306 if (upType == ConnectivityManager.TYPE_NONE) { 1307 boolean tryAgainLater = true; 1308 if ((tryCell == TRY_TO_SETUP_MOBILE_CONNECTION) && 1309 (turnOnUpstreamMobileConnection(mPreferredUpstreamMobileApn) == true)) { 1310 // we think mobile should be coming up - don't set a retry 1311 tryAgainLater = false; 1312 } 1313 if (tryAgainLater) { 1314 sendMessageDelayed(CMD_RETRY_UPSTREAM, UPSTREAM_SETTLE_TIME_MS); 1315 } 1316 } else { 1317 LinkProperties linkProperties = 1318 getConnectivityManager().getLinkProperties(upType); 1319 if (linkProperties != null) { 1320 // Find the interface with the default IPv4 route. It may be the 1321 // interface described by linkProperties, or one of the interfaces 1322 // stacked on top of it. 1323 Log.i(TAG, "Finding IPv4 upstream interface on: " + linkProperties); 1324 RouteInfo ipv4Default = RouteInfo.selectBestRoute( 1325 linkProperties.getAllRoutes(), Inet4Address.ANY); 1326 if (ipv4Default != null) { 1327 iface = ipv4Default.getInterface(); 1328 Log.i(TAG, "Found interface " + ipv4Default.getInterface()); 1329 } else { 1330 Log.i(TAG, "No IPv4 upstream interface, giving up."); 1331 } 1332 } 1333 1334 if (iface != null) { 1335 String[] dnsServers = mDefaultDnsServers; 1336 Collection<InetAddress> dnses = linkProperties.getDnsServers(); 1337 if (dnses != null) { 1338 // we currently only handle IPv4 1339 ArrayList<InetAddress> v4Dnses = 1340 new ArrayList<InetAddress>(dnses.size()); 1341 for (InetAddress dnsAddress : dnses) { 1342 if (dnsAddress instanceof Inet4Address) { 1343 v4Dnses.add(dnsAddress); 1344 } 1345 } 1346 if (v4Dnses.size() > 0) { 1347 dnsServers = NetworkUtils.makeStrings(v4Dnses); 1348 } 1349 } 1350 try { 1351 mNMService.setDnsForwarders(dnsServers); 1352 } catch (Exception e) { 1353 transitionTo(mSetDnsForwardersErrorState); 1354 } 1355 } 1356 } 1357 notifyTetheredOfNewUpstreamIface(iface); 1358 } 1359 1360 protected void notifyTetheredOfNewUpstreamIface(String ifaceName) { 1361 if (DBG) Log.d(TAG, "notifying tethered with iface =" + ifaceName); 1362 mUpstreamIfaceName = ifaceName; 1363 for (TetherInterfaceSM sm : mNotifyList) { 1364 sm.sendMessage(TetherInterfaceSM.CMD_TETHER_CONNECTION_CHANGED, 1365 ifaceName); 1366 } 1367 } 1368 } 1369 1370 class InitialState extends TetherMasterUtilState { 1371 @Override 1372 public void enter() { 1373 } 1374 @Override 1375 public boolean processMessage(Message message) { 1376 if (DBG) Log.d(TAG, "MasterInitialState.processMessage what=" + message.what); 1377 boolean retValue = true; 1378 switch (message.what) { 1379 case CMD_TETHER_MODE_REQUESTED: 1380 TetherInterfaceSM who = (TetherInterfaceSM)message.obj; 1381 if (VDBG) Log.d(TAG, "Tether Mode requested by " + who); 1382 mNotifyList.add(who); 1383 transitionTo(mTetherModeAliveState); 1384 break; 1385 case CMD_TETHER_MODE_UNREQUESTED: 1386 who = (TetherInterfaceSM)message.obj; 1387 if (VDBG) Log.d(TAG, "Tether Mode unrequested by " + who); 1388 int index = mNotifyList.indexOf(who); 1389 if (index != -1) { 1390 mNotifyList.remove(who); 1391 } 1392 break; 1393 default: 1394 retValue = false; 1395 break; 1396 } 1397 return retValue; 1398 } 1399 } 1400 1401 class TetherModeAliveState extends TetherMasterUtilState { 1402 boolean mTryCell = !WAIT_FOR_NETWORK_TO_SETTLE; 1403 @Override 1404 public void enter() { 1405 turnOnMasterTetherSettings(); // may transition us out 1406 1407 mTryCell = !WAIT_FOR_NETWORK_TO_SETTLE; // better try something first pass 1408 // or crazy tests cases will fail 1409 chooseUpstreamType(mTryCell); 1410 mTryCell = !mTryCell; 1411 } 1412 @Override 1413 public void exit() { 1414 turnOffUpstreamMobileConnection(); 1415 notifyTetheredOfNewUpstreamIface(null); 1416 } 1417 @Override 1418 public boolean processMessage(Message message) { 1419 if (DBG) Log.d(TAG, "TetherModeAliveState.processMessage what=" + message.what); 1420 boolean retValue = true; 1421 switch (message.what) { 1422 case CMD_TETHER_MODE_REQUESTED: 1423 TetherInterfaceSM who = (TetherInterfaceSM)message.obj; 1424 if (VDBG) Log.d(TAG, "Tether Mode requested by " + who); 1425 mNotifyList.add(who); 1426 who.sendMessage(TetherInterfaceSM.CMD_TETHER_CONNECTION_CHANGED, 1427 mUpstreamIfaceName); 1428 break; 1429 case CMD_TETHER_MODE_UNREQUESTED: 1430 who = (TetherInterfaceSM)message.obj; 1431 if (VDBG) Log.d(TAG, "Tether Mode unrequested by " + who); 1432 int index = mNotifyList.indexOf(who); 1433 if (index != -1) { 1434 if (DBG) Log.d(TAG, "TetherModeAlive removing notifyee " + who); 1435 mNotifyList.remove(index); 1436 if (mNotifyList.isEmpty()) { 1437 turnOffMasterTetherSettings(); // transitions appropriately 1438 } else { 1439 if (DBG) { 1440 Log.d(TAG, "TetherModeAlive still has " + mNotifyList.size() + 1441 " live requests:"); 1442 for (Object o : mNotifyList) Log.d(TAG, " " + o); 1443 } 1444 } 1445 } else { 1446 Log.e(TAG, "TetherModeAliveState UNREQUESTED has unknown who: " + who); 1447 } 1448 break; 1449 case CMD_UPSTREAM_CHANGED: 1450 // need to try DUN immediately if Wifi goes down 1451 mTryCell = !WAIT_FOR_NETWORK_TO_SETTLE; 1452 chooseUpstreamType(mTryCell); 1453 mTryCell = !mTryCell; 1454 break; 1455 case CMD_CELL_CONNECTION_RENEW: 1456 // make sure we're still using a requested connection - may have found 1457 // wifi or something since then. 1458 if (mCurrentConnectionSequence == message.arg1) { 1459 if (VDBG) { 1460 Log.d(TAG, "renewing mobile connection - requeuing for another " + 1461 CELL_CONNECTION_RENEW_MS + "ms"); 1462 } 1463 turnOnUpstreamMobileConnection(mMobileApnReserved); 1464 } 1465 break; 1466 case CMD_RETRY_UPSTREAM: 1467 chooseUpstreamType(mTryCell); 1468 mTryCell = !mTryCell; 1469 break; 1470 default: 1471 retValue = false; 1472 break; 1473 } 1474 return retValue; 1475 } 1476 } 1477 1478 class ErrorState extends State { 1479 int mErrorNotification; 1480 @Override 1481 public boolean processMessage(Message message) { 1482 boolean retValue = true; 1483 switch (message.what) { 1484 case CMD_TETHER_MODE_REQUESTED: 1485 TetherInterfaceSM who = (TetherInterfaceSM)message.obj; 1486 who.sendMessage(mErrorNotification); 1487 break; 1488 default: 1489 retValue = false; 1490 } 1491 return retValue; 1492 } 1493 void notify(int msgType) { 1494 mErrorNotification = msgType; 1495 for (Object o : mNotifyList) { 1496 TetherInterfaceSM sm = (TetherInterfaceSM)o; 1497 sm.sendMessage(msgType); 1498 } 1499 } 1500 1501 } 1502 class SetIpForwardingEnabledErrorState extends ErrorState { 1503 @Override 1504 public void enter() { 1505 Log.e(TAG, "Error in setIpForwardingEnabled"); 1506 notify(TetherInterfaceSM.CMD_IP_FORWARDING_ENABLE_ERROR); 1507 } 1508 } 1509 1510 class SetIpForwardingDisabledErrorState extends ErrorState { 1511 @Override 1512 public void enter() { 1513 Log.e(TAG, "Error in setIpForwardingDisabled"); 1514 notify(TetherInterfaceSM.CMD_IP_FORWARDING_DISABLE_ERROR); 1515 } 1516 } 1517 1518 class StartTetheringErrorState extends ErrorState { 1519 @Override 1520 public void enter() { 1521 Log.e(TAG, "Error in startTethering"); 1522 notify(TetherInterfaceSM.CMD_START_TETHERING_ERROR); 1523 try { 1524 mNMService.setIpForwardingEnabled(false); 1525 } catch (Exception e) {} 1526 } 1527 } 1528 1529 class StopTetheringErrorState extends ErrorState { 1530 @Override 1531 public void enter() { 1532 Log.e(TAG, "Error in stopTethering"); 1533 notify(TetherInterfaceSM.CMD_STOP_TETHERING_ERROR); 1534 try { 1535 mNMService.setIpForwardingEnabled(false); 1536 } catch (Exception e) {} 1537 } 1538 } 1539 1540 class SetDnsForwardersErrorState extends ErrorState { 1541 @Override 1542 public void enter() { 1543 Log.e(TAG, "Error in setDnsForwarders"); 1544 notify(TetherInterfaceSM.CMD_SET_DNS_FORWARDERS_ERROR); 1545 try { 1546 mNMService.stopTethering(); 1547 } catch (Exception e) {} 1548 try { 1549 mNMService.setIpForwardingEnabled(false); 1550 } catch (Exception e) {} 1551 } 1552 } 1553 } 1554 1555 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1556 if (mContext.checkCallingOrSelfPermission( 1557 android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) { 1558 pw.println("Permission Denial: can't dump ConnectivityService.Tether " + 1559 "from from pid=" + Binder.getCallingPid() + ", uid=" + 1560 Binder.getCallingUid()); 1561 return; 1562 } 1563 1564 synchronized (mPublicSync) { 1565 pw.println("mUpstreamIfaceTypes: "); 1566 for (Integer netType : mUpstreamIfaceTypes) { 1567 pw.println(" " + netType); 1568 } 1569 1570 pw.println(); 1571 pw.println("Tether state:"); 1572 for (Object o : mIfaces.values()) { 1573 pw.println(" " + o); 1574 } 1575 } 1576 pw.println(); 1577 return; 1578 } 1579} 1580