blob: 35704d404ff32ff31bb5b734f9fd555692de7041 [file] [log] [blame]
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001/*
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
Erik Klinec438e302017-07-04 22:02:49 +090019import static android.hardware.usb.UsbManager.USB_CONFIGURED;
Erik Kline2e88b5e2017-01-18 11:57:45 +090020import static android.hardware.usb.UsbManager.USB_CONNECTED;
21import static android.hardware.usb.UsbManager.USB_FUNCTION_RNDIS;
Erik Kline7a26ba32018-03-09 14:18:02 +090022import static android.net.ConnectivityManager.ACTION_TETHER_STATE_CHANGED;
23import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
24import static android.net.ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY;
25import static android.net.ConnectivityManager.EXTRA_ACTIVE_TETHER;
Erik Kline7a26ba32018-03-09 14:18:02 +090026import static android.net.ConnectivityManager.EXTRA_AVAILABLE_TETHER;
27import static android.net.ConnectivityManager.EXTRA_ERRORED_TETHER;
28import static android.net.ConnectivityManager.EXTRA_NETWORK_INFO;
Erik Kline7a26ba32018-03-09 14:18:02 +090029import static android.net.ConnectivityManager.TETHERING_BLUETOOTH;
30import static android.net.ConnectivityManager.TETHERING_INVALID;
31import static android.net.ConnectivityManager.TETHERING_USB;
32import static android.net.ConnectivityManager.TETHERING_WIFI;
markchienb6eb2c22018-07-18 14:29:20 +080033import static android.net.ConnectivityManager.TETHER_ERROR_MASTER_ERROR;
34import static android.net.ConnectivityManager.TETHER_ERROR_NO_ERROR;
35import static android.net.ConnectivityManager.TETHER_ERROR_SERVICE_UNAVAIL;
36import static android.net.ConnectivityManager.TETHER_ERROR_UNAVAIL_IFACE;
37import static android.net.ConnectivityManager.TETHER_ERROR_UNKNOWN_IFACE;
Erik Kline2efb8272017-05-31 15:53:53 +090038import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_INTERFACE_NAME;
39import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_MODE;
Erik Kline2e88b5e2017-01-18 11:57:45 +090040import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_STATE;
Erik Kline2efb8272017-05-31 15:53:53 +090041import static android.net.wifi.WifiManager.IFACE_IP_MODE_CONFIGURATION_ERROR;
42import static android.net.wifi.WifiManager.IFACE_IP_MODE_LOCAL_ONLY;
43import static android.net.wifi.WifiManager.IFACE_IP_MODE_TETHERED;
44import static android.net.wifi.WifiManager.IFACE_IP_MODE_UNSPECIFIED;
Erik Kline2e88b5e2017-01-18 11:57:45 +090045import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLED;
Erik Klinede637722017-10-12 22:16:01 +090046import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
markchienb6eb2c22018-07-18 14:29:20 +080047
Erik Kline7747fd42017-05-12 16:52:48 +090048import static com.android.server.ConnectivityService.SHORT_ARG;
Erik Kline2e88b5e2017-01-18 11:57:45 +090049
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080050import android.app.Notification;
51import android.app.NotificationManager;
52import android.app.PendingIntent;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080053import android.bluetooth.BluetoothAdapter;
54import android.bluetooth.BluetoothPan;
55import android.bluetooth.BluetoothProfile;
56import android.bluetooth.BluetoothProfile.ServiceListener;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080057import android.content.BroadcastReceiver;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080058import android.content.Context;
59import android.content.Intent;
60import android.content.IntentFilter;
61import android.content.res.Resources;
Mike Lockwoodc4308f02011-03-01 08:04:54 -080062import android.hardware.usb.UsbManager;
Christopher Wileydeebfec2016-09-16 11:14:36 -070063import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070064import android.net.INetworkStatsService;
markchien6ea34542019-02-27 14:56:11 +080065import android.net.ITetheringEventCallback;
Erik Kline3a5278f2017-06-24 19:29:10 +090066import android.net.IpPrefix;
Erik Klineed962a82017-07-06 19:49:35 +090067import android.net.LinkAddress;
Robert Greenwalt05d89362011-01-23 16:04:05 -080068import android.net.LinkProperties;
Lorenzo Colittib57edc52014-08-22 17:10:50 -070069import android.net.Network;
Robert Greenwalt2a091d72010-02-11 18:18:40 -080070import android.net.NetworkInfo;
Erik Kline6ff17f72015-12-10 20:42:12 +090071import android.net.NetworkState;
Robert Greenwalte5903732011-02-22 16:00:42 -080072import android.net.NetworkUtils;
markchienb6eb2c22018-07-18 14:29:20 +080073import android.net.ip.IpServer;
Remi NGUYEN VAN6c02f992018-03-09 14:07:18 +090074import android.net.util.InterfaceSet;
Erik Kline32179ff2017-07-04 18:28:11 +090075import android.net.util.PrefixUtils;
Erik Kline7747fd42017-05-12 16:52:48 +090076import android.net.util.SharedLog;
Erik Klinede637722017-10-12 22:16:01 +090077import android.net.util.VersionedBroadcastListener;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080078import android.net.wifi.WifiManager;
Robert Greenwalt2a091d72010-02-11 18:18:40 -080079import android.os.Binder;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080080import android.os.Bundle;
Erik Klinef4b6e342017-04-25 19:19:59 +090081import android.os.Handler;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080082import android.os.INetworkManagementService;
Robert Greenwaltdfadaea2010-03-11 15:03:08 -080083import android.os.Looper;
Robert Greenwalt2a091d72010-02-11 18:18:40 -080084import android.os.Message;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080085import android.os.Parcel;
markchien6ea34542019-02-27 14:56:11 +080086import android.os.RemoteCallbackList;
Christopher Wileydeebfec2016-09-16 11:14:36 -070087import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080088import android.os.ResultReceiver;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070089import android.os.UserHandle;
Alexandru-Andrei Rotarufa6d5c52017-07-18 16:49:22 +010090import android.os.UserManager;
91import android.os.UserManagerInternal;
92import android.os.UserManagerInternal.UserRestrictionsListener;
Lorenzo Colitticd63d242016-04-10 15:39:53 +090093import android.text.TextUtils;
Christopher Wileye9490392016-05-26 15:57:29 -070094import android.util.ArrayMap;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080095import android.util.Log;
Lorenzo Colitticd63d242016-04-10 15:39:53 +090096import android.util.SparseArray;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080097
Christopher Wiley497c1472016-10-11 13:26:03 -070098import com.android.internal.annotations.VisibleForTesting;
Chris Wren282cfef2017-03-27 15:01:44 -040099import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500100import com.android.internal.notification.SystemNotificationChannels;
markchien0b595072019-01-08 23:52:21 +0800101import com.android.internal.telephony.TelephonyIntents;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600102import com.android.internal.util.DumpUtils;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800103import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitticd63d242016-04-10 15:39:53 +0900104import com.android.internal.util.MessageUtils;
105import com.android.internal.util.Protocol;
Wink Saville64c42ca2011-04-18 14:55:10 -0700106import com.android.internal.util.State;
107import com.android.internal.util.StateMachine;
Alexandru-Andrei Rotarufa6d5c52017-07-18 16:49:22 +0100108import com.android.server.LocalServices;
markchienb6eb2c22018-07-18 14:29:20 +0800109import com.android.server.connectivity.tethering.EntitlementManager;
Erik Kline1eb8c692016-07-08 17:21:26 +0900110import com.android.server.connectivity.tethering.IPv6TetheringCoordinator;
Erik Klinee0cce212017-03-06 14:05:23 +0900111import com.android.server.connectivity.tethering.OffloadController;
Hugo Benichib55fb222017-03-10 14:20:57 +0900112import com.android.server.connectivity.tethering.TetheringConfiguration;
Erik Kline47222fc2017-04-30 19:36:15 +0900113import com.android.server.connectivity.tethering.TetheringDependencies;
Remi NGUYEN VAN6c02f992018-03-09 14:07:18 +0900114import com.android.server.connectivity.tethering.TetheringInterfaceUtils;
Erik Kline9bba3402017-01-13 16:46:52 +0900115import com.android.server.connectivity.tethering.UpstreamNetworkMonitor;
Lorenzo Colittif4e90ea2013-10-31 23:30:47 +0900116import com.android.server.net.BaseNetworkObserver;
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800117
118import java.io.FileDescriptor;
119import java.io.PrintWriter;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800120import java.net.InetAddress;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800121import java.util.ArrayList;
Lorenzo Colittib57edc52014-08-22 17:10:50 -0700122import java.util.Arrays;
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700123import java.util.Collection;
Erik Klineea9cc482017-03-10 19:35:34 +0900124import java.util.HashSet;
Erik Kline3a5278f2017-06-24 19:29:10 +0900125import java.util.Set;
Robert Greenwalt2ffe4122014-12-12 12:22:31 -0800126
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800127/**
128 * @hide
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800129 *
Christopher Wiley3b1d9222016-05-20 16:44:04 -0700130 * This class holds much of the business logic to allow Android devices
131 * to act as IP gateways via USB, BT, and WiFi interfaces.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800132 */
Erik Kline6e9a1012017-06-06 19:24:21 +0900133public class Tethering extends BaseNetworkObserver {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800134
Hugo Benichib55fb222017-03-10 14:20:57 +0900135 private final static String TAG = Tethering.class.getSimpleName();
Joe Onorato12acbd72016-02-01 17:49:31 -0800136 private final static boolean DBG = false;
Robert Greenwaltfd1be2b2011-11-11 12:30:19 -0800137 private final static boolean VDBG = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800138
Lorenzo Colitticd63d242016-04-10 15:39:53 +0900139 private static final Class[] messageClasses = {
Erik Kline7a4ccc62018-08-27 17:26:47 +0900140 Tethering.class, TetherMasterSM.class, IpServer.class
Lorenzo Colitticd63d242016-04-10 15:39:53 +0900141 };
142 private static final SparseArray<String> sMagicDecoderRing =
143 MessageUtils.findMessageNames(messageClasses);
144
Hugo Benichib55fb222017-03-10 14:20:57 +0900145 private static class TetherState {
Erik Kline7a4ccc62018-08-27 17:26:47 +0900146 public final IpServer ipServer;
Hugo Benichib55fb222017-03-10 14:20:57 +0900147 public int lastState;
148 public int lastError;
Erik Klineea9cc482017-03-10 19:35:34 +0900149
Erik Kline7a4ccc62018-08-27 17:26:47 +0900150 public TetherState(IpServer ipServer) {
151 this.ipServer = ipServer;
Hugo Benichib55fb222017-03-10 14:20:57 +0900152 // Assume all state machines start out available and with no errors.
Erik Kline7a4ccc62018-08-27 17:26:47 +0900153 lastState = IpServer.STATE_AVAILABLE;
Erik Kline7a26ba32018-03-09 14:18:02 +0900154 lastError = TETHER_ERROR_NO_ERROR;
Hugo Benichib55fb222017-03-10 14:20:57 +0900155 }
Erik Klineea9cc482017-03-10 19:35:34 +0900156
157 public boolean isCurrentlyServing() {
158 switch (lastState) {
Erik Kline7a4ccc62018-08-27 17:26:47 +0900159 case IpServer.STATE_TETHERED:
160 case IpServer.STATE_LOCAL_ONLY:
Erik Klineea9cc482017-03-10 19:35:34 +0900161 return true;
162 default:
163 return false;
164 }
165 }
Hugo Benichib55fb222017-03-10 14:20:57 +0900166 }
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700167
Erik Kline7747fd42017-05-12 16:52:48 +0900168 private final SharedLog mLog = new SharedLog(TAG);
Erik Kline1fdc2e22017-05-08 17:56:35 +0900169
Robert Greenwaltb4453622011-11-03 16:01:40 -0700170 // used to synchronize public access to members
Erik Kline6ff17f72015-12-10 20:42:12 +0900171 private final Object mPublicSync;
Hugo Benichib55fb222017-03-10 14:20:57 +0900172 private final Context mContext;
173 private final ArrayMap<String, TetherState> mTetherStates;
174 private final BroadcastReceiver mStateReceiver;
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700175 private final INetworkManagementService mNMService;
176 private final INetworkStatsService mStatsService;
Christopher Wileydeebfec2016-09-16 11:14:36 -0700177 private final INetworkPolicyManager mPolicyManager;
Erik Kline6ff17f72015-12-10 20:42:12 +0900178 private final Looper mLooper;
Erik Kline6ff17f72015-12-10 20:42:12 +0900179 private final StateMachine mTetherMasterSM;
Erik Klinee0cce212017-03-06 14:05:23 +0900180 private final OffloadController mOffloadController;
Erik Kline6ff17f72015-12-10 20:42:12 +0900181 private final UpstreamNetworkMonitor mUpstreamNetworkMonitor;
Erik Kline6e9a1012017-06-06 19:24:21 +0900182 // TODO: Figure out how to merge this and other downstream-tracking objects
183 // into a single coherent structure.
Erik Kline7a4ccc62018-08-27 17:26:47 +0900184 private final HashSet<IpServer> mForwardedDownstreams;
Erik Klinede637722017-10-12 22:16:01 +0900185 private final VersionedBroadcastListener mCarrierConfigChange;
markchien0b595072019-01-08 23:52:21 +0800186 private final VersionedBroadcastListener mDefaultSubscriptionChange;
Remi NGUYEN VAN5d0dc452018-03-15 11:57:14 +0900187 private final TetheringDependencies mDeps;
markchienb6eb2c22018-07-18 14:29:20 +0800188 private final EntitlementManager mEntitlementMgr;
markchien6ea34542019-02-27 14:56:11 +0800189 private final Handler mHandler;
190 private final RemoteCallbackList<ITetheringEventCallback> mTetheringEventCallbacks =
191 new RemoteCallbackList<>();
Robert Greenwalta599fe7c2010-03-08 18:30:14 -0800192
Hugo Benichib55fb222017-03-10 14:20:57 +0900193 private volatile TetheringConfiguration mConfig;
Remi NGUYEN VAN6c02f992018-03-09 14:07:18 +0900194 private InterfaceSet mCurrentUpstreamIfaceSet;
Chris Wren1ce4b6d2015-06-11 10:19:43 -0400195 private Notification.Builder mTetheredNotificationBuilder;
196 private int mLastNotificationId;
Erik Klineea9cc482017-03-10 19:35:34 +0900197
Mike Lockwood6c2260b2011-07-19 13:04:47 -0700198 private boolean mRndisEnabled; // track the RNDIS function enabled state
Erik Kline6e9a1012017-06-06 19:24:21 +0900199 // True iff. WiFi tethering should be started when soft AP is ready.
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700200 private boolean mWifiTetherRequested;
markchien6ea34542019-02-27 14:56:11 +0800201 private Network mTetherUpstream;
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700202
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700203 public Tethering(Context context, INetworkManagementService nmService,
Christopher Wiley497c1472016-10-11 13:26:03 -0700204 INetworkStatsService statsService, INetworkPolicyManager policyManager,
Erik Kline47222fc2017-04-30 19:36:15 +0900205 Looper looper, MockableSystemProperties systemProperties,
206 TetheringDependencies deps) {
Erik Kline7747fd42017-05-12 16:52:48 +0900207 mLog.mark("constructed");
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800208 mContext = context;
Chia-chi Yehc9338302011-05-11 16:35:13 -0700209 mNMService = nmService;
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700210 mStatsService = statsService;
Christopher Wileydeebfec2016-09-16 11:14:36 -0700211 mPolicyManager = policyManager;
Christopher Wiley497c1472016-10-11 13:26:03 -0700212 mLooper = looper;
Remi NGUYEN VAN5d0dc452018-03-15 11:57:14 +0900213 mDeps = deps;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800214
Robert Greenwaltb4453622011-11-03 16:01:40 -0700215 mPublicSync = new Object();
216
Christopher Wileyd985dde2016-05-31 10:44:35 -0700217 mTetherStates = new ArrayMap<>();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800218
Remi NGUYEN VAN5d0dc452018-03-15 11:57:14 +0900219 mTetherMasterSM = new TetherMasterSM("TetherMaster", mLooper, deps);
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800220 mTetherMasterSM.start();
221
markchien6ea34542019-02-27 14:56:11 +0800222 mHandler = mTetherMasterSM.getHandler();
223 mOffloadController = new OffloadController(mHandler,
224 mDeps.getOffloadHardwareInterface(mHandler, mLog),
Lorenzo Colitti5a7dea12017-07-12 15:48:07 +0900225 mContext.getContentResolver(), mNMService,
Erik Klinef4b6e342017-04-25 19:19:59 +0900226 mLog);
Remi NGUYEN VAN5d0dc452018-03-15 11:57:14 +0900227 mUpstreamNetworkMonitor = deps.getUpstreamNetworkMonitor(mContext, mTetherMasterSM, mLog,
228 TetherMasterSM.EVENT_UPSTREAM_CALLBACK);
Erik Klineea9cc482017-03-10 19:35:34 +0900229 mForwardedDownstreams = new HashSet<>();
Erik Klinede637722017-10-12 22:16:01 +0900230
231 IntentFilter filter = new IntentFilter();
232 filter.addAction(ACTION_CARRIER_CONFIG_CHANGED);
markchienf2731272019-01-16 17:44:13 +0800233 mEntitlementMgr = mDeps.getEntitlementManager(mContext, mTetherMasterSM,
234 mLog, systemProperties);
Erik Klinede637722017-10-12 22:16:01 +0900235 mCarrierConfigChange = new VersionedBroadcastListener(
markchien6ea34542019-02-27 14:56:11 +0800236 "CarrierConfigChangeListener", mContext, mHandler, filter,
Erik Klinede637722017-10-12 22:16:01 +0900237 (Intent ignored) -> {
238 mLog.log("OBSERVED carrier config change");
Erik Kline80b7a9f2018-02-28 15:01:35 +0900239 updateConfiguration();
markchienb6eb2c22018-07-18 14:29:20 +0800240 mEntitlementMgr.reevaluateSimCardProvisioning();
Erik Klinede637722017-10-12 22:16:01 +0900241 });
Erik Kline6ff17f72015-12-10 20:42:12 +0900242
markchien0b595072019-01-08 23:52:21 +0800243 filter = new IntentFilter();
244 filter.addAction(TelephonyIntents.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED);
245 mDefaultSubscriptionChange = new VersionedBroadcastListener(
markchien6ea34542019-02-27 14:56:11 +0800246 "DefaultSubscriptionChangeListener", mContext, mHandler, filter,
markchien0b595072019-01-08 23:52:21 +0800247 (Intent ignored) -> {
248 mLog.log("OBSERVED default data subscription change");
249 updateConfiguration();
250 mEntitlementMgr.reevaluateSimCardProvisioning();
251 });
Robert Greenwaltbb51d9f2010-03-12 10:23:35 -0800252 mStateReceiver = new StateReceiver();
Erik Kline80b7a9f2018-02-28 15:01:35 +0900253
254 // Load tethering configuration.
255 updateConfiguration();
256
markchien6ea34542019-02-27 14:56:11 +0800257 startStateMachineUpdaters(mHandler);
Erik Kline80b7a9f2018-02-28 15:01:35 +0900258 }
259
markchien6ea34542019-02-27 14:56:11 +0800260 private void startStateMachineUpdaters(Handler handler) {
Erik Kline80b7a9f2018-02-28 15:01:35 +0900261 mCarrierConfigChange.startListening();
markchien0b595072019-01-08 23:52:21 +0800262 mDefaultSubscriptionChange.startListening();
Erik Kline80b7a9f2018-02-28 15:01:35 +0900263
Erik Kline80b7a9f2018-02-28 15:01:35 +0900264 IntentFilter filter = new IntentFilter();
Mike Lockwood770126a2010-12-09 22:30:37 -0800265 filter.addAction(UsbManager.ACTION_USB_STATE);
Erik Kline7a26ba32018-03-09 14:18:02 +0900266 filter.addAction(CONNECTIVITY_ACTION);
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700267 filter.addAction(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
Robert Greenwaltc13368b2013-07-18 14:24:42 -0700268 filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
Erik Kline80b7a9f2018-02-28 15:01:35 +0900269 mContext.registerReceiver(mStateReceiver, filter, null, handler);
Robert Greenwaltbb51d9f2010-03-12 10:23:35 -0800270
271 filter = new IntentFilter();
Robert Greenwalt030f5e12010-03-10 16:41:03 -0800272 filter.addAction(Intent.ACTION_MEDIA_SHARED);
273 filter.addAction(Intent.ACTION_MEDIA_UNSHARED);
Robert Greenwaltbb51d9f2010-03-12 10:23:35 -0800274 filter.addDataScheme("file");
Erik Kline80b7a9f2018-02-28 15:01:35 +0900275 mContext.registerReceiver(mStateReceiver, filter, null, handler);
Robert Greenwaltbb51d9f2010-03-12 10:23:35 -0800276
Erik Kline80b7a9f2018-02-28 15:01:35 +0900277 final UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
278 // This check is useful only for some unit tests; example: ConnectivityServiceTest.
279 if (umi != null) {
280 umi.addUserRestrictionsListener(new TetheringUserRestrictionListener(this));
Alexandru-Andrei Rotarufa6d5c52017-07-18 16:49:22 +0100281 }
Robert Greenwalt49348e72011-10-21 16:54:26 -0700282 }
283
Erik Kline216af6d2017-04-27 20:57:23 +0900284 private WifiManager getWifiManager() {
285 return (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
286 }
287
Erik Kline93c4afa2017-06-04 11:36:01 +0900288 // NOTE: This is always invoked on the mLooper thread.
Erik Klined781fba2017-01-23 13:01:58 +0900289 private void updateConfiguration() {
markchien0b595072019-01-08 23:52:21 +0800290 final int subId = mDeps.getDefaultDataSubscriptionId();
291 mConfig = new TetheringConfiguration(mContext, mLog, subId);
Erik Kline93c4afa2017-06-04 11:36:01 +0900292 mUpstreamNetworkMonitor.updateMobileRequiresDun(mConfig.isDunRequired);
markchienb6eb2c22018-07-18 14:29:20 +0800293 mEntitlementMgr.updateConfiguration(mConfig);
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800294 }
295
Erik Kline6ee73da2017-07-08 20:36:37 +0900296 private void maybeUpdateConfiguration() {
markchiendb3a2362018-10-05 12:36:08 +0800297 final boolean isDunRequired = TetheringConfiguration.checkDunRequired(mContext);
298 if (isDunRequired == mConfig.isDunRequired) return;
Erik Kline6ee73da2017-07-08 20:36:37 +0900299 updateConfiguration();
300 }
301
Erik Kline0c9cb2b2015-11-20 17:47:08 +0900302 @Override
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700303 public void interfaceStatusChanged(String iface, boolean up) {
Lorenzo Colitticd63d242016-04-10 15:39:53 +0900304 // Never called directly: only called from interfaceLinkStateChanged.
305 // See NetlinkHandler.cpp:71.
Wink Savillec9acde92011-09-21 11:05:43 -0700306 if (VDBG) Log.d(TAG, "interfaceStatusChanged " + iface + ", " + up);
Robert Greenwaltb4453622011-11-03 16:01:40 -0700307 synchronized (mPublicSync) {
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700308 if (up) {
Erik Kline4dd9bb82017-04-26 11:11:07 +0900309 maybeTrackNewInterfaceLocked(iface);
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800310 } else {
Erik Kline7a26ba32018-03-09 14:18:02 +0900311 if (ifaceNameToType(iface) == TETHERING_BLUETOOTH) {
Erik Kline4dd9bb82017-04-26 11:11:07 +0900312 stopTrackingInterfaceLocked(iface);
Christopher Wileyd30aaeb2016-07-08 09:33:50 -0700313 } else {
314 // Ignore usb0 down after enabling RNDIS.
315 // We will handle disconnect in interfaceRemoved.
316 // Similarly, ignore interface down for WiFi. We monitor WiFi AP status
317 // through the WifiManager.WIFI_AP_STATE_CHANGED_ACTION intent.
318 if (VDBG) Log.d(TAG, "ignore interface down for " + iface);
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800319 }
320 }
321 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800322 }
323
Erik Kline0c9cb2b2015-11-20 17:47:08 +0900324 @Override
Mike J. Chenf59c7d02011-06-23 15:33:15 -0700325 public void interfaceLinkStateChanged(String iface, boolean up) {
Irfan Sheriff23eb2972011-07-22 15:21:10 -0700326 interfaceStatusChanged(iface, up);
Mike J. Chenf59c7d02011-06-23 15:33:15 -0700327 }
328
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700329 private int ifaceNameToType(String iface) {
Erik Kline3e756652017-01-17 13:42:19 +0900330 final TetheringConfiguration cfg = mConfig;
331
332 if (cfg.isWifi(iface)) {
Erik Kline7a26ba32018-03-09 14:18:02 +0900333 return TETHERING_WIFI;
Erik Kline3e756652017-01-17 13:42:19 +0900334 } else if (cfg.isUsb(iface)) {
Erik Kline7a26ba32018-03-09 14:18:02 +0900335 return TETHERING_USB;
Erik Kline3e756652017-01-17 13:42:19 +0900336 } else if (cfg.isBluetooth(iface)) {
Erik Kline7a26ba32018-03-09 14:18:02 +0900337 return TETHERING_BLUETOOTH;
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700338 }
Erik Kline7a26ba32018-03-09 14:18:02 +0900339 return TETHERING_INVALID;
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700340 }
341
Erik Kline0c9cb2b2015-11-20 17:47:08 +0900342 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800343 public void interfaceAdded(String iface) {
Wink Savillec9acde92011-09-21 11:05:43 -0700344 if (VDBG) Log.d(TAG, "interfaceAdded " + iface);
Robert Greenwaltb4453622011-11-03 16:01:40 -0700345 synchronized (mPublicSync) {
Erik Kline4dd9bb82017-04-26 11:11:07 +0900346 maybeTrackNewInterfaceLocked(iface);
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800347 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800348 }
349
Erik Kline0c9cb2b2015-11-20 17:47:08 +0900350 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800351 public void interfaceRemoved(String iface) {
Wink Savillec9acde92011-09-21 11:05:43 -0700352 if (VDBG) Log.d(TAG, "interfaceRemoved " + iface);
Robert Greenwaltb4453622011-11-03 16:01:40 -0700353 synchronized (mPublicSync) {
Erik Kline4dd9bb82017-04-26 11:11:07 +0900354 stopTrackingInterfaceLocked(iface);
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800355 }
356 }
357
Hugo Benichib55fb222017-03-10 14:20:57 +0900358 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi) {
markchienb6eb2c22018-07-18 14:29:20 +0800359 mEntitlementMgr.startTethering(type);
360 if (!mEntitlementMgr.isTetherProvisioningRequired()) {
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800361 enableTetheringInternal(type, true, receiver);
362 return;
363 }
364
markchienb6eb2c22018-07-18 14:29:20 +0800365 final ResultReceiver proxyReceiver = getProxyReceiver(type, receiver);
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800366 if (showProvisioningUi) {
markchienb6eb2c22018-07-18 14:29:20 +0800367 mEntitlementMgr.runUiTetherProvisioningAndEnable(type, proxyReceiver);
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800368 } else {
markchienb6eb2c22018-07-18 14:29:20 +0800369 mEntitlementMgr.runSilentTetherProvisioningAndEnable(type, proxyReceiver);
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800370 }
371 }
372
373 public void stopTethering(int type) {
374 enableTetheringInternal(type, false, null);
markchienb6eb2c22018-07-18 14:29:20 +0800375 mEntitlementMgr.stopTethering(type);
376 if (mEntitlementMgr.isTetherProvisioningRequired()) {
377 // There are lurking bugs where the notion of "provisioning required" or
378 // "tethering supported" may change without notifying tethering properly, then
379 // tethering can't shutdown correctly.
380 // TODO: cancel re-check all the time
381 if (mDeps.isTetheringSupported()) {
382 mEntitlementMgr.cancelTetherProvisioningRechecks(type);
383 }
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800384 }
385 }
386
387 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800388 * Enables or disables tethering for the given type. This should only be called once
389 * provisioning has succeeded or is not necessary. It will also schedule provisioning rechecks
390 * for the specified interface.
391 */
392 private void enableTetheringInternal(int type, boolean enable, ResultReceiver receiver) {
markchienb6eb2c22018-07-18 14:29:20 +0800393 boolean isProvisioningRequired = enable && mEntitlementMgr.isTetherProvisioningRequired();
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700394 int result;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800395 switch (type) {
Erik Kline7a26ba32018-03-09 14:18:02 +0900396 case TETHERING_WIFI:
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700397 result = setWifiTethering(enable);
Erik Kline7a26ba32018-03-09 14:18:02 +0900398 if (isProvisioningRequired && result == TETHER_ERROR_NO_ERROR) {
markchienb6eb2c22018-07-18 14:29:20 +0800399 mEntitlementMgr.scheduleProvisioningRechecks(type);
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800400 }
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700401 sendTetherResult(receiver, result);
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800402 break;
Erik Kline7a26ba32018-03-09 14:18:02 +0900403 case TETHERING_USB:
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700404 result = setUsbTethering(enable);
Erik Kline7a26ba32018-03-09 14:18:02 +0900405 if (isProvisioningRequired && result == TETHER_ERROR_NO_ERROR) {
markchienb6eb2c22018-07-18 14:29:20 +0800406 mEntitlementMgr.scheduleProvisioningRechecks(type);
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800407 }
408 sendTetherResult(receiver, result);
409 break;
Erik Kline7a26ba32018-03-09 14:18:02 +0900410 case TETHERING_BLUETOOTH:
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800411 setBluetoothTethering(enable, receiver);
412 break;
413 default:
414 Log.w(TAG, "Invalid tether type.");
Erik Kline7a26ba32018-03-09 14:18:02 +0900415 sendTetherResult(receiver, TETHER_ERROR_UNKNOWN_IFACE);
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800416 }
417 }
418
419 private void sendTetherResult(ResultReceiver receiver, int result) {
420 if (receiver != null) {
421 receiver.send(result, null);
422 }
423 }
424
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700425 private int setWifiTethering(final boolean enable) {
Erik Kline7a26ba32018-03-09 14:18:02 +0900426 int rval = TETHER_ERROR_MASTER_ERROR;
Erik Kline256be782017-04-29 13:20:04 +0900427 final long ident = Binder.clearCallingIdentity();
428 try {
429 synchronized (mPublicSync) {
430 mWifiTetherRequested = enable;
431 final WifiManager mgr = getWifiManager();
432 if ((enable && mgr.startSoftAp(null /* use existing wifi config */)) ||
433 (!enable && mgr.stopSoftAp())) {
Erik Kline7a26ba32018-03-09 14:18:02 +0900434 rval = TETHER_ERROR_NO_ERROR;
Erik Kline256be782017-04-29 13:20:04 +0900435 }
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700436 }
Erik Kline256be782017-04-29 13:20:04 +0900437 } finally {
438 Binder.restoreCallingIdentity(ident);
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700439 }
Erik Kline256be782017-04-29 13:20:04 +0900440 return rval;
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700441 }
442
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800443 private void setBluetoothTethering(final boolean enable, final ResultReceiver receiver) {
444 final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
445 if (adapter == null || !adapter.isEnabled()) {
446 Log.w(TAG, "Tried to enable bluetooth tethering with null or disabled adapter. null: " +
447 (adapter == null));
Erik Kline7a26ba32018-03-09 14:18:02 +0900448 sendTetherResult(receiver, TETHER_ERROR_SERVICE_UNAVAIL);
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800449 return;
450 }
451
452 adapter.getProfileProxy(mContext, new ServiceListener() {
453 @Override
454 public void onServiceDisconnected(int profile) { }
455
456 @Override
457 public void onServiceConnected(int profile, BluetoothProfile proxy) {
458 ((BluetoothPan) proxy).setBluetoothTethering(enable);
459 // TODO: Enabling bluetooth tethering can fail asynchronously here.
460 // We should figure out a way to bubble up that failure instead of sending success.
Erik Kline7a26ba32018-03-09 14:18:02 +0900461 final int result = (((BluetoothPan) proxy).isTetheringOn() == enable)
462 ? TETHER_ERROR_NO_ERROR
463 : TETHER_ERROR_MASTER_ERROR;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800464 sendTetherResult(receiver, result);
markchienb6eb2c22018-07-18 14:29:20 +0800465 if (enable && mEntitlementMgr.isTetherProvisioningRequired()) {
466 mEntitlementMgr.scheduleProvisioningRechecks(TETHERING_BLUETOOTH);
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800467 }
468 adapter.closeProfileProxy(BluetoothProfile.PAN, proxy);
469 }
470 }, BluetoothProfile.PAN);
471 }
472
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800473 /**
Erik Klinefdd41112017-01-12 17:02:51 +0900474 * Creates a proxy {@link ResultReceiver} which enables tethering if the provisioning result
475 * is successful before firing back up to the wrapped receiver.
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800476 *
477 * @param type The type of tethering being enabled.
478 * @param receiver A ResultReceiver which will be called back with an int resultCode.
479 * @return The proxy receiver.
480 */
481 private ResultReceiver getProxyReceiver(final int type, final ResultReceiver receiver) {
482 ResultReceiver rr = new ResultReceiver(null) {
483 @Override
484 protected void onReceiveResult(int resultCode, Bundle resultData) {
485 // If provisioning is successful, enable tethering, otherwise just send the error.
Erik Kline7a26ba32018-03-09 14:18:02 +0900486 if (resultCode == TETHER_ERROR_NO_ERROR) {
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800487 enableTetheringInternal(type, true, receiver);
488 } else {
489 sendTetherResult(receiver, resultCode);
490 }
markchienf2731272019-01-16 17:44:13 +0800491 mEntitlementMgr.updateEntitlementCacheValue(type, resultCode);
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800492 }
493 };
494
495 // The following is necessary to avoid unmarshalling issues when sending the receiver
Erik Kline6ff17f72015-12-10 20:42:12 +0900496 // across processes.
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800497 Parcel parcel = Parcel.obtain();
498 rr.writeToParcel(parcel,0);
499 parcel.setDataPosition(0);
500 ResultReceiver receiverForSending = ResultReceiver.CREATOR.createFromParcel(parcel);
501 parcel.recycle();
502 return receiverForSending;
503 }
504
Robert Greenwalt5a735062010-03-02 17:25:02 -0800505 public int tether(String iface) {
Erik Kline7a4ccc62018-08-27 17:26:47 +0900506 return tether(iface, IpServer.STATE_TETHERED);
Erik Klineea9cc482017-03-10 19:35:34 +0900507 }
508
509 private int tether(String iface, int requestedState) {
Wink Savillec9acde92011-09-21 11:05:43 -0700510 if (DBG) Log.d(TAG, "Tethering " + iface);
Robert Greenwaltb4453622011-11-03 16:01:40 -0700511 synchronized (mPublicSync) {
Christopher Wileyd985dde2016-05-31 10:44:35 -0700512 TetherState tetherState = mTetherStates.get(iface);
513 if (tetherState == null) {
Erik Kline00019f42016-06-30 19:31:46 +0900514 Log.e(TAG, "Tried to Tether an unknown iface: " + iface + ", ignoring");
Erik Kline7a26ba32018-03-09 14:18:02 +0900515 return TETHER_ERROR_UNKNOWN_IFACE;
Christopher Wiley4312a4c2016-05-23 13:58:00 -0700516 }
517 // Ignore the error status of the interface. If the interface is available,
518 // the errors are referring to past tethering attempts anyway.
Erik Kline7a4ccc62018-08-27 17:26:47 +0900519 if (tetherState.lastState != IpServer.STATE_AVAILABLE) {
Erik Kline00019f42016-06-30 19:31:46 +0900520 Log.e(TAG, "Tried to Tether an unavailable iface: " + iface + ", ignoring");
Erik Kline7a26ba32018-03-09 14:18:02 +0900521 return TETHER_ERROR_UNAVAIL_IFACE;
Christopher Wiley4312a4c2016-05-23 13:58:00 -0700522 }
Erik Klineea9cc482017-03-10 19:35:34 +0900523 // NOTE: If a CMD_TETHER_REQUESTED message is already in the TISM's
524 // queue but not yet processed, this will be a no-op and it will not
525 // return an error.
526 //
527 // TODO: reexamine the threading and messaging model.
Erik Kline7a4ccc62018-08-27 17:26:47 +0900528 tetherState.ipServer.sendMessage(IpServer.CMD_TETHER_REQUESTED, requestedState);
Erik Kline7a26ba32018-03-09 14:18:02 +0900529 return TETHER_ERROR_NO_ERROR;
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800530 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800531 }
532
Robert Greenwalt5a735062010-03-02 17:25:02 -0800533 public int untether(String iface) {
Wink Savillec9acde92011-09-21 11:05:43 -0700534 if (DBG) Log.d(TAG, "Untethering " + iface);
Robert Greenwaltb4453622011-11-03 16:01:40 -0700535 synchronized (mPublicSync) {
Christopher Wileyd985dde2016-05-31 10:44:35 -0700536 TetherState tetherState = mTetherStates.get(iface);
537 if (tetherState == null) {
Christopher Wiley4312a4c2016-05-23 13:58:00 -0700538 Log.e(TAG, "Tried to Untether an unknown iface :" + iface + ", ignoring");
Erik Kline7a26ba32018-03-09 14:18:02 +0900539 return TETHER_ERROR_UNKNOWN_IFACE;
Christopher Wiley4312a4c2016-05-23 13:58:00 -0700540 }
Erik Klineea9cc482017-03-10 19:35:34 +0900541 if (!tetherState.isCurrentlyServing()) {
542 Log.e(TAG, "Tried to untether an inactive iface :" + iface + ", ignoring");
Erik Kline7a26ba32018-03-09 14:18:02 +0900543 return TETHER_ERROR_UNAVAIL_IFACE;
Christopher Wiley4312a4c2016-05-23 13:58:00 -0700544 }
Erik Kline7a4ccc62018-08-27 17:26:47 +0900545 tetherState.ipServer.sendMessage(IpServer.CMD_TETHER_UNREQUESTED);
Erik Kline7a26ba32018-03-09 14:18:02 +0900546 return TETHER_ERROR_NO_ERROR;
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800547 }
Robert Greenwalt5a735062010-03-02 17:25:02 -0800548 }
549
Felipe Leme70c8b9b2016-04-25 14:41:31 -0700550 public void untetherAll() {
Erik Kline7a26ba32018-03-09 14:18:02 +0900551 stopTethering(TETHERING_WIFI);
552 stopTethering(TETHERING_USB);
553 stopTethering(TETHERING_BLUETOOTH);
Felipe Leme70c8b9b2016-04-25 14:41:31 -0700554 }
555
Robert Greenwalt5a735062010-03-02 17:25:02 -0800556 public int getLastTetherError(String iface) {
Robert Greenwaltb4453622011-11-03 16:01:40 -0700557 synchronized (mPublicSync) {
Christopher Wileyd985dde2016-05-31 10:44:35 -0700558 TetherState tetherState = mTetherStates.get(iface);
559 if (tetherState == null) {
Robert Greenwaltb4453622011-11-03 16:01:40 -0700560 Log.e(TAG, "Tried to getLastTetherError on an unknown iface :" + iface +
561 ", ignoring");
Erik Kline7a26ba32018-03-09 14:18:02 +0900562 return TETHER_ERROR_UNKNOWN_IFACE;
Robert Greenwaltb4453622011-11-03 16:01:40 -0700563 }
Hugo Benichib55fb222017-03-10 14:20:57 +0900564 return tetherState.lastError;
Robert Greenwalt5a735062010-03-02 17:25:02 -0800565 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800566 }
567
Erik Klineea9cc482017-03-10 19:35:34 +0900568 // TODO: Figure out how to update for local hotspot mode interfaces.
Christopher Wileyd985dde2016-05-31 10:44:35 -0700569 private void sendTetherStateChangedBroadcast() {
Erik Kline7a26ba32018-03-09 14:18:02 +0900570 if (!mDeps.isTetheringSupported()) return;
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800571
Erik Kline8351faa2017-04-17 16:47:23 +0900572 final ArrayList<String> availableList = new ArrayList<>();
573 final ArrayList<String> tetherList = new ArrayList<>();
574 final ArrayList<String> localOnlyList = new ArrayList<>();
575 final ArrayList<String> erroredList = new ArrayList<>();
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800576
Robert Greenwalta599fe7c2010-03-08 18:30:14 -0800577 boolean wifiTethered = false;
578 boolean usbTethered = false;
Danica Chang6fdd0c62010-08-11 14:54:43 -0700579 boolean bluetoothTethered = false;
Robert Greenwalta599fe7c2010-03-08 18:30:14 -0800580
Erik Kline3e756652017-01-17 13:42:19 +0900581 final TetheringConfiguration cfg = mConfig;
582
Robert Greenwaltb4453622011-11-03 16:01:40 -0700583 synchronized (mPublicSync) {
Christopher Wileyd985dde2016-05-31 10:44:35 -0700584 for (int i = 0; i < mTetherStates.size(); i++) {
585 TetherState tetherState = mTetherStates.valueAt(i);
586 String iface = mTetherStates.keyAt(i);
Erik Kline7a26ba32018-03-09 14:18:02 +0900587 if (tetherState.lastError != TETHER_ERROR_NO_ERROR) {
Christopher Wileyd985dde2016-05-31 10:44:35 -0700588 erroredList.add(iface);
Erik Kline7a4ccc62018-08-27 17:26:47 +0900589 } else if (tetherState.lastState == IpServer.STATE_AVAILABLE) {
Christopher Wileyd985dde2016-05-31 10:44:35 -0700590 availableList.add(iface);
Erik Kline7a4ccc62018-08-27 17:26:47 +0900591 } else if (tetherState.lastState == IpServer.STATE_LOCAL_ONLY) {
Erik Kline8351faa2017-04-17 16:47:23 +0900592 localOnlyList.add(iface);
Erik Kline7a4ccc62018-08-27 17:26:47 +0900593 } else if (tetherState.lastState == IpServer.STATE_TETHERED) {
Erik Kline3e756652017-01-17 13:42:19 +0900594 if (cfg.isUsb(iface)) {
Christopher Wileyd985dde2016-05-31 10:44:35 -0700595 usbTethered = true;
Erik Kline3e756652017-01-17 13:42:19 +0900596 } else if (cfg.isWifi(iface)) {
Christopher Wileyd985dde2016-05-31 10:44:35 -0700597 wifiTethered = true;
Erik Kline3e756652017-01-17 13:42:19 +0900598 } else if (cfg.isBluetooth(iface)) {
Christopher Wileyd985dde2016-05-31 10:44:35 -0700599 bluetoothTethered = true;
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800600 }
Erik Kline8351faa2017-04-17 16:47:23 +0900601 tetherList.add(iface);
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800602 }
603 }
604 }
Erik Kline7a26ba32018-03-09 14:18:02 +0900605 final Intent bcast = new Intent(ACTION_TETHER_STATE_CHANGED);
Erik Kline8351faa2017-04-17 16:47:23 +0900606 bcast.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
Robert Greenwalt98c79e52011-07-28 11:51:11 -0700607 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Erik Kline7a26ba32018-03-09 14:18:02 +0900608 bcast.putStringArrayListExtra(EXTRA_AVAILABLE_TETHER, availableList);
609 bcast.putStringArrayListExtra(EXTRA_ACTIVE_LOCAL_ONLY, localOnlyList);
610 bcast.putStringArrayListExtra(EXTRA_ACTIVE_TETHER, tetherList);
611 bcast.putStringArrayListExtra(EXTRA_ERRORED_TETHER, erroredList);
Erik Kline8351faa2017-04-17 16:47:23 +0900612 mContext.sendStickyBroadcastAsUser(bcast, UserHandle.ALL);
Robert Greenwaltfd1be2b2011-11-11 12:30:19 -0800613 if (DBG) {
Lorenzo Colitticd63d242016-04-10 15:39:53 +0900614 Log.d(TAG, String.format(
Erik Kline8351faa2017-04-17 16:47:23 +0900615 "sendTetherStateChangedBroadcast %s=[%s] %s=[%s] %s=[%s] %s=[%s]",
616 "avail", TextUtils.join(",", availableList),
617 "local_only", TextUtils.join(",", localOnlyList),
618 "tether", TextUtils.join(",", tetherList),
619 "error", TextUtils.join(",", erroredList)));
Robert Greenwalt924cc942010-06-28 10:26:19 -0700620 }
Robert Greenwalta599fe7c2010-03-08 18:30:14 -0800621
622 if (usbTethered) {
Danica Chang6fdd0c62010-08-11 14:54:43 -0700623 if (wifiTethered || bluetoothTethered) {
Chris Wren282cfef2017-03-27 15:01:44 -0400624 showTetheredNotification(SystemMessage.NOTE_TETHER_GENERAL);
Robert Greenwalta599fe7c2010-03-08 18:30:14 -0800625 } else {
Chris Wren282cfef2017-03-27 15:01:44 -0400626 showTetheredNotification(SystemMessage.NOTE_TETHER_USB);
Robert Greenwalta599fe7c2010-03-08 18:30:14 -0800627 }
628 } else if (wifiTethered) {
Danica Chang6fdd0c62010-08-11 14:54:43 -0700629 if (bluetoothTethered) {
Chris Wren282cfef2017-03-27 15:01:44 -0400630 showTetheredNotification(SystemMessage.NOTE_TETHER_GENERAL);
Danica Chang6fdd0c62010-08-11 14:54:43 -0700631 } else {
Vinit Deshpande2576a802014-11-18 13:56:15 -0800632 /* We now have a status bar icon for WifiTethering, so drop the notification */
633 clearTetheredNotification();
Danica Chang6fdd0c62010-08-11 14:54:43 -0700634 }
635 } else if (bluetoothTethered) {
Chris Wren282cfef2017-03-27 15:01:44 -0400636 showTetheredNotification(SystemMessage.NOTE_TETHER_BLUETOOTH);
Robert Greenwalta599fe7c2010-03-08 18:30:14 -0800637 } else {
638 clearTetheredNotification();
639 }
640 }
641
Chris Wren282cfef2017-03-27 15:01:44 -0400642 private void showTetheredNotification(int id) {
Alexandru-Andrei Rotarufa6d5c52017-07-18 16:49:22 +0100643 showTetheredNotification(id, true);
644 }
645
646 @VisibleForTesting
647 protected void showTetheredNotification(int id, boolean tetheringOn) {
Robert Greenwalta599fe7c2010-03-08 18:30:14 -0800648 NotificationManager notificationManager =
Erik Klinec438e302017-07-04 22:02:49 +0900649 (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
Robert Greenwalta599fe7c2010-03-08 18:30:14 -0800650 if (notificationManager == null) {
651 return;
652 }
Chris Wren282cfef2017-03-27 15:01:44 -0400653 int icon = 0;
654 switch(id) {
655 case SystemMessage.NOTE_TETHER_USB:
656 icon = com.android.internal.R.drawable.stat_sys_tether_usb;
657 break;
658 case SystemMessage.NOTE_TETHER_BLUETOOTH:
659 icon = com.android.internal.R.drawable.stat_sys_tether_bluetooth;
660 break;
661 case SystemMessage.NOTE_TETHER_GENERAL:
662 default:
663 icon = com.android.internal.R.drawable.stat_sys_tether_general;
664 break;
665 }
Robert Greenwalta599fe7c2010-03-08 18:30:14 -0800666
Chris Wren1ce4b6d2015-06-11 10:19:43 -0400667 if (mLastNotificationId != 0) {
668 if (mLastNotificationId == icon) {
Robert Greenwaltdb3fe9e2010-03-18 16:28:30 -0700669 return;
670 }
Chris Wren1ce4b6d2015-06-11 10:19:43 -0400671 notificationManager.cancelAsUser(null, mLastNotificationId,
Robert Greenwalt3cab6b02012-10-04 16:44:26 -0700672 UserHandle.ALL);
Chris Wren1ce4b6d2015-06-11 10:19:43 -0400673 mLastNotificationId = 0;
Robert Greenwaltdb3fe9e2010-03-18 16:28:30 -0700674 }
675
Robert Greenwalta599fe7c2010-03-08 18:30:14 -0800676 Intent intent = new Intent();
677 intent.setClassName("com.android.settings", "com.android.settings.TetherSettings");
678 intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
679
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700680 PendingIntent pi = PendingIntent.getActivityAsUser(mContext, 0, intent, 0,
681 null, UserHandle.CURRENT);
Robert Greenwalta599fe7c2010-03-08 18:30:14 -0800682
683 Resources r = Resources.getSystem();
Alexandru-Andrei Rotarufa6d5c52017-07-18 16:49:22 +0100684 final CharSequence title;
685 final CharSequence message;
686
687 if (tetheringOn) {
688 title = r.getText(com.android.internal.R.string.tethered_notification_title);
689 message = r.getText(com.android.internal.R.string.tethered_notification_message);
690 } else {
691 title = r.getText(com.android.internal.R.string.disable_tether_notification_title);
692 message = r.getText(com.android.internal.R.string.disable_tether_notification_message);
693 }
Robert Greenwalta599fe7c2010-03-08 18:30:14 -0800694
Chris Wren1ce4b6d2015-06-11 10:19:43 -0400695 if (mTetheredNotificationBuilder == null) {
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500696 mTetheredNotificationBuilder =
697 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Chris Wren1ce4b6d2015-06-11 10:19:43 -0400698 mTetheredNotificationBuilder.setWhen(0)
699 .setOngoing(true)
700 .setColor(mContext.getColor(
701 com.android.internal.R.color.system_notification_accent_color))
702 .setVisibility(Notification.VISIBILITY_PUBLIC)
703 .setCategory(Notification.CATEGORY_STATUS);
Robert Greenwalta599fe7c2010-03-08 18:30:14 -0800704 }
Chris Wren1ce4b6d2015-06-11 10:19:43 -0400705 mTetheredNotificationBuilder.setSmallIcon(icon)
706 .setContentTitle(title)
707 .setContentText(message)
708 .setContentIntent(pi);
Chris Wren282cfef2017-03-27 15:01:44 -0400709 mLastNotificationId = id;
Robert Greenwalta599fe7c2010-03-08 18:30:14 -0800710
Chris Wren1ce4b6d2015-06-11 10:19:43 -0400711 notificationManager.notifyAsUser(null, mLastNotificationId,
zhouzhijie130d4592017-05-18 10:02:59 +0800712 mTetheredNotificationBuilder.buildInto(new Notification()), UserHandle.ALL);
Robert Greenwalta599fe7c2010-03-08 18:30:14 -0800713 }
714
Alexandru-Andrei Rotarufa6d5c52017-07-18 16:49:22 +0100715 @VisibleForTesting
716 protected void clearTetheredNotification() {
Robert Greenwalta599fe7c2010-03-08 18:30:14 -0800717 NotificationManager notificationManager =
Erik Klinec438e302017-07-04 22:02:49 +0900718 (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
Chris Wren1ce4b6d2015-06-11 10:19:43 -0400719 if (notificationManager != null && mLastNotificationId != 0) {
720 notificationManager.cancelAsUser(null, mLastNotificationId,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700721 UserHandle.ALL);
Chris Wren1ce4b6d2015-06-11 10:19:43 -0400722 mLastNotificationId = 0;
Robert Greenwalta599fe7c2010-03-08 18:30:14 -0800723 }
Robert Greenwalt5a735062010-03-02 17:25:02 -0800724 }
725
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800726 private class StateReceiver extends BroadcastReceiver {
Nick Kralevich70c117a2014-05-27 15:30:02 -0700727 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800728 public void onReceive(Context content, Intent intent) {
Erik Kline2e88b5e2017-01-18 11:57:45 +0900729 final String action = intent.getAction();
730 if (action == null) return;
731
Mike Lockwood770126a2010-12-09 22:30:37 -0800732 if (action.equals(UsbManager.ACTION_USB_STATE)) {
Erik Kline2e88b5e2017-01-18 11:57:45 +0900733 handleUsbAction(intent);
Erik Kline7a26ba32018-03-09 14:18:02 +0900734 } else if (action.equals(CONNECTIVITY_ACTION)) {
Erik Kline2e88b5e2017-01-18 11:57:45 +0900735 handleConnectivityAction(intent);
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700736 } else if (action.equals(WifiManager.WIFI_AP_STATE_CHANGED_ACTION)) {
Erik Kline2e88b5e2017-01-18 11:57:45 +0900737 handleWifiApAction(intent);
Robert Greenwaltc13368b2013-07-18 14:24:42 -0700738 } else if (action.equals(Intent.ACTION_CONFIGURATION_CHANGED)) {
Erik Klinede637722017-10-12 22:16:01 +0900739 mLog.log("OBSERVED configuration changed");
Robert Greenwaltc13368b2013-07-18 14:24:42 -0700740 updateConfiguration();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800741 }
742 }
Erik Kline2e88b5e2017-01-18 11:57:45 +0900743
744 private void handleConnectivityAction(Intent intent) {
Erik Kline7a26ba32018-03-09 14:18:02 +0900745 final NetworkInfo networkInfo =
746 (NetworkInfo) intent.getParcelableExtra(EXTRA_NETWORK_INFO);
Erik Kline2e88b5e2017-01-18 11:57:45 +0900747 if (networkInfo == null ||
748 networkInfo.getDetailedState() == NetworkInfo.DetailedState.FAILED) {
749 return;
750 }
751
752 if (VDBG) Log.d(TAG, "Tethering got CONNECTIVITY_ACTION: " + networkInfo.toString());
753 mTetherMasterSM.sendMessage(TetherMasterSM.CMD_UPSTREAM_CHANGED);
754 }
755
756 private void handleUsbAction(Intent intent) {
757 final boolean usbConnected = intent.getBooleanExtra(USB_CONNECTED, false);
Erik Klinec438e302017-07-04 22:02:49 +0900758 final boolean usbConfigured = intent.getBooleanExtra(USB_CONFIGURED, false);
Erik Kline2e88b5e2017-01-18 11:57:45 +0900759 final boolean rndisEnabled = intent.getBooleanExtra(USB_FUNCTION_RNDIS, false);
Erik Klinec438e302017-07-04 22:02:49 +0900760
761 mLog.log(String.format("USB bcast connected:%s configured:%s rndis:%s",
762 usbConnected, usbConfigured, rndisEnabled));
763
764 // There are three types of ACTION_USB_STATE:
765 //
766 // - DISCONNECTED (USB_CONNECTED and USB_CONFIGURED are 0)
767 // Meaning: USB connection has ended either because of
768 // software reset or hard unplug.
769 //
770 // - CONNECTED (USB_CONNECTED is 1, USB_CONFIGURED is 0)
771 // Meaning: the first stage of USB protocol handshake has
772 // occurred but it is not complete.
773 //
774 // - CONFIGURED (USB_CONNECTED and USB_CONFIGURED are 1)
775 // Meaning: the USB handshake is completely done and all the
776 // functions are ready to use.
777 //
778 // For more explanation, see b/62552150 .
Erik Kline2e88b5e2017-01-18 11:57:45 +0900779 synchronized (Tethering.this.mPublicSync) {
Jerry Zhang656a7bc2017-12-20 14:26:39 -0800780 if (!usbConnected && mRndisEnabled) {
781 // Turn off tethering if it was enabled and there is a disconnect.
Erik Kline7a4ccc62018-08-27 17:26:47 +0900782 tetherMatchingInterfaces(IpServer.STATE_AVAILABLE, TETHERING_USB);
Jerry Zhang656a7bc2017-12-20 14:26:39 -0800783 } else if (usbConfigured && rndisEnabled) {
784 // Tether if rndis is enabled and usb is configured.
Erik Kline7a4ccc62018-08-27 17:26:47 +0900785 tetherMatchingInterfaces(IpServer.STATE_TETHERED, TETHERING_USB);
Erik Kline2e88b5e2017-01-18 11:57:45 +0900786 }
Jerry Zhang656a7bc2017-12-20 14:26:39 -0800787 mRndisEnabled = usbConfigured && rndisEnabled;
Erik Kline2e88b5e2017-01-18 11:57:45 +0900788 }
789 }
790
791 private void handleWifiApAction(Intent intent) {
Erik Kline2efb8272017-05-31 15:53:53 +0900792 final int curState = intent.getIntExtra(EXTRA_WIFI_AP_STATE, WIFI_AP_STATE_DISABLED);
793 final String ifname = intent.getStringExtra(EXTRA_WIFI_AP_INTERFACE_NAME);
794 final int ipmode = intent.getIntExtra(EXTRA_WIFI_AP_MODE, IFACE_IP_MODE_UNSPECIFIED);
795
Erik Kline2e88b5e2017-01-18 11:57:45 +0900796 synchronized (Tethering.this.mPublicSync) {
797 switch (curState) {
798 case WifiManager.WIFI_AP_STATE_ENABLING:
799 // We can see this state on the way to both enabled and failure states.
800 break;
801 case WifiManager.WIFI_AP_STATE_ENABLED:
Erik Kline2efb8272017-05-31 15:53:53 +0900802 enableWifiIpServingLocked(ifname, ipmode);
Erik Kline2e88b5e2017-01-18 11:57:45 +0900803 break;
804 case WifiManager.WIFI_AP_STATE_DISABLED:
805 case WifiManager.WIFI_AP_STATE_DISABLING:
806 case WifiManager.WIFI_AP_STATE_FAILED:
807 default:
Erik Kline562e0c12017-06-09 16:36:29 +0900808 disableWifiIpServingLocked(ifname, curState);
Erik Kline2efb8272017-05-31 15:53:53 +0900809 break;
Erik Kline2e88b5e2017-01-18 11:57:45 +0900810 }
811 }
812 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800813 }
814
Alexandru-Andrei Rotarufa6d5c52017-07-18 16:49:22 +0100815 @VisibleForTesting
816 protected static class TetheringUserRestrictionListener implements UserRestrictionsListener {
817 private final Tethering mWrapper;
818
819 public TetheringUserRestrictionListener(Tethering wrapper) {
820 mWrapper = wrapper;
821 }
822
823 public void onUserRestrictionsChanged(int userId,
824 Bundle newRestrictions,
825 Bundle prevRestrictions) {
826 final boolean newlyDisallowed =
827 newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_TETHERING);
828 final boolean previouslyDisallowed =
829 prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_TETHERING);
830 final boolean tetheringDisallowedChanged = (newlyDisallowed != previouslyDisallowed);
831
832 if (!tetheringDisallowedChanged) {
833 return;
834 }
835
836 mWrapper.clearTetheredNotification();
837 final boolean isTetheringActiveOnDevice = (mWrapper.getTetheredIfaces().length != 0);
838
839 if (newlyDisallowed && isTetheringActiveOnDevice) {
840 mWrapper.showTetheredNotification(
841 com.android.internal.R.drawable.stat_sys_tether_general, false);
842 mWrapper.untetherAll();
843 }
844 }
845 }
846
Erik Kline562e0c12017-06-09 16:36:29 +0900847 private void disableWifiIpServingLocked(String ifname, int apState) {
848 mLog.log("Canceling WiFi tethering request - AP_STATE=" + apState);
Erik Kline2efb8272017-05-31 15:53:53 +0900849
Erik Kline562e0c12017-06-09 16:36:29 +0900850 // Regardless of whether we requested this transition, the AP has gone
851 // down. Don't try to tether again unless we're requested to do so.
852 // TODO: Remove this altogether, once Wi-Fi reliably gives us an
853 // interface name with every broadcast.
854 mWifiTetherRequested = false;
855
856 if (!TextUtils.isEmpty(ifname)) {
857 final TetherState ts = mTetherStates.get(ifname);
858 if (ts != null) {
Erik Kline7a4ccc62018-08-27 17:26:47 +0900859 ts.ipServer.unwanted();
Erik Kline562e0c12017-06-09 16:36:29 +0900860 return;
861 }
862 }
863
Erik Kline2efb8272017-05-31 15:53:53 +0900864 for (int i = 0; i < mTetherStates.size(); i++) {
Erik Kline7a4ccc62018-08-27 17:26:47 +0900865 final IpServer ipServer = mTetherStates.valueAt(i).ipServer;
866 if (ipServer.interfaceType() == TETHERING_WIFI) {
867 ipServer.unwanted();
Erik Kline562e0c12017-06-09 16:36:29 +0900868 return;
Erik Kline2efb8272017-05-31 15:53:53 +0900869 }
870 }
Erik Kline562e0c12017-06-09 16:36:29 +0900871
872 mLog.log("Error disabling Wi-Fi IP serving; " +
873 (TextUtils.isEmpty(ifname) ? "no interface name specified"
874 : "specified interface: " + ifname));
Erik Kline2efb8272017-05-31 15:53:53 +0900875 }
876
877 private void enableWifiIpServingLocked(String ifname, int wifiIpMode) {
Erik Kline7a4ccc62018-08-27 17:26:47 +0900878 // Map wifiIpMode values to IpServer.Callback serving states, inferring
Erik Kline2efb8272017-05-31 15:53:53 +0900879 // from mWifiTetherRequested as a final "best guess".
880 final int ipServingMode;
881 switch (wifiIpMode) {
882 case IFACE_IP_MODE_TETHERED:
Erik Kline7a4ccc62018-08-27 17:26:47 +0900883 ipServingMode = IpServer.STATE_TETHERED;
Erik Kline2efb8272017-05-31 15:53:53 +0900884 break;
885 case IFACE_IP_MODE_LOCAL_ONLY:
Erik Kline7a4ccc62018-08-27 17:26:47 +0900886 ipServingMode = IpServer.STATE_LOCAL_ONLY;
Erik Kline2efb8272017-05-31 15:53:53 +0900887 break;
888 default:
Erik Kline9e225542017-06-08 17:48:48 +0900889 mLog.e("Cannot enable IP serving in unknown WiFi mode: " + wifiIpMode);
890 return;
Erik Kline2efb8272017-05-31 15:53:53 +0900891 }
892
893 if (!TextUtils.isEmpty(ifname)) {
Erik Kline7a26ba32018-03-09 14:18:02 +0900894 maybeTrackNewInterfaceLocked(ifname, TETHERING_WIFI);
Erik Kline2efb8272017-05-31 15:53:53 +0900895 changeInterfaceState(ifname, ipServingMode);
896 } else {
Erik Kline9e225542017-06-08 17:48:48 +0900897 mLog.e(String.format(
898 "Cannot enable IP serving in mode %s on missing interface name",
899 ipServingMode));
Erik Kline2efb8272017-05-31 15:53:53 +0900900 }
901 }
902
Erik Klineea9cc482017-03-10 19:35:34 +0900903 // TODO: Consider renaming to something more accurate in its description.
904 // This method:
905 // - allows requesting either tethering or local hotspot serving states
906 // - handles both enabling and disabling serving states
907 // - only tethers the first matching interface in listInterfaces()
908 // order of a given type
909 private void tetherMatchingInterfaces(int requestedState, int interfaceType) {
910 if (VDBG) {
911 Log.d(TAG, "tetherMatchingInterfaces(" + requestedState + ", " + interfaceType + ")");
912 }
Mike Lockwood3c2a2f62011-06-08 15:10:26 -0700913
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700914 String[] ifaces = null;
Robert Greenwalt65ae29b2010-02-18 11:25:54 -0800915 try {
Chia-chi Yehc9338302011-05-11 16:35:13 -0700916 ifaces = mNMService.listInterfaces();
Robert Greenwalt65ae29b2010-02-18 11:25:54 -0800917 } catch (Exception e) {
Mike Lockwood3c2a2f62011-06-08 15:10:26 -0700918 Log.e(TAG, "Error listing Interfaces", e);
Robert Greenwalt65ae29b2010-02-18 11:25:54 -0800919 return;
920 }
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700921 String chosenIface = null;
922 if (ifaces != null) {
923 for (String iface : ifaces) {
924 if (ifaceNameToType(iface) == interfaceType) {
925 chosenIface = iface;
926 break;
Robert Greenwalt65ae29b2010-02-18 11:25:54 -0800927 }
928 }
929 }
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700930 if (chosenIface == null) {
931 Log.e(TAG, "could not find iface of type " + interfaceType);
932 return;
933 }
934
Erik Kline2efb8272017-05-31 15:53:53 +0900935 changeInterfaceState(chosenIface, requestedState);
936 }
937
938 private void changeInterfaceState(String ifname, int requestedState) {
Erik Klineea9cc482017-03-10 19:35:34 +0900939 final int result;
940 switch (requestedState) {
Erik Kline7a4ccc62018-08-27 17:26:47 +0900941 case IpServer.STATE_UNAVAILABLE:
942 case IpServer.STATE_AVAILABLE:
Erik Kline2efb8272017-05-31 15:53:53 +0900943 result = untether(ifname);
Erik Klineea9cc482017-03-10 19:35:34 +0900944 break;
Erik Kline7a4ccc62018-08-27 17:26:47 +0900945 case IpServer.STATE_TETHERED:
946 case IpServer.STATE_LOCAL_ONLY:
Erik Kline2efb8272017-05-31 15:53:53 +0900947 result = tether(ifname, requestedState);
Erik Klineea9cc482017-03-10 19:35:34 +0900948 break;
949 default:
950 Log.wtf(TAG, "Unknown interface state: " + requestedState);
951 return;
952 }
Erik Kline7a26ba32018-03-09 14:18:02 +0900953 if (result != TETHER_ERROR_NO_ERROR) {
Erik Kline2efb8272017-05-31 15:53:53 +0900954 Log.e(TAG, "unable start or stop tethering on iface " + ifname);
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700955 return;
956 }
Robert Greenwalt65ae29b2010-02-18 11:25:54 -0800957 }
958
Erik Kline3e756652017-01-17 13:42:19 +0900959 public TetheringConfiguration getTetheringConfiguration() {
960 return mConfig;
961 }
962
Erik Klined781fba2017-01-23 13:01:58 +0900963 public boolean hasTetherableConfiguration() {
964 final TetheringConfiguration cfg = mConfig;
965 final boolean hasDownstreamConfiguration =
markchien1be8d8f2018-12-05 21:20:01 +0800966 (cfg.tetherableUsbRegexs.length != 0)
967 || (cfg.tetherableWifiRegexs.length != 0)
968 || (cfg.tetherableBluetoothRegexs.length != 0);
969 final boolean hasUpstreamConfiguration = !cfg.preferredUpstreamIfaceTypes.isEmpty()
970 || cfg.chooseUpstreamAutomatically;
Erik Klined781fba2017-01-23 13:01:58 +0900971
972 return hasDownstreamConfiguration && hasUpstreamConfiguration;
973 }
974
Erik Kline3e756652017-01-17 13:42:19 +0900975 // TODO - update callers to use getTetheringConfiguration(),
976 // which has only final members.
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800977 public String[] getTetherableUsbRegexs() {
Erik Kline3e756652017-01-17 13:42:19 +0900978 return copy(mConfig.tetherableUsbRegexs);
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800979 }
980
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800981 public String[] getTetherableWifiRegexs() {
Erik Kline3e756652017-01-17 13:42:19 +0900982 return copy(mConfig.tetherableWifiRegexs);
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800983 }
984
Danica Chang6fdd0c62010-08-11 14:54:43 -0700985 public String[] getTetherableBluetoothRegexs() {
Erik Kline3e756652017-01-17 13:42:19 +0900986 return copy(mConfig.tetherableBluetoothRegexs);
Danica Chang6fdd0c62010-08-11 14:54:43 -0700987 }
988
Mike Lockwood6c2260b2011-07-19 13:04:47 -0700989 public int setUsbTethering(boolean enable) {
Wink Savillec9acde92011-09-21 11:05:43 -0700990 if (VDBG) Log.d(TAG, "setUsbTethering(" + enable + ")");
Erik Klinec438e302017-07-04 22:02:49 +0900991 UsbManager usbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
Robert Greenwaltb4453622011-11-03 16:01:40 -0700992 synchronized (mPublicSync) {
Jerry Zhang327b8092018-01-09 17:53:04 -0800993 usbManager.setCurrentFunctions(enable ? UsbManager.FUNCTION_RNDIS
994 : UsbManager.FUNCTION_NONE);
Mike Lockwood6c2260b2011-07-19 13:04:47 -0700995 }
Erik Kline7a26ba32018-03-09 14:18:02 +0900996 return TETHER_ERROR_NO_ERROR;
Mike Lockwood6c2260b2011-07-19 13:04:47 -0700997 }
998
Erik Kline1fdc2e22017-05-08 17:56:35 +0900999 // TODO review API - figure out how to delete these entirely.
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001000 public String[] getTetheredIfaces() {
1001 ArrayList<String> list = new ArrayList<String>();
Robert Greenwaltb4453622011-11-03 16:01:40 -07001002 synchronized (mPublicSync) {
Christopher Wileyd985dde2016-05-31 10:44:35 -07001003 for (int i = 0; i < mTetherStates.size(); i++) {
1004 TetherState tetherState = mTetherStates.valueAt(i);
Erik Kline7a4ccc62018-08-27 17:26:47 +09001005 if (tetherState.lastState == IpServer.STATE_TETHERED) {
Christopher Wileyd985dde2016-05-31 10:44:35 -07001006 list.add(mTetherStates.keyAt(i));
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001007 }
1008 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001009 }
Christopher Wileyd985dde2016-05-31 10:44:35 -07001010 return list.toArray(new String[list.size()]);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001011 }
1012
1013 public String[] getTetherableIfaces() {
1014 ArrayList<String> list = new ArrayList<String>();
Robert Greenwaltb4453622011-11-03 16:01:40 -07001015 synchronized (mPublicSync) {
Christopher Wileyd985dde2016-05-31 10:44:35 -07001016 for (int i = 0; i < mTetherStates.size(); i++) {
1017 TetherState tetherState = mTetherStates.valueAt(i);
Erik Kline7a4ccc62018-08-27 17:26:47 +09001018 if (tetherState.lastState == IpServer.STATE_AVAILABLE) {
Christopher Wileyd985dde2016-05-31 10:44:35 -07001019 list.add(mTetherStates.keyAt(i));
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001020 }
1021 }
1022 }
Christopher Wileyd985dde2016-05-31 10:44:35 -07001023 return list.toArray(new String[list.size()]);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001024 }
1025
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07001026 public String[] getTetheredDhcpRanges() {
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +09001027 // TODO: this is only valid for the old DHCP server. Latest search suggests it is only used
1028 // by WifiP2pServiceImpl to start dnsmasq: remove/deprecate after migrating callers.
1029 return mConfig.legacyDhcpRanges;
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07001030 }
1031
Robert Greenwalt5a735062010-03-02 17:25:02 -08001032 public String[] getErroredIfaces() {
1033 ArrayList<String> list = new ArrayList<String>();
Robert Greenwaltb4453622011-11-03 16:01:40 -07001034 synchronized (mPublicSync) {
Christopher Wileyd985dde2016-05-31 10:44:35 -07001035 for (int i = 0; i < mTetherStates.size(); i++) {
1036 TetherState tetherState = mTetherStates.valueAt(i);
Erik Kline7a26ba32018-03-09 14:18:02 +09001037 if (tetherState.lastError != TETHER_ERROR_NO_ERROR) {
Christopher Wileyd985dde2016-05-31 10:44:35 -07001038 list.add(mTetherStates.keyAt(i));
Robert Greenwalt5a735062010-03-02 17:25:02 -08001039 }
1040 }
1041 }
Christopher Wileyd985dde2016-05-31 10:44:35 -07001042 return list.toArray(new String[list.size()]);
Robert Greenwalt5a735062010-03-02 17:25:02 -08001043 }
1044
Erik Kline22108902017-07-06 16:40:06 +09001045 private void logMessage(State state, int what) {
1046 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
Lorenzo Colitticd63d242016-04-10 15:39:53 +09001047 }
1048
Erik Klineea9cc482017-03-10 19:35:34 +09001049 private boolean upstreamWanted() {
1050 if (!mForwardedDownstreams.isEmpty()) return true;
1051
1052 synchronized (mPublicSync) {
Jerry Zhang656a7bc2017-12-20 14:26:39 -08001053 return mWifiTetherRequested;
Erik Klineea9cc482017-03-10 19:35:34 +09001054 }
1055 }
1056
Erik Kline00019f42016-06-30 19:31:46 +09001057 // Needed because the canonical source of upstream truth is just the
Remi NGUYEN VAN6c02f992018-03-09 14:07:18 +09001058 // upstream interface set, |mCurrentUpstreamIfaceSet|.
Erik Kline3a5278f2017-06-24 19:29:10 +09001059 private boolean pertainsToCurrentUpstream(NetworkState ns) {
Remi NGUYEN VAN6c02f992018-03-09 14:07:18 +09001060 if (ns != null && ns.linkProperties != null && mCurrentUpstreamIfaceSet != null) {
Erik Kline00019f42016-06-30 19:31:46 +09001061 for (String ifname : ns.linkProperties.getAllInterfaceNames()) {
Remi NGUYEN VAN6c02f992018-03-09 14:07:18 +09001062 if (mCurrentUpstreamIfaceSet.ifnames.contains(ifname)) {
Erik Kline00019f42016-06-30 19:31:46 +09001063 return true;
Erik Kline6ff17f72015-12-10 20:42:12 +09001064 }
1065 }
Erik Kline6ff17f72015-12-10 20:42:12 +09001066 }
Erik Kline00019f42016-06-30 19:31:46 +09001067 return false;
Erik Kline6ff17f72015-12-10 20:42:12 +09001068 }
1069
Wink Saville64c42ca2011-04-18 14:55:10 -07001070 class TetherMasterSM extends StateMachine {
Lorenzo Colitticd63d242016-04-10 15:39:53 +09001071 private static final int BASE_MASTER = Protocol.BASE_TETHERING;
Erik Klineea9cc482017-03-10 19:35:34 +09001072 // an interface SM has requested Tethering/Local Hotspot
1073 static final int EVENT_IFACE_SERVING_STATE_ACTIVE = BASE_MASTER + 1;
1074 // an interface SM has unrequested Tethering/Local Hotspot
1075 static final int EVENT_IFACE_SERVING_STATE_INACTIVE = BASE_MASTER + 2;
Robert Greenwalt6a1967c2010-03-17 11:19:57 -07001076 // upstream connection change - do the right thing
Lorenzo Colitticd63d242016-04-10 15:39:53 +09001077 static final int CMD_UPSTREAM_CHANGED = BASE_MASTER + 3;
Robert Greenwalt6a1967c2010-03-17 11:19:57 -07001078 // we don't have a valid upstream conn, check again after a delay
Lorenzo Colitticd63d242016-04-10 15:39:53 +09001079 static final int CMD_RETRY_UPSTREAM = BASE_MASTER + 4;
Erik Kline6ff17f72015-12-10 20:42:12 +09001080 // Events from NetworkCallbacks that we process on the master state
1081 // machine thread on behalf of the UpstreamNetworkMonitor.
Erik Kline00019f42016-06-30 19:31:46 +09001082 static final int EVENT_UPSTREAM_CALLBACK = BASE_MASTER + 5;
Yohei, Oshima977aad52016-12-08 13:39:20 +09001083 // we treated the error and want now to clear it
1084 static final int CMD_CLEAR_ERROR = BASE_MASTER + 6;
Erik Kline6e9a1012017-06-06 19:24:21 +09001085 static final int EVENT_IFACE_UPDATE_LINKPROPERTIES = BASE_MASTER + 7;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001086
Erik Kline32179ff2017-07-04 18:28:11 +09001087 private final State mInitialState;
1088 private final State mTetherModeAliveState;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001089
Erik Kline32179ff2017-07-04 18:28:11 +09001090 private final State mSetIpForwardingEnabledErrorState;
1091 private final State mSetIpForwardingDisabledErrorState;
1092 private final State mStartTetheringErrorState;
1093 private final State mStopTetheringErrorState;
1094 private final State mSetDnsForwardersErrorState;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001095
Christopher Wileyd985dde2016-05-31 10:44:35 -07001096 // This list is a little subtle. It contains all the interfaces that currently are
1097 // requesting tethering, regardless of whether these interfaces are still members of
1098 // mTetherStates. This allows us to maintain the following predicates:
1099 //
1100 // 1) mTetherStates contains the set of all currently existing, tetherable, link state up
1101 // interfaces.
1102 // 2) mNotifyList contains all state machines that may have outstanding tethering state
1103 // that needs to be torn down.
1104 //
1105 // Because we excise interfaces immediately from mTetherStates, we must maintain mNotifyList
1106 // so that the garbage collector does not clean up the state machine before it has a chance
1107 // to tear itself down.
Erik Kline7a4ccc62018-08-27 17:26:47 +09001108 private final ArrayList<IpServer> mNotifyList;
Erik Kline1eb8c692016-07-08 17:21:26 +09001109 private final IPv6TetheringCoordinator mIPv6TetheringCoordinator;
Erik Klineed962a82017-07-06 19:49:35 +09001110 private final OffloadWrapper mOffload;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001111
Robert Greenwalt6a1967c2010-03-17 11:19:57 -07001112 private static final int UPSTREAM_SETTLE_TIME_MS = 10000;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001113
Remi NGUYEN VAN5d0dc452018-03-15 11:57:14 +09001114 TetherMasterSM(String name, Looper looper, TetheringDependencies deps) {
Robert Greenwaltdfadaea2010-03-11 15:03:08 -08001115 super(name, looper);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001116
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001117 mInitialState = new InitialState();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001118 mTetherModeAliveState = new TetherModeAliveState();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001119 mSetIpForwardingEnabledErrorState = new SetIpForwardingEnabledErrorState();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001120 mSetIpForwardingDisabledErrorState = new SetIpForwardingDisabledErrorState();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001121 mStartTetheringErrorState = new StartTetheringErrorState();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001122 mStopTetheringErrorState = new StopTetheringErrorState();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001123 mSetDnsForwardersErrorState = new SetDnsForwardersErrorState();
Erik Kline1fdc2e22017-05-08 17:56:35 +09001124
1125 addState(mInitialState);
1126 addState(mTetherModeAliveState);
1127 addState(mSetIpForwardingEnabledErrorState);
1128 addState(mSetIpForwardingDisabledErrorState);
1129 addState(mStartTetheringErrorState);
1130 addState(mStopTetheringErrorState);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001131 addState(mSetDnsForwardersErrorState);
1132
Mitchell Wills7040b4e2016-05-23 16:40:10 -07001133 mNotifyList = new ArrayList<>();
Remi NGUYEN VAN5d0dc452018-03-15 11:57:14 +09001134 mIPv6TetheringCoordinator = deps.getIPv6TetheringCoordinator(mNotifyList, mLog);
Erik Klineed962a82017-07-06 19:49:35 +09001135 mOffload = new OffloadWrapper();
Erik Kline32179ff2017-07-04 18:28:11 +09001136
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001137 setInitialState(mInitialState);
1138 }
1139
Erik Kline1fdc2e22017-05-08 17:56:35 +09001140 class InitialState extends State {
1141 @Override
1142 public boolean processMessage(Message message) {
Erik Kline22108902017-07-06 16:40:06 +09001143 logMessage(this, message.what);
Erik Kline1fdc2e22017-05-08 17:56:35 +09001144 switch (message.what) {
Erik Kline7a4ccc62018-08-27 17:26:47 +09001145 case EVENT_IFACE_SERVING_STATE_ACTIVE: {
1146 final IpServer who = (IpServer) message.obj;
Erik Kline1fdc2e22017-05-08 17:56:35 +09001147 if (VDBG) Log.d(TAG, "Tether Mode requested by " + who);
1148 handleInterfaceServingStateActive(message.arg1, who);
1149 transitionTo(mTetherModeAliveState);
1150 break;
Erik Kline7a4ccc62018-08-27 17:26:47 +09001151 }
1152 case EVENT_IFACE_SERVING_STATE_INACTIVE: {
1153 final IpServer who = (IpServer) message.obj;
Erik Kline1fdc2e22017-05-08 17:56:35 +09001154 if (VDBG) Log.d(TAG, "Tether Mode unrequested by " + who);
1155 handleInterfaceServingStateInactive(who);
1156 break;
Erik Kline7a4ccc62018-08-27 17:26:47 +09001157 }
Erik Kline6e9a1012017-06-06 19:24:21 +09001158 case EVENT_IFACE_UPDATE_LINKPROPERTIES:
1159 // Silently ignore these for now.
1160 break;
Erik Kline1fdc2e22017-05-08 17:56:35 +09001161 default:
1162 return NOT_HANDLED;
1163 }
1164 return HANDLED;
1165 }
1166 }
1167
Erik Kline3a5278f2017-06-24 19:29:10 +09001168 protected boolean turnOnMasterTetherSettings() {
1169 final TetheringConfiguration cfg = mConfig;
1170 try {
1171 mNMService.setIpForwardingEnabled(true);
1172 } catch (Exception e) {
1173 mLog.e(e);
1174 transitionTo(mSetIpForwardingEnabledErrorState);
Robert Greenwaltd70a3d42010-02-23 18:15:29 -08001175 return false;
1176 }
Erik Kline3a5278f2017-06-24 19:29:10 +09001177 // TODO: Randomize DHCPv4 ranges, especially in hotspot mode.
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +09001178 // Legacy DHCP server is disabled if passed an empty ranges array
1179 final String[] dhcpRanges = cfg.enableLegacyDhcpServer
1180 ? cfg.legacyDhcpRanges
1181 : new String[0];
Erik Kline3a5278f2017-06-24 19:29:10 +09001182 try {
1183 // TODO: Find a more accurate method name (startDHCPv4()?).
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +09001184 mNMService.startTethering(dhcpRanges);
Erik Kline3a5278f2017-06-24 19:29:10 +09001185 } catch (Exception e) {
Robert Greenwaltd70a3d42010-02-23 18:15:29 -08001186 try {
Chia-chi Yehc9338302011-05-11 16:35:13 -07001187 mNMService.stopTethering();
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +09001188 mNMService.startTethering(dhcpRanges);
Erik Kline3a5278f2017-06-24 19:29:10 +09001189 } catch (Exception ee) {
1190 mLog.e(ee);
1191 transitionTo(mStartTetheringErrorState);
Robert Greenwaltd70a3d42010-02-23 18:15:29 -08001192 return false;
1193 }
Robert Greenwaltd70a3d42010-02-23 18:15:29 -08001194 }
Erik Kline3a5278f2017-06-24 19:29:10 +09001195 mLog.log("SET master tether settings: ON");
1196 return true;
1197 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001198
Erik Kline3a5278f2017-06-24 19:29:10 +09001199 protected boolean turnOffMasterTetherSettings() {
1200 try {
1201 mNMService.stopTethering();
1202 } catch (Exception e) {
1203 mLog.e(e);
1204 transitionTo(mStopTetheringErrorState);
1205 return false;
Erik Kline14f7faf2017-02-14 19:03:09 +09001206 }
Erik Kline3a5278f2017-06-24 19:29:10 +09001207 try {
1208 mNMService.setIpForwardingEnabled(false);
1209 } catch (Exception e) {
1210 mLog.e(e);
1211 transitionTo(mSetIpForwardingDisabledErrorState);
1212 return false;
1213 }
1214 transitionTo(mInitialState);
1215 mLog.log("SET master tether settings: OFF");
1216 return true;
1217 }
Erik Kline14f7faf2017-02-14 19:03:09 +09001218
Erik Kline3a5278f2017-06-24 19:29:10 +09001219 protected void chooseUpstreamType(boolean tryCell) {
Erik Kline6ee73da2017-07-08 20:36:37 +09001220 // We rebuild configuration on ACTION_CONFIGURATION_CHANGED, but we
1221 // do not currently know how to watch for changes in DUN settings.
1222 maybeUpdateConfiguration();
Erik Kline1e2897d2017-06-09 17:08:52 +09001223
Erik Kline72302902018-06-14 17:36:40 +09001224 final TetheringConfiguration config = mConfig;
1225 final NetworkState ns = (config.chooseUpstreamAutomatically)
1226 ? mUpstreamNetworkMonitor.getCurrentPreferredUpstream()
1227 : mUpstreamNetworkMonitor.selectPreferredUpstreamType(
1228 config.preferredUpstreamIfaceTypes);
Erik Kline3a5278f2017-06-24 19:29:10 +09001229 if (ns == null) {
1230 if (tryCell) {
1231 mUpstreamNetworkMonitor.registerMobileNetworkRequest();
1232 // We think mobile should be coming up; don't set a retry.
1233 } else {
1234 sendMessageDelayed(CMD_RETRY_UPSTREAM, UPSTREAM_SETTLE_TIME_MS);
Erik Kline1e2897d2017-06-09 17:08:52 +09001235 }
Erik Kline3a5278f2017-06-24 19:29:10 +09001236 }
1237 setUpstreamNetwork(ns);
markchien6ea34542019-02-27 14:56:11 +08001238 final Network newUpstream = (ns != null) ? ns.network : null;
1239 if (mTetherUpstream != newUpstream) {
1240 mTetherUpstream = newUpstream;
1241 mUpstreamNetworkMonitor.setCurrentUpstream(mTetherUpstream);
1242 reportUpstreamChanged(mTetherUpstream);
1243 }
Erik Kline3a5278f2017-06-24 19:29:10 +09001244 }
1245
1246 protected void setUpstreamNetwork(NetworkState ns) {
Remi NGUYEN VAN6c02f992018-03-09 14:07:18 +09001247 InterfaceSet ifaces = null;
Erik Klinee8bdb402018-02-23 14:16:06 -08001248 if (ns != null) {
Erik Kline3a5278f2017-06-24 19:29:10 +09001249 // Find the interface with the default IPv4 route. It may be the
1250 // interface described by linkProperties, or one of the interfaces
1251 // stacked on top of it.
Erik Klinee8bdb402018-02-23 14:16:06 -08001252 mLog.i("Looking for default routes on: " + ns.linkProperties);
Remi NGUYEN VAN6c02f992018-03-09 14:07:18 +09001253 ifaces = TetheringInterfaceUtils.getTetheringInterfaces(ns);
1254 mLog.i("Found upstream interface(s): " + ifaces);
Robert Greenwalt6a1967c2010-03-17 11:19:57 -07001255 }
Robert Greenwaltccf83af12011-06-02 17:30:47 -07001256
Remi NGUYEN VAN6c02f992018-03-09 14:07:18 +09001257 if (ifaces != null) {
Erik Kline3a5278f2017-06-24 19:29:10 +09001258 setDnsForwarders(ns.network, ns.linkProperties);
Erik Kline6ff17f72015-12-10 20:42:12 +09001259 }
Remi NGUYEN VAN6c02f992018-03-09 14:07:18 +09001260 notifyDownstreamsOfNewUpstreamIface(ifaces);
Erik Kline3a5278f2017-06-24 19:29:10 +09001261 if (ns != null && pertainsToCurrentUpstream(ns)) {
Erik Kline72302902018-06-14 17:36:40 +09001262 // If we already have NetworkState for this network update it immediately.
Erik Kline3a5278f2017-06-24 19:29:10 +09001263 handleNewUpstreamNetworkState(ns);
Remi NGUYEN VAN6c02f992018-03-09 14:07:18 +09001264 } else if (mCurrentUpstreamIfaceSet == null) {
1265 // There are no available upstream networks.
Erik Kline3a5278f2017-06-24 19:29:10 +09001266 handleNewUpstreamNetworkState(null);
1267 }
1268 }
Erik Kline6ff17f72015-12-10 20:42:12 +09001269
Erik Kline3a5278f2017-06-24 19:29:10 +09001270 protected void setDnsForwarders(final Network network, final LinkProperties lp) {
1271 // TODO: Set v4 and/or v6 DNS per available connectivity.
1272 String[] dnsServers = mConfig.defaultIPv4DNS;
1273 final Collection<InetAddress> dnses = lp.getDnsServers();
1274 // TODO: Properly support the absence of DNS servers.
1275 if (dnses != null && !dnses.isEmpty()) {
1276 // TODO: remove this invocation of NetworkUtils.makeStrings().
1277 dnsServers = NetworkUtils.makeStrings(dnses);
Robert Greenwalt6a1967c2010-03-17 11:19:57 -07001278 }
Erik Kline3a5278f2017-06-24 19:29:10 +09001279 try {
1280 mNMService.setDnsForwarders(network, dnsServers);
1281 mLog.log(String.format(
1282 "SET DNS forwarders: network=%s dnsServers=%s",
1283 network, Arrays.toString(dnsServers)));
1284 } catch (Exception e) {
1285 // TODO: Investigate how this can fail and what exactly
1286 // happens if/when such failures occur.
1287 mLog.e("setting DNS forwarders failed, " + e);
1288 transitionTo(mSetDnsForwardersErrorState);
1289 }
1290 }
Erik Kline00019f42016-06-30 19:31:46 +09001291
Remi NGUYEN VAN6c02f992018-03-09 14:07:18 +09001292 protected void notifyDownstreamsOfNewUpstreamIface(InterfaceSet ifaces) {
1293 mCurrentUpstreamIfaceSet = ifaces;
Erik Kline7a4ccc62018-08-27 17:26:47 +09001294 for (IpServer ipServer : mNotifyList) {
1295 ipServer.sendMessage(IpServer.CMD_TETHER_CONNECTION_CHANGED, ifaces);
Erik Kline00019f42016-06-30 19:31:46 +09001296 }
Robert Greenwaltd70a3d42010-02-23 18:15:29 -08001297 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001298
Erik Kline3a5278f2017-06-24 19:29:10 +09001299 protected void handleNewUpstreamNetworkState(NetworkState ns) {
1300 mIPv6TetheringCoordinator.updateUpstreamNetworkState(ns);
Erik Klineed962a82017-07-06 19:49:35 +09001301 mOffload.updateUpstreamNetworkState(ns);
Erik Kline3a5278f2017-06-24 19:29:10 +09001302 }
1303
Erik Kline7a4ccc62018-08-27 17:26:47 +09001304 private void handleInterfaceServingStateActive(int mode, IpServer who) {
Erik Klineea9cc482017-03-10 19:35:34 +09001305 if (mNotifyList.indexOf(who) < 0) {
1306 mNotifyList.add(who);
1307 mIPv6TetheringCoordinator.addActiveDownstream(who, mode);
1308 }
1309
Erik Kline7a4ccc62018-08-27 17:26:47 +09001310 if (mode == IpServer.STATE_TETHERED) {
Erik Klineed962a82017-07-06 19:49:35 +09001311 // No need to notify OffloadController just yet as there are no
1312 // "offload-able" prefixes to pass along. This will handled
1313 // when the TISM informs Tethering of its LinkProperties.
Erik Klineea9cc482017-03-10 19:35:34 +09001314 mForwardedDownstreams.add(who);
1315 } else {
Erik Klineed962a82017-07-06 19:49:35 +09001316 mOffload.excludeDownstreamInterface(who.interfaceName());
Erik Klineea9cc482017-03-10 19:35:34 +09001317 mForwardedDownstreams.remove(who);
1318 }
Erik Kline216af6d2017-04-27 20:57:23 +09001319
1320 // If this is a Wi-Fi interface, notify WifiManager of the active serving state.
Erik Kline7a26ba32018-03-09 14:18:02 +09001321 if (who.interfaceType() == TETHERING_WIFI) {
Erik Kline216af6d2017-04-27 20:57:23 +09001322 final WifiManager mgr = getWifiManager();
1323 final String iface = who.interfaceName();
1324 switch (mode) {
Erik Kline7a4ccc62018-08-27 17:26:47 +09001325 case IpServer.STATE_TETHERED:
Erik Kline2efb8272017-05-31 15:53:53 +09001326 mgr.updateInterfaceIpState(iface, IFACE_IP_MODE_TETHERED);
Erik Kline216af6d2017-04-27 20:57:23 +09001327 break;
Erik Kline7a4ccc62018-08-27 17:26:47 +09001328 case IpServer.STATE_LOCAL_ONLY:
Erik Kline2efb8272017-05-31 15:53:53 +09001329 mgr.updateInterfaceIpState(iface, IFACE_IP_MODE_LOCAL_ONLY);
Erik Kline216af6d2017-04-27 20:57:23 +09001330 break;
1331 default:
1332 Log.wtf(TAG, "Unknown active serving mode: " + mode);
1333 break;
1334 }
1335 }
Erik Klineea9cc482017-03-10 19:35:34 +09001336 }
1337
Erik Kline7a4ccc62018-08-27 17:26:47 +09001338 private void handleInterfaceServingStateInactive(IpServer who) {
Erik Klineea9cc482017-03-10 19:35:34 +09001339 mNotifyList.remove(who);
1340 mIPv6TetheringCoordinator.removeActiveDownstream(who);
Erik Klineed962a82017-07-06 19:49:35 +09001341 mOffload.excludeDownstreamInterface(who.interfaceName());
Erik Klineea9cc482017-03-10 19:35:34 +09001342 mForwardedDownstreams.remove(who);
Erik Kline216af6d2017-04-27 20:57:23 +09001343
1344 // If this is a Wi-Fi interface, tell WifiManager of any errors.
Erik Kline7a26ba32018-03-09 14:18:02 +09001345 if (who.interfaceType() == TETHERING_WIFI) {
1346 if (who.lastError() != TETHER_ERROR_NO_ERROR) {
Erik Kline216af6d2017-04-27 20:57:23 +09001347 getWifiManager().updateInterfaceIpState(
Erik Kline2efb8272017-05-31 15:53:53 +09001348 who.interfaceName(), IFACE_IP_MODE_CONFIGURATION_ERROR);
Erik Kline216af6d2017-04-27 20:57:23 +09001349 }
1350 }
Erik Klineea9cc482017-03-10 19:35:34 +09001351 }
1352
Erik Kline3a5278f2017-06-24 19:29:10 +09001353 private void handleUpstreamNetworkMonitorCallback(int arg1, Object o) {
Erik Kline32179ff2017-07-04 18:28:11 +09001354 if (arg1 == UpstreamNetworkMonitor.NOTIFY_LOCAL_PREFIXES) {
Erik Klineed962a82017-07-06 19:49:35 +09001355 mOffload.sendOffloadExemptPrefixes((Set<IpPrefix>) o);
Erik Kline3a5278f2017-06-24 19:29:10 +09001356 return;
1357 }
1358
1359 final NetworkState ns = (NetworkState) o;
1360
1361 if (ns == null || !pertainsToCurrentUpstream(ns)) {
1362 // TODO: In future, this is where upstream evaluation and selection
1363 // could be handled for notifications which include sufficient data.
1364 // For example, after CONNECTIVITY_ACTION listening is removed, here
1365 // is where we could observe a Wi-Fi network becoming available and
1366 // passing validation.
Remi NGUYEN VAN6c02f992018-03-09 14:07:18 +09001367 if (mCurrentUpstreamIfaceSet == null) {
Erik Kline3a5278f2017-06-24 19:29:10 +09001368 // If we have no upstream interface, try to run through upstream
1369 // selection again. If, for example, IPv4 connectivity has shown up
1370 // after IPv6 (e.g., 464xlat became available) we want the chance to
1371 // notice and act accordingly.
1372 chooseUpstreamType(false);
1373 }
1374 return;
1375 }
1376
1377 switch (arg1) {
Erik Kline3a5278f2017-06-24 19:29:10 +09001378 case UpstreamNetworkMonitor.EVENT_ON_CAPABILITIES:
1379 handleNewUpstreamNetworkState(ns);
1380 break;
1381 case UpstreamNetworkMonitor.EVENT_ON_LINKPROPERTIES:
Remi NGUYEN VAN6c02f992018-03-09 14:07:18 +09001382 chooseUpstreamType(false);
Erik Kline3a5278f2017-06-24 19:29:10 +09001383 break;
1384 case UpstreamNetworkMonitor.EVENT_ON_LOST:
1385 // TODO: Re-evaluate possible upstreams. Currently upstream
1386 // reevaluation is triggered via received CONNECTIVITY_ACTION
1387 // broadcasts that result in being passed a
1388 // TetherMasterSM.CMD_UPSTREAM_CHANGED.
1389 handleNewUpstreamNetworkState(null);
1390 break;
1391 default:
1392 mLog.e("Unknown arg1 value: " + arg1);
1393 break;
1394 }
1395 }
1396
1397 class TetherModeAliveState extends State {
Erik Klineea9cc482017-03-10 19:35:34 +09001398 boolean mUpstreamWanted = false;
Erik Kline6ff17f72015-12-10 20:42:12 +09001399 boolean mTryCell = true;
Erik Klinee0cce212017-03-06 14:05:23 +09001400
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001401 @Override
1402 public void enter() {
Erik Kline1fdc2e22017-05-08 17:56:35 +09001403 // If turning on master tether settings fails, we have already
1404 // transitioned to an error state; exit early.
1405 if (!turnOnMasterTetherSettings()) {
1406 return;
1407 }
1408
markchiena6c72872018-11-13 18:34:56 +09001409 mUpstreamNetworkMonitor.startObserveAllNetworks();
Robert Greenwalt4f74d552011-12-19 16:59:31 -08001410
Erik Klinef4b6e342017-04-25 19:19:59 +09001411 // TODO: De-duplicate with updateUpstreamWanted() below.
Erik Klineea9cc482017-03-10 19:35:34 +09001412 if (upstreamWanted()) {
1413 mUpstreamWanted = true;
Erik Klineed962a82017-07-06 19:49:35 +09001414 mOffload.start();
Erik Klineea9cc482017-03-10 19:35:34 +09001415 chooseUpstreamType(true);
1416 mTryCell = false;
1417 }
Robert Greenwalt6a1967c2010-03-17 11:19:57 -07001418 }
Erik Klinefa37b2f2016-08-02 18:27:03 +09001419
Robert Greenwalt6a1967c2010-03-17 11:19:57 -07001420 @Override
1421 public void exit() {
Erik Klineed962a82017-07-06 19:49:35 +09001422 mOffload.stop();
Erik Kline6ff17f72015-12-10 20:42:12 +09001423 mUpstreamNetworkMonitor.stop();
Erik Kline22108902017-07-06 16:40:06 +09001424 notifyDownstreamsOfNewUpstreamIface(null);
Erik Klinefa37b2f2016-08-02 18:27:03 +09001425 handleNewUpstreamNetworkState(null);
markchien6ea34542019-02-27 14:56:11 +08001426 if (mTetherUpstream != null) {
1427 mTetherUpstream = null;
1428 reportUpstreamChanged(null);
1429 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001430 }
Erik Klinefa37b2f2016-08-02 18:27:03 +09001431
Erik Klineea9cc482017-03-10 19:35:34 +09001432 private boolean updateUpstreamWanted() {
1433 final boolean previousUpstreamWanted = mUpstreamWanted;
1434 mUpstreamWanted = upstreamWanted();
Erik Klinef4b6e342017-04-25 19:19:59 +09001435 if (mUpstreamWanted != previousUpstreamWanted) {
1436 if (mUpstreamWanted) {
Erik Klineed962a82017-07-06 19:49:35 +09001437 mOffload.start();
Erik Klinef4b6e342017-04-25 19:19:59 +09001438 } else {
Erik Klineed962a82017-07-06 19:49:35 +09001439 mOffload.stop();
Erik Klinef4b6e342017-04-25 19:19:59 +09001440 }
1441 }
Erik Klineea9cc482017-03-10 19:35:34 +09001442 return previousUpstreamWanted;
1443 }
1444
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001445 @Override
1446 public boolean processMessage(Message message) {
Erik Kline22108902017-07-06 16:40:06 +09001447 logMessage(this, message.what);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001448 boolean retValue = true;
1449 switch (message.what) {
Erik Klineea9cc482017-03-10 19:35:34 +09001450 case EVENT_IFACE_SERVING_STATE_ACTIVE: {
Erik Kline7a4ccc62018-08-27 17:26:47 +09001451 IpServer who = (IpServer) message.obj;
Robert Greenwalt68ea9b02012-05-10 16:58:16 -07001452 if (VDBG) Log.d(TAG, "Tether Mode requested by " + who);
Erik Klineea9cc482017-03-10 19:35:34 +09001453 handleInterfaceServingStateActive(message.arg1, who);
Erik Kline7a4ccc62018-08-27 17:26:47 +09001454 who.sendMessage(IpServer.CMD_TETHER_CONNECTION_CHANGED,
Remi NGUYEN VAN6c02f992018-03-09 14:07:18 +09001455 mCurrentUpstreamIfaceSet);
Erik Klineea9cc482017-03-10 19:35:34 +09001456 // If there has been a change and an upstream is now
1457 // desired, kick off the selection process.
1458 final boolean previousUpstreamWanted = updateUpstreamWanted();
1459 if (!previousUpstreamWanted && mUpstreamWanted) {
1460 chooseUpstreamType(true);
1461 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001462 break;
Erik Kline6e29bf02016-08-15 16:16:18 +09001463 }
Erik Klineea9cc482017-03-10 19:35:34 +09001464 case EVENT_IFACE_SERVING_STATE_INACTIVE: {
Erik Kline7a4ccc62018-08-27 17:26:47 +09001465 IpServer who = (IpServer) message.obj;
Robert Greenwalt68ea9b02012-05-10 16:58:16 -07001466 if (VDBG) Log.d(TAG, "Tether Mode unrequested by " + who);
Erik Klineea9cc482017-03-10 19:35:34 +09001467 handleInterfaceServingStateInactive(who);
1468
1469 if (mNotifyList.isEmpty()) {
Erik Kline47222fc2017-04-30 19:36:15 +09001470 // This transitions us out of TetherModeAliveState,
1471 // either to InitialState or an error state.
Erik Kline1fdc2e22017-05-08 17:56:35 +09001472 turnOffMasterTetherSettings();
1473 break;
1474 }
1475
1476 if (DBG) {
1477 Log.d(TAG, "TetherModeAlive still has " + mNotifyList.size() +
1478 " live requests:");
Erik Kline7a4ccc62018-08-27 17:26:47 +09001479 for (IpServer o : mNotifyList) {
Erik Kline1fdc2e22017-05-08 17:56:35 +09001480 Log.d(TAG, " " + o);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001481 }
1482 }
Erik Klineea9cc482017-03-10 19:35:34 +09001483 // If there has been a change and an upstream is no
1484 // longer desired, release any mobile requests.
1485 final boolean previousUpstreamWanted = updateUpstreamWanted();
1486 if (previousUpstreamWanted && !mUpstreamWanted) {
1487 mUpstreamNetworkMonitor.releaseMobileNetworkRequest();
1488 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001489 break;
Erik Kline6e29bf02016-08-15 16:16:18 +09001490 }
Erik Kline6e9a1012017-06-06 19:24:21 +09001491 case EVENT_IFACE_UPDATE_LINKPROPERTIES: {
1492 final LinkProperties newLp = (LinkProperties) message.obj;
Erik Kline7a4ccc62018-08-27 17:26:47 +09001493 if (message.arg1 == IpServer.STATE_TETHERED) {
Erik Klineed962a82017-07-06 19:49:35 +09001494 mOffload.updateDownstreamLinkProperties(newLp);
Erik Kline6e9a1012017-06-06 19:24:21 +09001495 } else {
Erik Klineed962a82017-07-06 19:49:35 +09001496 mOffload.excludeDownstreamInterface(newLp.getInterfaceName());
Erik Kline6e9a1012017-06-06 19:24:21 +09001497 }
1498 break;
1499 }
Robert Greenwalt6a1967c2010-03-17 11:19:57 -07001500 case CMD_UPSTREAM_CHANGED:
Erik Klineea9cc482017-03-10 19:35:34 +09001501 updateUpstreamWanted();
1502 if (!mUpstreamWanted) break;
1503
Erik Klinefb413432017-02-14 18:26:04 +09001504 // Need to try DUN immediately if Wi-Fi goes down.
1505 chooseUpstreamType(true);
1506 mTryCell = false;
Robert Greenwalt6a1967c2010-03-17 11:19:57 -07001507 break;
Kazuhiro Ondo01758e82011-04-30 20:10:57 -05001508 case CMD_RETRY_UPSTREAM:
Erik Klineea9cc482017-03-10 19:35:34 +09001509 updateUpstreamWanted();
1510 if (!mUpstreamWanted) break;
1511
Kazuhiro Ondo01758e82011-04-30 20:10:57 -05001512 chooseUpstreamType(mTryCell);
1513 mTryCell = !mTryCell;
1514 break;
Erik Kline00019f42016-06-30 19:31:46 +09001515 case EVENT_UPSTREAM_CALLBACK: {
Erik Klineea9cc482017-03-10 19:35:34 +09001516 updateUpstreamWanted();
Erik Kline3a5278f2017-06-24 19:29:10 +09001517 if (mUpstreamWanted) {
1518 handleUpstreamNetworkMonitorCallback(message.arg1, message.obj);
Erik Kline6ff17f72015-12-10 20:42:12 +09001519 }
1520 break;
Erik Kline00019f42016-06-30 19:31:46 +09001521 }
Kazuhiro Ondo01758e82011-04-30 20:10:57 -05001522 default:
1523 retValue = false;
1524 break;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001525 }
1526 return retValue;
1527 }
1528 }
1529
Wink Saville64c42ca2011-04-18 14:55:10 -07001530 class ErrorState extends State {
Erik Kline8351faa2017-04-17 16:47:23 +09001531 private int mErrorNotification;
1532
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001533 @Override
1534 public boolean processMessage(Message message) {
1535 boolean retValue = true;
1536 switch (message.what) {
Erik Klineea9cc482017-03-10 19:35:34 +09001537 case EVENT_IFACE_SERVING_STATE_ACTIVE:
Erik Kline7a4ccc62018-08-27 17:26:47 +09001538 IpServer who = (IpServer) message.obj;
Robert Greenwalt6a1967c2010-03-17 11:19:57 -07001539 who.sendMessage(mErrorNotification);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001540 break;
Yohei, Oshima977aad52016-12-08 13:39:20 +09001541 case CMD_CLEAR_ERROR:
Erik Kline7a26ba32018-03-09 14:18:02 +09001542 mErrorNotification = TETHER_ERROR_NO_ERROR;
Yohei, Oshima977aad52016-12-08 13:39:20 +09001543 transitionTo(mInitialState);
1544 break;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001545 default:
1546 retValue = false;
1547 }
1548 return retValue;
1549 }
Erik Kline8351faa2017-04-17 16:47:23 +09001550
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001551 void notify(int msgType) {
1552 mErrorNotification = msgType;
Erik Kline7a4ccc62018-08-27 17:26:47 +09001553 for (IpServer ipServer : mNotifyList) {
1554 ipServer.sendMessage(msgType);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001555 }
1556 }
1557
1558 }
Erik Kline8351faa2017-04-17 16:47:23 +09001559
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001560 class SetIpForwardingEnabledErrorState extends ErrorState {
1561 @Override
1562 public void enter() {
1563 Log.e(TAG, "Error in setIpForwardingEnabled");
Erik Kline7a4ccc62018-08-27 17:26:47 +09001564 notify(IpServer.CMD_IP_FORWARDING_ENABLE_ERROR);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001565 }
1566 }
1567
1568 class SetIpForwardingDisabledErrorState extends ErrorState {
1569 @Override
1570 public void enter() {
1571 Log.e(TAG, "Error in setIpForwardingDisabled");
Erik Kline7a4ccc62018-08-27 17:26:47 +09001572 notify(IpServer.CMD_IP_FORWARDING_DISABLE_ERROR);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001573 }
1574 }
1575
1576 class StartTetheringErrorState extends ErrorState {
1577 @Override
1578 public void enter() {
1579 Log.e(TAG, "Error in startTethering");
Erik Kline7a4ccc62018-08-27 17:26:47 +09001580 notify(IpServer.CMD_START_TETHERING_ERROR);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001581 try {
Chia-chi Yehc9338302011-05-11 16:35:13 -07001582 mNMService.setIpForwardingEnabled(false);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001583 } catch (Exception e) {}
1584 }
1585 }
1586
1587 class StopTetheringErrorState extends ErrorState {
1588 @Override
1589 public void enter() {
1590 Log.e(TAG, "Error in stopTethering");
Erik Kline7a4ccc62018-08-27 17:26:47 +09001591 notify(IpServer.CMD_STOP_TETHERING_ERROR);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001592 try {
Chia-chi Yehc9338302011-05-11 16:35:13 -07001593 mNMService.setIpForwardingEnabled(false);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001594 } catch (Exception e) {}
1595 }
1596 }
1597
1598 class SetDnsForwardersErrorState extends ErrorState {
1599 @Override
1600 public void enter() {
1601 Log.e(TAG, "Error in setDnsForwarders");
Erik Kline7a4ccc62018-08-27 17:26:47 +09001602 notify(IpServer.CMD_SET_DNS_FORWARDERS_ERROR);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001603 try {
Chia-chi Yehc9338302011-05-11 16:35:13 -07001604 mNMService.stopTethering();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001605 } catch (Exception e) {}
1606 try {
Chia-chi Yehc9338302011-05-11 16:35:13 -07001607 mNMService.setIpForwardingEnabled(false);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001608 } catch (Exception e) {}
1609 }
1610 }
Erik Klineed962a82017-07-06 19:49:35 +09001611
1612 // A wrapper class to handle multiple situations where several calls to
1613 // the OffloadController need to happen together.
1614 //
1615 // TODO: This suggests that the interface between OffloadController and
1616 // Tethering is in need of improvement. Refactor these calls into the
1617 // OffloadController implementation.
1618 class OffloadWrapper {
1619 public void start() {
1620 mOffloadController.start();
1621 sendOffloadExemptPrefixes();
1622 }
1623
1624 public void stop() {
1625 mOffloadController.stop();
1626 }
1627
1628 public void updateUpstreamNetworkState(NetworkState ns) {
1629 mOffloadController.setUpstreamLinkProperties(
1630 (ns != null) ? ns.linkProperties : null);
1631 }
1632
1633 public void updateDownstreamLinkProperties(LinkProperties newLp) {
1634 // Update the list of offload-exempt prefixes before adding
1635 // new prefixes on downstream interfaces to the offload HAL.
1636 sendOffloadExemptPrefixes();
1637 mOffloadController.notifyDownstreamLinkProperties(newLp);
1638 }
1639
1640 public void excludeDownstreamInterface(String ifname) {
1641 // This and other interfaces may be in local-only hotspot mode;
1642 // resend all local prefixes to the OffloadController.
1643 sendOffloadExemptPrefixes();
1644 mOffloadController.removeDownstreamInterface(ifname);
1645 }
1646
1647 public void sendOffloadExemptPrefixes() {
1648 sendOffloadExemptPrefixes(mUpstreamNetworkMonitor.getLocalPrefixes());
1649 }
1650
1651 public void sendOffloadExemptPrefixes(final Set<IpPrefix> localPrefixes) {
1652 // Add in well-known minimum set.
1653 PrefixUtils.addNonForwardablePrefixes(localPrefixes);
1654 // Add tragically hardcoded prefixes.
1655 localPrefixes.add(PrefixUtils.DEFAULT_WIFI_P2P_PREFIX);
1656
1657 // Maybe add prefixes or addresses for downstreams, depending on
1658 // the IP serving mode of each.
Erik Kline7a4ccc62018-08-27 17:26:47 +09001659 for (IpServer ipServer : mNotifyList) {
1660 final LinkProperties lp = ipServer.linkProperties();
Erik Klineed962a82017-07-06 19:49:35 +09001661
Erik Kline7a4ccc62018-08-27 17:26:47 +09001662 switch (ipServer.servingMode()) {
1663 case IpServer.STATE_UNAVAILABLE:
1664 case IpServer.STATE_AVAILABLE:
Erik Klineed962a82017-07-06 19:49:35 +09001665 // No usable LinkProperties in these states.
1666 continue;
Erik Kline7a4ccc62018-08-27 17:26:47 +09001667 case IpServer.STATE_TETHERED:
Erik Klineed962a82017-07-06 19:49:35 +09001668 // Only add IPv4 /32 and IPv6 /128 prefixes. The
1669 // directly-connected prefixes will be sent as
1670 // downstream "offload-able" prefixes.
1671 for (LinkAddress addr : lp.getAllLinkAddresses()) {
1672 final InetAddress ip = addr.getAddress();
1673 if (ip.isLinkLocalAddress()) continue;
1674 localPrefixes.add(PrefixUtils.ipAddressAsPrefix(ip));
1675 }
1676 break;
Erik Kline7a4ccc62018-08-27 17:26:47 +09001677 case IpServer.STATE_LOCAL_ONLY:
Erik Klineed962a82017-07-06 19:49:35 +09001678 // Add prefixes covering all local IPs.
1679 localPrefixes.addAll(PrefixUtils.localPrefixesFrom(lp));
1680 break;
1681 }
1682 }
1683
1684 mOffloadController.setLocalPrefixes(localPrefixes);
1685 }
1686 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001687 }
1688
markchiena6c72872018-11-13 18:34:56 +09001689 public void systemReady() {
1690 mUpstreamNetworkMonitor.startTrackDefaultNetwork(mDeps.getDefaultNetworkRequest());
1691 }
1692
markchienf2731272019-01-16 17:44:13 +08001693 /** Get the latest value of the tethering entitlement check. */
markchien9554abf2019-03-06 16:25:00 +08001694 public void getLatestTetheringEntitlementResult(int type, ResultReceiver receiver,
markchienf2731272019-01-16 17:44:13 +08001695 boolean showEntitlementUi) {
1696 if (receiver != null) {
markchien9554abf2019-03-06 16:25:00 +08001697 mEntitlementMgr.getLatestTetheringEntitlementResult(type, receiver, showEntitlementUi);
markchienf2731272019-01-16 17:44:13 +08001698 }
1699 }
1700
markchien6ea34542019-02-27 14:56:11 +08001701 /** Register tethering event callback */
1702 public void registerTetheringEventCallback(ITetheringEventCallback callback) {
1703 mHandler.post(() -> {
1704 try {
1705 callback.onUpstreamChanged(mTetherUpstream);
1706 } catch (RemoteException e) {
1707 // Not really very much to do here.
1708 }
1709 mTetheringEventCallbacks.register(callback);
1710 });
1711 }
1712
1713 /** Unregister tethering event callback */
1714 public void unregisterTetheringEventCallback(ITetheringEventCallback callback) {
1715 mHandler.post(() -> {
1716 mTetheringEventCallbacks.unregister(callback);
1717 });
1718 }
1719
1720 private void reportUpstreamChanged(Network network) {
1721 final int length = mTetheringEventCallbacks.beginBroadcast();
1722 try {
1723 for (int i = 0; i < length; i++) {
1724 try {
1725 mTetheringEventCallbacks.getBroadcastItem(i).onUpstreamChanged(network);
1726 } catch (RemoteException e) {
1727 // Not really very much to do here.
1728 }
1729 }
1730 } finally {
1731 mTetheringEventCallbacks.finishBroadcast();
1732 }
1733 }
1734
Christopher Wiley499a57a2016-05-16 16:19:07 -07001735 @Override
Lorenzo Colittie3805462015-06-03 11:18:24 +09001736 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Christopher Wiley499a57a2016-05-16 16:19:07 -07001737 // Binder.java closes the resource for us.
1738 @SuppressWarnings("resource")
Lorenzo Colittie3805462015-06-03 11:18:24 +09001739 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001740 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001741
Lorenzo Colittie3805462015-06-03 11:18:24 +09001742 pw.println("Tethering:");
1743 pw.increaseIndent();
Lorenzo Colittie3805462015-06-03 11:18:24 +09001744
Erik Kline9db1b542017-03-16 14:10:27 +09001745 pw.println("Configuration:");
1746 pw.increaseIndent();
1747 final TetheringConfiguration cfg = mConfig;
1748 cfg.dump(pw);
1749 pw.decreaseIndent();
1750
1751 synchronized (mPublicSync) {
Robert Greenwaltb4453622011-11-03 16:01:40 -07001752 pw.println("Tether state:");
Lorenzo Colittie3805462015-06-03 11:18:24 +09001753 pw.increaseIndent();
Christopher Wileyd985dde2016-05-31 10:44:35 -07001754 for (int i = 0; i < mTetherStates.size(); i++) {
1755 final String iface = mTetherStates.keyAt(i);
1756 final TetherState tetherState = mTetherStates.valueAt(i);
1757 pw.print(iface + " - ");
1758
Hugo Benichib55fb222017-03-10 14:20:57 +09001759 switch (tetherState.lastState) {
Erik Kline7a4ccc62018-08-27 17:26:47 +09001760 case IpServer.STATE_UNAVAILABLE:
Christopher Wileyd985dde2016-05-31 10:44:35 -07001761 pw.print("UnavailableState");
1762 break;
Erik Kline7a4ccc62018-08-27 17:26:47 +09001763 case IpServer.STATE_AVAILABLE:
Christopher Wileyd985dde2016-05-31 10:44:35 -07001764 pw.print("AvailableState");
1765 break;
Erik Kline7a4ccc62018-08-27 17:26:47 +09001766 case IpServer.STATE_TETHERED:
Christopher Wileyd985dde2016-05-31 10:44:35 -07001767 pw.print("TetheredState");
1768 break;
Erik Kline7a4ccc62018-08-27 17:26:47 +09001769 case IpServer.STATE_LOCAL_ONLY:
Erik Klineea9cc482017-03-10 19:35:34 +09001770 pw.print("LocalHotspotState");
1771 break;
Christopher Wileyd985dde2016-05-31 10:44:35 -07001772 default:
1773 pw.print("UnknownState");
1774 break;
1775 }
Hugo Benichib55fb222017-03-10 14:20:57 +09001776 pw.println(" - lastError = " + tetherState.lastError);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001777 }
Erik Klineea9cc482017-03-10 19:35:34 +09001778 pw.println("Upstream wanted: " + upstreamWanted());
Remi NGUYEN VAN6c02f992018-03-09 14:07:18 +09001779 pw.println("Current upstream interface(s): " + mCurrentUpstreamIfaceSet);
Lorenzo Colittie3805462015-06-03 11:18:24 +09001780 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001781 }
Erik Kline1fdc2e22017-05-08 17:56:35 +09001782
Lorenzo Colittic2519c52017-07-13 01:48:26 +09001783 pw.println("Hardware offload:");
1784 pw.increaseIndent();
1785 mOffloadController.dump(pw);
1786 pw.decreaseIndent();
1787
Erik Kline1fdc2e22017-05-08 17:56:35 +09001788 pw.println("Log:");
1789 pw.increaseIndent();
Erik Kline7747fd42017-05-12 16:52:48 +09001790 if (argsContain(args, SHORT_ARG)) {
1791 pw.println("<log removed for brevity>");
1792 } else {
1793 mLog.dump(fd, pw, args);
1794 }
Erik Kline1fdc2e22017-05-08 17:56:35 +09001795 pw.decreaseIndent();
1796
Lorenzo Colittie3805462015-06-03 11:18:24 +09001797 pw.decreaseIndent();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001798 }
Christopher Wileye03fb442016-05-18 13:45:20 -07001799
Erik Kline7747fd42017-05-12 16:52:48 +09001800 private static boolean argsContain(String[] args, String target) {
1801 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001802 if (target.equals(arg)) return true;
Erik Kline7747fd42017-05-12 16:52:48 +09001803 }
1804 return false;
1805 }
1806
Erik Kline7a4ccc62018-08-27 17:26:47 +09001807 private IpServer.Callback makeControlCallback() {
1808 return new IpServer.Callback() {
Erik Kline6e9a1012017-06-06 19:24:21 +09001809 @Override
Erik Kline7a4ccc62018-08-27 17:26:47 +09001810 public void updateInterfaceState(IpServer who, int state, int lastError) {
1811 notifyInterfaceStateChange(who, state, lastError);
Erik Kline6e9a1012017-06-06 19:24:21 +09001812 }
1813
1814 @Override
Erik Kline7a4ccc62018-08-27 17:26:47 +09001815 public void updateLinkProperties(IpServer who, LinkProperties newLp) {
1816 notifyLinkPropertiesChanged(who, newLp);
Erik Kline6e9a1012017-06-06 19:24:21 +09001817 }
1818 };
1819 }
1820
1821 // TODO: Move into TetherMasterSM.
Erik Kline7a4ccc62018-08-27 17:26:47 +09001822 private void notifyInterfaceStateChange(IpServer who, int state, int error) {
1823 final String iface = who.interfaceName();
Christopher Wileyd985dde2016-05-31 10:44:35 -07001824 synchronized (mPublicSync) {
Erik Kline216af6d2017-04-27 20:57:23 +09001825 final TetherState tetherState = mTetherStates.get(iface);
Erik Kline7a4ccc62018-08-27 17:26:47 +09001826 if (tetherState != null && tetherState.ipServer.equals(who)) {
Hugo Benichib55fb222017-03-10 14:20:57 +09001827 tetherState.lastState = state;
1828 tetherState.lastError = error;
Christopher Wileyd985dde2016-05-31 10:44:35 -07001829 } else {
1830 if (DBG) Log.d(TAG, "got notification from stale iface " + iface);
1831 }
1832 }
1833
Erik Kline7747fd42017-05-12 16:52:48 +09001834 mLog.log(String.format("OBSERVED iface=%s state=%s error=%s", iface, state, error));
Christopher Wileyd985dde2016-05-31 10:44:35 -07001835
Christopher Wileydeebfec2016-09-16 11:14:36 -07001836 try {
1837 // Notify that we're tethering (or not) this interface.
1838 // This is how data saver for instance knows if the user explicitly
1839 // turned on tethering (thus keeping us from being in data saver mode).
Erik Kline7a4ccc62018-08-27 17:26:47 +09001840 mPolicyManager.onTetheringChanged(iface, state == IpServer.STATE_TETHERED);
Christopher Wileydeebfec2016-09-16 11:14:36 -07001841 } catch (RemoteException e) {
1842 // Not really very much we can do here.
1843 }
1844
Yohei, Oshima977aad52016-12-08 13:39:20 +09001845 // If TetherMasterSM is in ErrorState, TetherMasterSM stays there.
1846 // Thus we give a chance for TetherMasterSM to recover to InitialState
1847 // by sending CMD_CLEAR_ERROR
Erik Kline7a26ba32018-03-09 14:18:02 +09001848 if (error == TETHER_ERROR_MASTER_ERROR) {
Yohei, Oshima977aad52016-12-08 13:39:20 +09001849 mTetherMasterSM.sendMessage(TetherMasterSM.CMD_CLEAR_ERROR, who);
1850 }
Erik Klineea9cc482017-03-10 19:35:34 +09001851 int which;
Christopher Wileyd985dde2016-05-31 10:44:35 -07001852 switch (state) {
Erik Kline7a4ccc62018-08-27 17:26:47 +09001853 case IpServer.STATE_UNAVAILABLE:
1854 case IpServer.STATE_AVAILABLE:
Erik Klineea9cc482017-03-10 19:35:34 +09001855 which = TetherMasterSM.EVENT_IFACE_SERVING_STATE_INACTIVE;
Christopher Wileyd985dde2016-05-31 10:44:35 -07001856 break;
Erik Kline7a4ccc62018-08-27 17:26:47 +09001857 case IpServer.STATE_TETHERED:
1858 case IpServer.STATE_LOCAL_ONLY:
Erik Klineea9cc482017-03-10 19:35:34 +09001859 which = TetherMasterSM.EVENT_IFACE_SERVING_STATE_ACTIVE;
Christopher Wileyd985dde2016-05-31 10:44:35 -07001860 break;
Erik Klineea9cc482017-03-10 19:35:34 +09001861 default:
1862 Log.wtf(TAG, "Unknown interface state: " + state);
1863 return;
Christopher Wileyd985dde2016-05-31 10:44:35 -07001864 }
Erik Klineea9cc482017-03-10 19:35:34 +09001865 mTetherMasterSM.sendMessage(which, state, 0, who);
Christopher Wileyd985dde2016-05-31 10:44:35 -07001866 sendTetherStateChangedBroadcast();
1867 }
1868
Erik Kline7a4ccc62018-08-27 17:26:47 +09001869 private void notifyLinkPropertiesChanged(IpServer who, LinkProperties newLp) {
1870 final String iface = who.interfaceName();
Erik Kline6e9a1012017-06-06 19:24:21 +09001871 final int state;
1872 synchronized (mPublicSync) {
1873 final TetherState tetherState = mTetherStates.get(iface);
Erik Kline7a4ccc62018-08-27 17:26:47 +09001874 if (tetherState != null && tetherState.ipServer.equals(who)) {
Erik Kline6e9a1012017-06-06 19:24:21 +09001875 state = tetherState.lastState;
1876 } else {
1877 mLog.log("got notification from stale iface " + iface);
1878 return;
1879 }
1880 }
1881
Erik Kline7fd696c2017-06-12 18:20:08 +09001882 mLog.log(String.format(
1883 "OBSERVED LinkProperties update iface=%s state=%s lp=%s",
Erik Kline7a4ccc62018-08-27 17:26:47 +09001884 iface, IpServer.getStateString(state), newLp));
Erik Kline6e9a1012017-06-06 19:24:21 +09001885 final int which = TetherMasterSM.EVENT_IFACE_UPDATE_LINKPROPERTIES;
1886 mTetherMasterSM.sendMessage(which, state, 0, newLp);
1887 }
1888
Erik Kline4dd9bb82017-04-26 11:11:07 +09001889 private void maybeTrackNewInterfaceLocked(final String iface) {
1890 // If we don't care about this type of interface, ignore.
1891 final int interfaceType = ifaceNameToType(iface);
Erik Kline7a26ba32018-03-09 14:18:02 +09001892 if (interfaceType == TETHERING_INVALID) {
Erik Kline4dd9bb82017-04-26 11:11:07 +09001893 mLog.log(iface + " is not a tetherable iface, ignoring");
1894 return;
1895 }
Erik Klinea9cde8b2017-06-20 21:18:31 +09001896 maybeTrackNewInterfaceLocked(iface, interfaceType);
1897 }
Erik Kline4dd9bb82017-04-26 11:11:07 +09001898
Erik Klinea9cde8b2017-06-20 21:18:31 +09001899 private void maybeTrackNewInterfaceLocked(final String iface, int interfaceType) {
Erik Kline4dd9bb82017-04-26 11:11:07 +09001900 // If we have already started a TISM for this interface, skip.
1901 if (mTetherStates.containsKey(iface)) {
1902 mLog.log("active iface (" + iface + ") reported as added, ignoring");
1903 return;
1904 }
1905
1906 mLog.log("adding TetheringInterfaceStateMachine for: " + iface);
1907 final TetherState tetherState = new TetherState(
Erik Kline7a4ccc62018-08-27 17:26:47 +09001908 new IpServer(iface, mLooper, interfaceType, mLog, mNMService, mStatsService,
1909 makeControlCallback(), mConfig.enableLegacyDhcpServer,
Remi NGUYEN VAN5db454c2019-02-14 18:04:20 +09001910 mDeps.getIpServerDependencies()));
Christopher Wileyd985dde2016-05-31 10:44:35 -07001911 mTetherStates.put(iface, tetherState);
Erik Kline7a4ccc62018-08-27 17:26:47 +09001912 tetherState.ipServer.start();
Christopher Wileye03fb442016-05-18 13:45:20 -07001913 }
Erik Kline3e756652017-01-17 13:42:19 +09001914
Erik Kline4dd9bb82017-04-26 11:11:07 +09001915 private void stopTrackingInterfaceLocked(final String iface) {
1916 final TetherState tetherState = mTetherStates.get(iface);
1917 if (tetherState == null) {
1918 mLog.log("attempting to remove unknown iface (" + iface + "), ignoring");
1919 return;
1920 }
Erik Kline7a4ccc62018-08-27 17:26:47 +09001921 tetherState.ipServer.stop();
Erik Kline4dd9bb82017-04-26 11:11:07 +09001922 mLog.log("removing TetheringInterfaceStateMachine for: " + iface);
1923 mTetherStates.remove(iface);
1924 }
1925
Erik Kline3e756652017-01-17 13:42:19 +09001926 private static String[] copy(String[] strarray) {
1927 return Arrays.copyOf(strarray, strarray.length);
1928 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001929}