blob: 383b12cda5505ca0363251c500e96a8418915b4a [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 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;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090026import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
27import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070030import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Amith Yamasani15e472352015-04-24 19:06:07 -070031import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070033
Wenchao Tongf5ea3402015-03-04 13:26:38 -080034import android.annotation.Nullable;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070035import android.app.AlarmManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070036import android.app.Notification;
37import android.app.NotificationManager;
38import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070039import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.content.ContentResolver;
41import android.content.Context;
42import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070043import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070045import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090046import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070047import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.net.ConnectivityManager;
49import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070050import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070051import android.net.INetworkPolicyListener;
52import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070053import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080054import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070055import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070056import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070057import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070058import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070059import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070061import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070062import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070063import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070064import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070065import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070066import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070067import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040068import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070069import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040070import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040071import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.os.Binder;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070073import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040074import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070076import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070077import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070078import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.Looper;
80import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070081import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070082import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070083import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070084import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070085import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070086import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070088import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040089import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070091import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070092import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070093import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070094import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080095import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070096import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -050097import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070098import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070099import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
Wink Savilleab9321d2013-06-29 21:10:57 -0700101import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400102import com.android.internal.annotations.GuardedBy;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700103import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700104import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700105import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700106import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800107import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700108import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700109import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700110import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700111import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700112import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700113import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400114import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900115import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700116import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400117import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400118import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700119import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800120import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700121import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700122import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700123import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700124import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700125import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700126
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700127import org.xmlpull.v1.XmlPullParser;
128import org.xmlpull.v1.XmlPullParserException;
129
130import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700132import java.io.FileNotFoundException;
133import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700134import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700136import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700137import java.net.InetAddress;
138import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700139import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700140import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700141import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700142import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700143import java.util.HashSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500144import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700145import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700146import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700147import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700148import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149
150/**
151 * @hide
152 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800153public class ConnectivityService extends IConnectivityManager.Stub
154 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700155 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700157 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700158 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
Jake Hamby786e71a2014-02-06 14:43:50 -0800160 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700161
Jeff Sharkey899223b2012-08-04 15:24:58 -0700162 // TODO: create better separation between radio types and network types
163
Robert Greenwalt42acef32009-08-12 16:08:25 -0700164 // how long to wait before switching back to a radio's default network
165 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
166 // system property that can override the above value
167 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
168 "android.telephony.apn-restore";
169
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900170 // How long to wait before putting up a "This network doesn't have an Internet connection,
171 // connect anyway?" dialog after the user selects a network that doesn't validate.
172 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
173
Jeremy Joslin79294842014-12-03 17:15:28 -0800174 // How long to delay to removal of a pending intent based request.
175 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
176 private final int mReleasePendingIntentDelayMs;
177
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800178 private Tethering mTethering;
179
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700180 private final PermissionMonitor mPermissionMonitor;
181
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700182 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700183
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700184 @GuardedBy("mVpns")
185 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700186
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700187 private boolean mLockdownEnabled;
188 private LockdownVpnTracker mLockdownTracker;
189
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700190 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
191 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700192 /** Currently active network rules by UID. */
193 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700194 /** Set of ifaces that are costly. */
195 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700196
Erik Klineda4bfa82015-04-30 12:58:40 +0900197 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700199 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700200 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800202 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
204 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700205 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700207 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800208 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700209 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700210
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700211 private String mCurrentTcpBufferSizes;
212
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700213 private static final int ENABLED = 1;
214 private static final int DISABLED = 0;
215
Paul Jensenb10e37f2014-11-25 12:33:08 -0500216 // Arguments to rematchNetworkAndRequests()
217 private enum NascentState {
218 // Indicates a network was just validated for the first time. If the network is found to
219 // be unwanted (i.e. not satisfy any NetworkRequests) it is torn down.
220 JUST_VALIDATED,
221 // Indicates a network was not validated for the first time immediately prior to this call.
222 NOT_JUST_VALIDATED
223 };
224 private enum ReapUnvalidatedNetworks {
225 // Tear down unvalidated networks that have no chance (i.e. even if validated) of becoming
226 // the highest scoring network satisfying a NetworkRequest. This should be passed when it's
227 // known that there may be unvalidated networks that could potentially be reaped, and when
228 // all networks have been rematched against all NetworkRequests.
229 REAP,
230 // Don't reap unvalidated networks. This should be passed when it's known that there are
231 // no unvalidated networks that could potentially be reaped, and when some networks have
232 // not yet been rematched against all NetworkRequests.
233 DONT_REAP
234 };
235
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700236 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700237 * used internally to change our mobile data enabled flag
238 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700239 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700240
241 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700242 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700243 * from one net to another. Clear happens when we get a new
244 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
245 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700246 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700247 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700248
Robert Greenwalt434203a2010-10-11 16:00:27 -0700249 /**
250 * used internally to reload global proxy settings
251 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700252 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700253
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700254 /**
Wink Saville628b0852011-08-04 15:01:58 -0700255 * used internally to send a sticky broadcast delayed.
256 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700257 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700258
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700259 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400260 * PAC manager has received new port.
261 */
262 private static final int EVENT_PROXY_HAS_CHANGED = 16;
263
Robert Greenwalte049c232014-04-11 15:53:27 -0700264 /**
265 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700266 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700267 */
268 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
269
Robert Greenwalt7b816022014-04-18 15:25:25 -0700270 /**
271 * used internally when registering NetworkAgents
272 * obj = Messenger
273 */
274 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
275
Robert Greenwalt9258c642014-03-26 16:47:06 -0700276 /**
277 * used to add a network request
278 * includes a NetworkRequestInfo
279 */
280 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
281
282 /**
283 * indicates a timeout period is over - check if we had a network yet or not
284 * and if not, call the timeout calback (but leave the request live until they
285 * cancel it.
286 * includes a NetworkRequestInfo
287 */
288 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
289
290 /**
291 * used to add a network listener - no request
292 * includes a NetworkRequestInfo
293 */
294 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
295
296 /**
297 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400298 * arg1 = UID of caller
299 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700300 */
301 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
302
Robert Greenwalta67be032014-05-16 15:49:14 -0700303 /**
304 * used internally when registering NetworkFactories
305 * obj = Messenger
306 */
307 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
308
Robert Greenwalt27711812014-06-25 16:45:57 -0700309 /**
310 * used internally to expire a wakelock when transitioning
311 * from one net to another. Expire happens when we fail to find
312 * a new network (typically after 1 minute) -
313 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
314 * a replacement network.
315 */
316 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
317
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700318 /**
319 * Used internally to indicate the system is ready.
320 */
321 private static final int EVENT_SYSTEM_READY = 25;
322
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800323 /**
324 * used to add a network request with a pending intent
325 * includes a NetworkRequestInfo
326 */
327 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
328
329 /**
330 * used to remove a pending intent and its associated network request.
331 * arg1 = UID of caller
332 * obj = PendingIntent
333 */
334 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
335
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900336 /**
337 * used to specify whether a network should be used even if unvalidated.
338 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
339 * arg2 = whether to remember this choice in the future (1 or 0)
340 * obj = network
341 */
342 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
343
344 /**
345 * used to ask the user to confirm a connection to an unvalidated network.
346 * obj = network
347 */
348 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700349
Erik Klineda4bfa82015-04-30 12:58:40 +0900350 /**
351 * used internally to (re)configure mobile data always-on settings.
352 */
353 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
354
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700355 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700356 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700357 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700358 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700359
Mike Lockwood0f79b542009-08-14 14:18:49 -0400360 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800361 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400362
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700363 private PowerManager.WakeLock mNetTransitionWakeLock;
364 private String mNetTransitionWakeLockCausedBy = "";
365 private int mNetTransitionWakeLockSerialNumber;
366 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800367 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700368
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700369 private InetAddress mDefaultDns;
370
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700371 // used in DBG mode to track inet condition reports
372 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
373 private ArrayList mInetLog;
374
Robert Greenwalt434203a2010-10-11 16:00:27 -0700375 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400376 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700377 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700378 private boolean mDefaultProxyDisabled = false;
379
Robert Greenwalt434203a2010-10-11 16:00:27 -0700380 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400381 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700382
Jason Monk602b2322013-07-03 17:04:33 -0400383 private PacManager mPacManager = null;
384
Erik Klineda4bfa82015-04-30 12:58:40 +0900385 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700386
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400387 private UserManager mUserManager;
388
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700389 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700390 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700391
Robert Greenwalt50393202011-06-21 17:26:14 -0700392 // the set of network types that can only be enabled by system/sig apps
393 List mProtectedNetworks;
394
John Spurlockbf991a82013-06-24 14:20:23 -0400395 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700396
Wink Savilleab9321d2013-06-29 21:10:57 -0700397 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400398
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700399 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
400 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700401 private final static int MAX_NET_ID = 65535;
402 private int mNextNetId = MIN_NET_ID;
403
Robert Greenwalt34524f02014-05-18 16:22:10 -0700404 // sequence number of NetworkRequests
405 private int mNextNetworkRequestId = 1;
406
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700407 /**
408 * Implements support for the legacy "one network per network type" model.
409 *
410 * We used to have a static array of NetworkStateTrackers, one for each
411 * network type, but that doesn't work any more now that we can have,
412 * for example, more that one wifi network. This class stores all the
413 * NetworkAgentInfo objects that support a given type, but the legacy
414 * API will only see the first one.
415 *
416 * It serves two main purposes:
417 *
418 * 1. Provide information about "the network for a given type" (since this
419 * API only supports one).
420 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
421 * the first network for a given type changes, or if the default network
422 * changes.
423 */
424 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900425
426 private static final boolean DBG = true;
427 private static final boolean VDBG = false;
428 private static final String TAG = "CSLegacyTypeTracker";
429
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700430 /**
431 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
432 * Each list holds references to all NetworkAgentInfos that are used to
433 * satisfy requests for that network type.
434 *
435 * This array is built out at startup such that an unsupported network
436 * doesn't get an ArrayList instance, making this a tristate:
437 * unsupported, supported but not active and active.
438 *
439 * The actual lists are populated when we scan the network types that
440 * are supported on this device.
441 */
442 private ArrayList<NetworkAgentInfo> mTypeLists[];
443
444 public LegacyTypeTracker() {
445 mTypeLists = (ArrayList<NetworkAgentInfo>[])
446 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
447 }
448
449 public void addSupportedType(int type) {
450 if (mTypeLists[type] != null) {
451 throw new IllegalStateException(
452 "legacy list for type " + type + "already initialized");
453 }
454 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
455 }
456
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700457 public boolean isTypeSupported(int type) {
458 return isNetworkTypeValid(type) && mTypeLists[type] != null;
459 }
460
461 public NetworkAgentInfo getNetworkForType(int type) {
462 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
463 return mTypeLists[type].get(0);
464 } else {
465 return null;
466 }
467 }
468
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900469 private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type,
470 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900471 if (DBG) {
472 log("Sending " + (connected ? "connected" : "disconnected") +
473 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900474 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900475 }
476 }
477
478 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700479 public void add(int type, NetworkAgentInfo nai) {
480 if (!isTypeSupported(type)) {
481 return; // Invalid network type.
482 }
483 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
484
485 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
486 if (list.contains(nai)) {
487 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
488 return;
489 }
490
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900491 list.add(nai);
492
493 // Send a broadcast if this is the first network of its type or if it's the default.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900494 final boolean isDefaultNetwork = isDefaultNetwork(nai);
495 if (list.size() == 1 || isDefaultNetwork) {
496 maybeLogBroadcast(nai, true, type, isDefaultNetwork);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700497 sendLegacyNetworkBroadcast(nai, true, type);
498 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700499 }
500
Lorenzo Colittia793a672014-07-31 23:20:17 +0900501 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900502 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900503 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
504 if (list == null || list.isEmpty()) {
505 return;
506 }
507
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900508 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900509
510 if (!list.remove(nai)) {
511 return;
512 }
513
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900514 if (wasFirstNetwork || wasDefault) {
515 maybeLogBroadcast(nai, false, type, wasDefault);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900516 sendLegacyNetworkBroadcast(nai, false, type);
517 }
518
519 if (!list.isEmpty() && wasFirstNetwork) {
520 if (DBG) log("Other network available for type " + type +
521 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900522 final NetworkAgentInfo replacement = list.get(0);
523 maybeLogBroadcast(replacement, false, type, isDefaultNetwork(replacement));
524 sendLegacyNetworkBroadcast(replacement, false, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900525 }
526 }
527
528 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900529 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
530 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700531 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900532 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700533 }
534 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700535
Lorenzo Colittia793a672014-07-31 23:20:17 +0900536 private String naiToString(NetworkAgentInfo nai) {
537 String name = (nai != null) ? nai.name() : "null";
538 String state = (nai.networkInfo != null) ?
539 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
540 "???/???";
541 return name + " " + state;
542 }
543
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700544 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900545 pw.println("mLegacyTypeTracker:");
546 pw.increaseIndent();
547 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700548 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900549 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700550 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900551 pw.println();
552 pw.println("Current state:");
553 pw.increaseIndent();
554 for (int type = 0; type < mTypeLists.length; type++) {
555 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
556 for (NetworkAgentInfo nai : mTypeLists[type]) {
557 pw.println(type + " " + naiToString(nai));
558 }
559 }
560 pw.decreaseIndent();
561 pw.decreaseIndent();
562 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700563 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900564
565 // This class needs its own log method because it has a different TAG.
566 private void log(String s) {
567 Slog.d(TAG, s);
568 }
569
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700570 }
571 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
572
Jeff Sharkey899223b2012-08-04 15:24:58 -0700573 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700574 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800575 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800576
Erik Klineda4bfa82015-04-30 12:58:40 +0900577 mDefaultRequest = createInternetRequestForTransport(-1);
578 mNetworkRequests.put(mDefaultRequest, new NetworkRequestInfo(
579 null, mDefaultRequest, new Binder(), NetworkRequestInfo.REQUEST));
580
581 mDefaultMobileDataRequest = createInternetRequestForTransport(
582 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700583
Wink Savillebb08caf2010-09-02 19:23:52 -0700584 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
585 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700586 mHandler = new InternalHandler(handlerThread.getLooper());
587 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700588
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800589 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800590 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
591 String id = Settings.Secure.getString(context.getContentResolver(),
592 Settings.Secure.ANDROID_ID);
593 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700594 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800595 SystemProperties.set("net.hostname", name);
596 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800597 }
598
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700599 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700600 String dns = Settings.Global.getString(context.getContentResolver(),
601 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700602 if (dns == null || dns.length() == 0) {
603 dns = context.getResources().getString(
604 com.android.internal.R.string.config_default_dns_server);
605 }
606 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800607 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
608 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800609 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700610 }
611
Jeremy Joslin79294842014-12-03 17:15:28 -0800612 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
613 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
614
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700615 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700616 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800617 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700618 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700619 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700620 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700621
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700622 try {
623 mPolicyManager.registerListener(mPolicyListener);
624 } catch (RemoteException e) {
625 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700626 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700627 }
628
629 final PowerManager powerManager = (PowerManager) context.getSystemService(
630 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700631 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
632 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
633 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800634 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700635
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700636 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700637
Wink Saville51f456f2013-04-23 14:26:51 -0700638 // TODO: What is the "correct" way to do determine if this is a wifi only device?
639 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
640 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700641 String[] naStrings = context.getResources().getStringArray(
642 com.android.internal.R.array.networkAttributes);
643 for (String naString : naStrings) {
644 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700645 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700646 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700647 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800648 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700649 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700650 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700651 }
Wink Saville51f456f2013-04-23 14:26:51 -0700652 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
653 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
654 n.type);
655 continue;
656 }
Wink Saville975c8482011-04-07 14:23:45 -0700657 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800658 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700659 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700660 continue;
661 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700662 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700663
Wink Saville975c8482011-04-07 14:23:45 -0700664 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700665 mNetworksDefined++;
666 } catch(Exception e) {
667 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700668 }
669 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700670
671 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
672 if (mNetConfigs[TYPE_VPN] == null) {
673 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
674 // don't need to add TYPE_VPN to mNetConfigs.
675 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
676 mNetworksDefined++; // used only in the log() statement below.
677 }
678
Wink Saville5e56bc52013-07-29 15:00:57 -0700679 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700680
Robert Greenwalt50393202011-06-21 17:26:14 -0700681 mProtectedNetworks = new ArrayList<Integer>();
682 int[] protectedNetworks = context.getResources().getIntArray(
683 com.android.internal.R.array.config_protectedNetworks);
684 for (int p : protectedNetworks) {
685 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
686 mProtectedNetworks.add(p);
687 } else {
688 if (DBG) loge("Ignoring protectedNetwork " + p);
689 }
690 }
691
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700692 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
693 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700694
Robert Greenwaltfab501672014-07-23 11:44:01 -0700695 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800696
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700697 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
698
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700699 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700700 IntentFilter intentFilter = new IntentFilter();
701 intentFilter.addAction(Intent.ACTION_USER_STARTING);
702 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
703 mContext.registerReceiverAsUser(
704 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900705
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700706 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700707 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700708 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700709 } catch (RemoteException e) {
710 loge("Error registering observer :" + e);
711 }
712
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700713 if (DBG) {
714 mInetLog = new ArrayList();
715 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700716
Erik Klineda4bfa82015-04-30 12:58:40 +0900717 mSettingsObserver = new SettingsObserver(mContext, mHandler);
718 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800719
John Spurlockbf991a82013-06-24 14:20:23 -0400720 mDataConnectionStats = new DataConnectionStats(mContext);
721 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400722
Jason Monkdecd2952013-10-10 14:02:51 -0400723 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700724
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400725 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700727
Erik Klineda4bfa82015-04-30 12:58:40 +0900728 private NetworkRequest createInternetRequestForTransport(int transportType) {
729 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900730 netCap.addCapability(NET_CAPABILITY_INTERNET);
731 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900732 if (transportType > -1) {
733 netCap.addTransportType(transportType);
734 }
735 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
736 }
737
738 private void handleMobileDataAlwaysOn() {
739 final boolean enable = (Settings.Global.getInt(
740 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
741 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
742 if (enable == isEnabled) {
743 return; // Nothing to do.
744 }
745
746 if (enable) {
747 handleRegisterNetworkRequest(new NetworkRequestInfo(
748 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
749 } else {
750 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
751 }
752 }
753
754 private void registerSettingsCallbacks() {
755 // Watch for global HTTP proxy changes.
756 mSettingsObserver.observe(
757 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
758 EVENT_APPLY_GLOBAL_HTTP_PROXY);
759
760 // Watch for whether or not to keep mobile data always on.
761 mSettingsObserver.observe(
762 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
763 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
764 }
765
Robert Greenwalt34524f02014-05-18 16:22:10 -0700766 private synchronized int nextNetworkRequestId() {
767 return mNextNetworkRequestId++;
768 }
769
Paul Jensen31a94f42015-02-13 14:18:39 -0500770 private int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400771 synchronized (mNetworkForNetId) {
772 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
773 int netId = mNextNetId;
774 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
775 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500776 if (!mNetIdInUse.get(netId)) {
777 mNetIdInUse.put(netId, true);
778 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400779 }
780 }
781 }
782 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700783 }
784
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800785 private NetworkState getFilteredNetworkState(int networkType, int uid) {
786 NetworkInfo info = null;
787 LinkProperties lp = null;
788 NetworkCapabilities nc = null;
789 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800790 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800791
792 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
793 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
794 if (nai != null) {
795 synchronized (nai) {
796 info = new NetworkInfo(nai.networkInfo);
797 lp = new LinkProperties(nai.linkProperties);
798 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400799 // Network objects are outwardly immutable so there is no point to duplicating.
800 // Duplicating also precludes sharing socket factories and connection pools.
801 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800802 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800803 }
804 info.setType(networkType);
805 } else {
806 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
807 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
808 info.setIsAvailable(true);
809 lp = new LinkProperties();
810 nc = new NetworkCapabilities();
811 network = null;
812 }
813 info = getFilteredNetworkInfo(info, lp, uid);
814 }
815
Jeff Sharkey32566012014-12-02 18:30:14 -0800816 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400817 }
818
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800819 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
820 if (network == null) {
821 return null;
822 }
823 synchronized (mNetworkForNetId) {
824 return mNetworkForNetId.get(network.netId);
825 }
826 };
827
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900828 private Network[] getVpnUnderlyingNetworks(int uid) {
829 if (!mLockdownEnabled) {
830 int user = UserHandle.getUserId(uid);
831 synchronized (mVpns) {
832 Vpn vpn = mVpns.get(user);
833 if (vpn != null && vpn.appliesToUid(uid)) {
834 return vpn.getUnderlyingNetworks();
835 }
836 }
837 }
838 return null;
839 }
840
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800841 private NetworkState getUnfilteredActiveNetworkState(int uid) {
842 NetworkInfo info = null;
843 LinkProperties lp = null;
844 NetworkCapabilities nc = null;
845 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800846 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800847
848 NetworkAgentInfo nai = mNetworkForRequestId.get(mDefaultRequest.requestId);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800849
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900850 final Network[] networks = getVpnUnderlyingNetworks(uid);
851 if (networks != null) {
852 // getUnderlyingNetworks() returns:
853 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
854 // empty array => the VPN explicitly said "no default network".
855 // non-empty array => the VPN specified one or more default networks; we use the
856 // first one.
857 if (networks.length > 0) {
858 nai = getNetworkAgentInfoForNetwork(networks[0]);
859 } else {
860 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800861 }
862 }
863
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800864 if (nai != null) {
865 synchronized (nai) {
866 info = new NetworkInfo(nai.networkInfo);
867 lp = new LinkProperties(nai.linkProperties);
868 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400869 // Network objects are outwardly immutable so there is no point to duplicating.
870 // Duplicating also precludes sharing socket factories and connection pools.
871 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800872 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800873 }
874 }
875
Jeff Sharkey32566012014-12-02 18:30:14 -0800876 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400877 }
878
879 /**
880 * Check if UID should be blocked from using the network with the given LinkProperties.
881 */
882 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700883 final boolean networkCostly;
884 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700885
Robert Greenwalt12e67352014-05-13 21:41:06 -0700886 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700887 synchronized (mRulesLock) {
888 networkCostly = mMeteredIfaces.contains(iface);
889 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700890 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700891
Amith Yamasani15e472352015-04-24 19:06:07 -0700892 if ((uidRules & RULE_REJECT_ALL) != 0
893 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700894 return true;
895 }
896
897 // no restrictive rules; network is visible
898 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700899 }
900
901 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700902 * Return a filtered {@link NetworkInfo}, potentially marked
903 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800904 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700905 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800906 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
907 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400908 // network is blocked; clone and override state
909 info = new NetworkInfo(info);
910 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900911 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900912 log("returning Blocked NetworkInfo for ifname=" +
913 lp.getInterfaceName() + ", uid=" + uid);
914 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700915 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800916 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700917 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900918 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700919 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700920 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700921 }
922
923 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 * Return NetworkInfo for the active (i.e., connected) network interface.
925 * It is assumed that at most one network is active at a time. If more
926 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700927 * @return the info for the active network, or {@code null} if none is
928 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700930 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700932 enforceAccessPermission();
933 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800934 NetworkState state = getUnfilteredActiveNetworkState(uid);
935 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 }
937
Paul Jensen31a94f42015-02-13 14:18:39 -0500938 @Override
939 public Network getActiveNetwork() {
940 enforceAccessPermission();
941 final int uid = Binder.getCallingUid();
942 final int user = UserHandle.getUserId(uid);
943 int vpnNetId = NETID_UNSET;
944 synchronized (mVpns) {
945 final Vpn vpn = mVpns.get(user);
946 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
947 }
948 NetworkAgentInfo nai;
949 if (vpnNetId != NETID_UNSET) {
950 synchronized (mNetworkForNetId) {
951 nai = mNetworkForNetId.get(vpnNetId);
952 }
953 if (nai != null) return nai.network;
954 }
955 nai = getDefaultNetwork();
956 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
957 return nai != null ? nai.network : null;
958 }
959
Wink Saville948282b2013-08-29 08:55:16 -0700960 /**
961 * Find the first Provisioning network.
962 *
963 * @return NetworkInfo or null if none.
964 */
965 private NetworkInfo getProvisioningNetworkInfo() {
966 enforceAccessPermission();
967
968 // Find the first Provisioning Network
969 NetworkInfo provNi = null;
970 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville67c38212013-09-05 12:02:25 -0700971 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -0700972 provNi = ni;
973 break;
974 }
975 }
976 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
977 return provNi;
978 }
979
980 /**
981 * Find the first Provisioning network or the ActiveDefaultNetwork
982 * if there is no Provisioning network
983 *
984 * @return NetworkInfo or null if none.
985 */
986 @Override
987 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
988 enforceAccessPermission();
989
990 NetworkInfo provNi = getProvisioningNetworkInfo();
991 if (provNi == null) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800992 provNi = getActiveNetworkInfo();
Wink Saville948282b2013-08-29 08:55:16 -0700993 }
994 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
995 return provNi;
996 }
997
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700998 public NetworkInfo getActiveNetworkInfoUnfiltered() {
999 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001000 final int uid = Binder.getCallingUid();
1001 NetworkState state = getUnfilteredActiveNetworkState(uid);
1002 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001003 }
1004
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001005 @Override
1006 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1007 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001008 NetworkState state = getUnfilteredActiveNetworkState(uid);
1009 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001010 }
1011
1012 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 public NetworkInfo getNetworkInfo(int networkType) {
1014 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001015 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001016 if (getVpnUnderlyingNetworks(uid) != null) {
1017 // A VPN is active, so we may need to return one of its underlying networks. This
1018 // information is not available in LegacyTypeTracker, so we have to get it from
1019 // getUnfilteredActiveNetworkState.
1020 NetworkState state = getUnfilteredActiveNetworkState(uid);
1021 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1022 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1023 }
1024 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001025 NetworkState state = getFilteredNetworkState(networkType, uid);
1026 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 }
1028
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001029 @Override
1030 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1031 enforceAccessPermission();
1032 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001033 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001034 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1035 if (nai != null) {
1036 synchronized (nai) {
1037 info = new NetworkInfo(nai.networkInfo);
1038 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001039 }
1040 }
1041 return info;
1042 }
1043
1044 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 public NetworkInfo[] getAllNetworkInfo() {
1046 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001047 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001048 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1049 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001050 NetworkInfo info = getNetworkInfo(networkType);
1051 if (info != null) {
1052 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001055 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 }
1057
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001058 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001059 public Network getNetworkForType(int networkType) {
1060 enforceAccessPermission();
1061 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001062 NetworkState state = getFilteredNetworkState(networkType, uid);
1063 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1064 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001065 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001066 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001067 }
1068
1069 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001070 public Network[] getAllNetworks() {
1071 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001072 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001073 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001074 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001075 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001076 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001077 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001078 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001079 }
1080
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001081 @Override
1082 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1083 // The basic principle is: if an app's traffic could possibly go over a
1084 // network, without the app doing anything multinetwork-specific,
1085 // (hence, by "default"), then include that network's capabilities in
1086 // the array.
1087 //
1088 // In the normal case, app traffic only goes over the system's default
1089 // network connection, so that's the only network returned.
1090 //
1091 // With a VPN in force, some app traffic may go into the VPN, and thus
1092 // over whatever underlying networks the VPN specifies, while other app
1093 // traffic may go over the system default network (e.g.: a split-tunnel
1094 // VPN, or an app disallowed by the VPN), so the set of networks
1095 // returned includes the VPN's underlying networks and the system
1096 // default.
1097 enforceAccessPermission();
1098
1099 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1100
1101 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001102 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001103 if (nc != null) {
1104 result.put(nai.network, nc);
1105 }
1106
1107 if (!mLockdownEnabled) {
1108 synchronized (mVpns) {
1109 Vpn vpn = mVpns.get(userId);
1110 if (vpn != null) {
1111 Network[] networks = vpn.getUnderlyingNetworks();
1112 if (networks != null) {
1113 for (Network network : networks) {
1114 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001115 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001116 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001117 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001118 }
1119 }
1120 }
1121 }
1122 }
1123 }
1124
1125 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1126 out = result.values().toArray(out);
1127 return out;
1128 }
1129
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001130 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001131 public boolean isNetworkSupported(int networkType) {
1132 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001133 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001134 }
1135
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001136 /**
1137 * Return LinkProperties for the active (i.e., connected) default
1138 * network interface. It is assumed that at most one default network
1139 * is active at a time. If more than one is active, it is indeterminate
1140 * which will be returned.
1141 * @return the ip properties for the active network, or {@code null} if
1142 * none is active
1143 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001144 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001145 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001146 enforceAccessPermission();
1147 final int uid = Binder.getCallingUid();
1148 NetworkState state = getUnfilteredActiveNetworkState(uid);
1149 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001150 }
1151
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001152 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001153 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001154 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001155 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1156 if (nai != null) {
1157 synchronized (nai) {
1158 return new LinkProperties(nai.linkProperties);
1159 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001160 }
1161 return null;
1162 }
1163
Robert Greenwalt12e67352014-05-13 21:41:06 -07001164 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001165 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001166 public LinkProperties getLinkProperties(Network network) {
1167 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001168 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001169 if (nai != null) {
1170 synchronized (nai) {
1171 return new LinkProperties(nai.linkProperties);
1172 }
1173 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001174 return null;
1175 }
1176
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001177 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001178 if (nai != null) {
1179 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001180 if (nai.networkCapabilities != null) {
1181 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001182 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001183 }
1184 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001185 return null;
1186 }
1187
1188 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001189 public NetworkCapabilities getNetworkCapabilities(Network network) {
1190 enforceAccessPermission();
1191 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1192 }
1193
1194 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001195 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001196 // Require internal since we're handing out IMSI details
1197 enforceConnectivityInternalPermission();
1198
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001199 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001200 for (Network network : getAllNetworks()) {
1201 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1202 if (nai != null) {
1203 synchronized (nai) {
1204 final String subscriberId = (nai.networkMisc != null)
1205 ? nai.networkMisc.subscriberId : null;
1206 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1207 nai.networkCapabilities, network, subscriberId, null));
1208 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001209 }
1210 }
1211 return result.toArray(new NetworkState[result.size()]);
1212 }
1213
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001214 @Override
1215 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1216 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001217 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001218 final long token = Binder.clearCallingIdentity();
1219 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001220 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1221 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001222 try {
1223 return mPolicyManager.getNetworkQuotaInfo(state);
1224 } catch (RemoteException e) {
1225 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001226 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001227 return null;
1228 } finally {
1229 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001230 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001231 }
1232
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001233 @Override
1234 public boolean isActiveNetworkMetered() {
1235 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001236 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001237 final long token = Binder.clearCallingIdentity();
1238 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001239 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001240 } finally {
1241 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001242 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001243 }
1244
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001245 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1246 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1247 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001248 try {
1249 return mPolicyManager.isNetworkMetered(state);
1250 } catch (RemoteException e) {
1251 }
1252 }
1253 return false;
1254 }
1255
Jeff Sharkey216c1812012-08-05 14:29:23 -07001256 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1257 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001258 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001259 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001260 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001261 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001262 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001263
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001264 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 * Ensure that a network route exists to deliver traffic to the specified
1266 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001267 * @param networkType the type of the network over which traffic to the
1268 * specified host is to be routed
1269 * @param hostAddress the IP address of the host to which the route is
1270 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 * @return {@code true} on success, {@code false} on failure
1272 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001273 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001275 if (mProtectedNetworks.contains(networkType)) {
1276 enforceConnectivityInternalPermission();
1277 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001278
Chad Brubakerc0234532014-02-14 13:24:29 -08001279 InetAddress addr;
1280 try {
1281 addr = InetAddress.getByAddress(hostAddress);
1282 } catch (UnknownHostException e) {
1283 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1284 return false;
1285 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001288 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 return false;
1290 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001291
1292 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1293 if (nai == null) {
1294 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1295 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1296 } else {
1297 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1298 }
1299 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001300 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001301
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001302 DetailedState netState;
1303 synchronized (nai) {
1304 netState = nai.networkInfo.getDetailedState();
1305 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001306
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001307 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001308 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001309 log("requestRouteToHostAddress on down network "
1310 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001311 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001312 }
1313 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001315
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001316 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001317 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001318 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001319 LinkProperties lp;
1320 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001321 synchronized (nai) {
1322 lp = nai.linkProperties;
1323 netId = nai.network.netId;
1324 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001325 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001326 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1327 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001328 } finally {
1329 Binder.restoreCallingIdentity(token);
1330 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001331 }
1332
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001333 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001334 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001335 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001336 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001337 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001338 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001339 if (bestRoute.getGateway().equals(addr)) {
1340 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001341 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001342 } else {
1343 // if we will connect to this through another route, add a direct route
1344 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001345 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001346 }
1347 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001348 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001349 try {
1350 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1351 } catch (Exception e) {
1352 // never crash - catch them all
1353 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001354 return false;
1355 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001356 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 }
1358
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001359 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1360 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001361 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001362 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001363 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001364 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001365 }
1366
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001367 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001368 // skip update when we've already applied rules
1369 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1370 if (oldRules == uidRules) return;
1371
1372 mUidRules.put(uid, uidRules);
1373 }
1374
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001375 // TODO: notify UID when it has requested targeted updates
1376 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001377
1378 @Override
1379 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001380 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001381 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001382 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001383 }
1384
1385 synchronized (mRulesLock) {
1386 mMeteredIfaces.clear();
1387 for (String iface : meteredIfaces) {
1388 mMeteredIfaces.add(iface);
1389 }
1390 }
1391 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001392
1393 @Override
1394 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1395 // caller is NPMS, since we only register with them
1396 if (LOGD_RULES) {
1397 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1398 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001399 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001400 };
1401
Robin Lee3b3dd942015-05-12 18:14:58 +01001402 /**
1403 * Require that the caller is either in the same user or has appropriate permission to interact
1404 * across users.
1405 *
1406 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1407 */
1408 private void enforceCrossUserPermission(int userId) {
1409 if (userId == UserHandle.getCallingUserId()) {
1410 // Not a cross-user call.
1411 return;
1412 }
1413 mContext.enforceCallingOrSelfPermission(
1414 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1415 "ConnectivityService");
1416 }
1417
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001418 private void enforceInternetPermission() {
1419 mContext.enforceCallingOrSelfPermission(
1420 android.Manifest.permission.INTERNET,
1421 "ConnectivityService");
1422 }
1423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001425 mContext.enforceCallingOrSelfPermission(
1426 android.Manifest.permission.ACCESS_NETWORK_STATE,
1427 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 }
1429
1430 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001431 mContext.enforceCallingOrSelfPermission(
1432 android.Manifest.permission.CHANGE_NETWORK_STATE,
1433 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 }
1435
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001436 private void enforceTetherAccessPermission() {
1437 mContext.enforceCallingOrSelfPermission(
1438 android.Manifest.permission.ACCESS_NETWORK_STATE,
1439 "ConnectivityService");
1440 }
1441
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001442 private void enforceConnectivityInternalPermission() {
1443 mContext.enforceCallingOrSelfPermission(
1444 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1445 "ConnectivityService");
1446 }
1447
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001448 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001449 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001450 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001451 }
1452
1453 private void sendInetConditionBroadcast(NetworkInfo info) {
1454 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1455 }
1456
Wink Saville628b0852011-08-04 15:01:58 -07001457 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001458 if (mLockdownTracker != null) {
1459 info = mLockdownTracker.augmentNetworkInfo(info);
1460 }
1461
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001462 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001463 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001464 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 if (info.isFailover()) {
1466 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1467 info.setFailover(false);
1468 }
1469 if (info.getReason() != null) {
1470 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1471 }
1472 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001473 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1474 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001476 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001477 return intent;
1478 }
1479
1480 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1481 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1482 }
1483
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001484 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001485 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1486 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1487 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001488 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001489 final long ident = Binder.clearCallingIdentity();
1490 try {
1491 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1492 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1493 } finally {
1494 Binder.restoreCallingIdentity(ident);
1495 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001496 }
1497
Mike Lockwood0f79b542009-08-14 14:18:49 -04001498 private void sendStickyBroadcast(Intent intent) {
1499 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001500 if (!mSystemReady) {
1501 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001502 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001503 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001504 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001505 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001506 }
1507
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001508 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001509 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1510 final IBatteryStats bs = BatteryStatsService.getService();
1511 try {
1512 NetworkInfo ni = intent.getParcelableExtra(
1513 ConnectivityManager.EXTRA_NETWORK_INFO);
1514 bs.noteConnectivityChanged(intent.getIntExtra(
1515 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1516 ni != null ? ni.getState().toString() : "?");
1517 } catch (RemoteException e) {
1518 }
1519 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001520 try {
1521 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1522 } finally {
1523 Binder.restoreCallingIdentity(ident);
1524 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001525 }
1526 }
1527
1528 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001529 loadGlobalProxy();
1530
Mike Lockwood0f79b542009-08-14 14:18:49 -04001531 synchronized(this) {
1532 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001533 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001534 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001535 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001536 }
1537 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001538 // load the global proxy at startup
1539 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001540
1541 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1542 // for user to unlock device.
1543 if (!updateLockdownVpn()) {
1544 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1545 mContext.registerReceiver(mUserPresentReceiver, filter);
1546 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001547
Erik Klineda4bfa82015-04-30 12:58:40 +09001548 // Configure whether mobile data is always on.
1549 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1550
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001551 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001552
1553 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 }
1555
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001556 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1557 @Override
1558 public void onReceive(Context context, Intent intent) {
1559 // Try creating lockdown tracker, since user present usually means
1560 // unlocked keystore.
1561 if (updateLockdownVpn()) {
1562 mContext.unregisterReceiver(this);
1563 }
1564 }
1565 };
1566
Wink Savilled747cbc2013-08-07 16:22:47 -07001567 /** @hide */
1568 @Override
1569 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
1570 enforceConnectivityInternalPermission();
1571 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
Robert Greenwalt12e67352014-05-13 21:41:06 -07001572// mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
Wink Savilled747cbc2013-08-07 16:22:47 -07001573 }
1574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001576 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001577 *
1578 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001579 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001580 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001581 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1582 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001583
1584 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001585 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001586
Robert Greenwalt7b816022014-04-18 15:25:25 -07001587 if (networkAgent.networkCapabilities.hasTransport(
1588 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001589 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1590 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001591 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001592 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001593 } else if (networkAgent.networkCapabilities.hasTransport(
1594 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001595 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1596 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinskie08af192015-03-25 16:42:59 -07001597 5);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001598 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001599 } else {
1600 // do not track any other networks
1601 timeout = 0;
1602 }
1603
Robert Greenwalt7b816022014-04-18 15:25:25 -07001604 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001605 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001606 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001607 } catch (Exception e) {
1608 // You shall not crash!
1609 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001610 }
1611 }
1612 }
1613
1614 /**
1615 * Remove data activity tracking when network disconnects.
1616 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001617 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1618 final String iface = networkAgent.linkProperties.getInterfaceName();
1619 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001620
Robert Greenwalt7b816022014-04-18 15:25:25 -07001621 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1622 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001623 try {
1624 // the call fails silently if no idletimer setup for this interface
1625 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001626 } catch (Exception e) {
1627 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001628 }
1629 }
1630 }
1631
1632 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001633 * Reads the network specific MTU size from reources.
1634 * and set it on it's iface.
1635 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001636 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1637 final String iface = newLp.getInterfaceName();
1638 final int mtu = newLp.getMtu();
1639 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1640 if (VDBG) log("identical MTU - not setting");
1641 return;
1642 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001643
Robert Greenwalt43074032014-08-15 17:53:05 -07001644 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001645 loge("Unexpected mtu value: " + mtu + ", " + iface);
1646 return;
1647 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001648
w1997615afd812014-08-05 15:18:11 -07001649 // Cannot set MTU without interface name
1650 if (TextUtils.isEmpty(iface)) {
1651 loge("Setting MTU size with null iface.");
1652 return;
1653 }
1654
Robert Greenwalt7b816022014-04-18 15:25:25 -07001655 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001656 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001657 mNetd.setMtu(iface, mtu);
1658 } catch (Exception e) {
1659 Slog.e(TAG, "exception in setMtu()" + e);
1660 }
1661 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001662
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001663 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Irfan Sheriffd649c122010-06-09 15:39:36 -07001664
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001665 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1666 if (isDefaultNetwork(nai) == false) {
1667 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001668 }
1669
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001670 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1671 String[] values = null;
1672 if (tcpBufferSizes != null) {
1673 values = tcpBufferSizes.split(",");
1674 }
1675
1676 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001677 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001678 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1679 values = tcpBufferSizes.split(",");
1680 }
1681
1682 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1683
1684 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001685 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001686
1687 final String prefix = "/sys/kernel/ipv4/tcp_";
1688 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1689 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1690 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1691 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1692 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1693 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1694 mCurrentTcpBufferSizes = tcpBufferSizes;
1695 } catch (IOException e) {
1696 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001697 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001698
1699 final String defaultRwndKey = "net.tcp.default_init_rwnd";
1700 int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0);
1701 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
1702 Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue);
1703 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1704 if (rwndValue != 0) {
1705 SystemProperties.set(sysctlKey, rwndValue.toString());
1706 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001707 }
1708
Mattias Falk8b47b362011-08-23 14:15:13 +02001709 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001710 /*
1711 * Tell the VMs to toss their DNS caches
1712 */
1713 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1714 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001715 /*
1716 * Connectivity events can happen before boot has completed ...
1717 */
1718 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001719 final long ident = Binder.clearCallingIdentity();
1720 try {
1721 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1722 } finally {
1723 Binder.restoreCallingIdentity(ident);
1724 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001725 }
1726
Robert Greenwalt562cc542014-05-15 18:07:26 -07001727 @Override
1728 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001729 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1730 NETWORK_RESTORE_DELAY_PROP_NAME);
1731 if(restoreDefaultNetworkDelayStr != null &&
1732 restoreDefaultNetworkDelayStr.length() != 0) {
1733 try {
1734 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1735 } catch (NumberFormatException e) {
1736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001738 // if the system property isn't set, use the value for the apn type
1739 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1740
1741 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1742 (mNetConfigs[networkType] != null)) {
1743 ret = mNetConfigs[networkType].restoreTime;
1744 }
1745 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 }
1747
1748 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001749 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1750 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001751 if (mContext.checkCallingOrSelfPermission(
1752 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001754 pw.println("Permission Denial: can't dump ConnectivityService " +
1755 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1756 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 return;
1758 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001759
Lorenzo Colittie3805462015-06-03 11:18:24 +09001760 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001761 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001762 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001763 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001764 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001765 pw.println();
1766
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001767 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1768 pw.print("Active default network: ");
1769 if (defaultNai == null) {
1770 pw.println("none");
1771 } else {
1772 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001774 pw.println();
1775
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001776 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001777 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001778 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1779 pw.println(nai.toString());
1780 pw.increaseIndent();
1781 pw.println("Requests:");
1782 pw.increaseIndent();
1783 for (int i = 0; i < nai.networkRequests.size(); i++) {
1784 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001785 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001786 pw.decreaseIndent();
1787 pw.println("Lingered:");
1788 pw.increaseIndent();
1789 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1790 pw.decreaseIndent();
1791 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001792 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001793 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001794 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001795
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001796 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001797 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001798 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1799 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001800 }
1801 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001802 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001803
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001804 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001805
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001806 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001807 pw.print("mNetTransitionWakeLock: currently " +
1808 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1809 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1810 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1811 } else {
1812 pw.println(", last requested never");
1813 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001814 }
1815 pw.println();
1816
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001817 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001818
Lorenzo Colittie3805462015-06-03 11:18:24 +09001819 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001820 pw.println();
1821 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001822 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001823 for(int i = 0; i < mInetLog.size(); i++) {
1824 pw.println(mInetLog.get(i));
1825 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001826 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 }
1829
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001830 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001831 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001832 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001833 if (officialNai != null && officialNai.equals(nai)) return true;
1834 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001835 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001836 " - " + nai);
1837 }
1838 return false;
1839 }
1840
Paul Jensenc8b9a742014-09-30 15:37:41 -04001841 private boolean isRequest(NetworkRequest request) {
1842 return mNetworkRequests.get(request).isRequest;
1843 }
1844
Robert Greenwalt42acef32009-08-12 16:08:25 -07001845 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001846 private class NetworkStateTrackerHandler extends Handler {
1847 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001848 super(looper);
1849 }
1850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 @Override
1852 public void handleMessage(Message msg) {
1853 NetworkInfo info;
1854 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001855 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001856 handleAsyncChannelHalfConnect(msg);
1857 break;
1858 }
1859 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1860 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1861 if (nai != null) nai.asyncChannel.disconnect();
1862 break;
1863 }
1864 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1865 handleAsyncChannelDisconnected(msg);
1866 break;
1867 }
1868 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1869 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1870 if (nai == null) {
1871 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1872 } else {
1873 updateCapabilities(nai, (NetworkCapabilities)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07001874 }
1875 break;
1876 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001877 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1878 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1879 if (nai == null) {
1880 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1881 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001882 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001883 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001884 "; created=" + nai.created);
1885 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001886 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001887 synchronized (nai) {
1888 nai.linkProperties = (LinkProperties)msg.obj;
1889 }
Paul Jenseneec75412014-08-04 12:21:19 -04001890 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001891 }
1892 break;
1893 }
1894 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1895 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1896 if (nai == null) {
1897 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1898 break;
1899 }
1900 info = (NetworkInfo) msg.obj;
1901 updateNetworkInfo(nai, info);
1902 break;
1903 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001904 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1905 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1906 if (nai == null) {
1907 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1908 break;
1909 }
1910 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001911 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001912 break;
1913 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001914 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1915 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1916 if (nai == null) {
1917 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1918 break;
1919 }
1920 try {
1921 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001922 } catch (Exception e) {
1923 // Never crash!
1924 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001925 }
1926 break;
1927 }
1928 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1929 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1930 if (nai == null) {
1931 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1932 break;
1933 }
1934 try {
1935 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001936 } catch (Exception e) {
1937 // Never crash!
1938 loge("Exception in removeVpnUidRanges: " + e);
1939 }
1940 break;
1941 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001942 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1943 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1944 if (nai == null) {
1945 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1946 break;
1947 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001948 if (nai.created && !nai.networkMisc.explicitlySelected) {
1949 loge("ERROR: created network explicitly selected.");
1950 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001951 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001952 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07001953 break;
1954 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001955 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001956 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001957 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
1958 final boolean valid =
1959 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
1960 final boolean validationChanged = (valid != nai.lastValidated);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001961 nai.lastValidated = valid;
Paul Jensenad50a1f2014-09-05 12:06:44 -04001962 if (valid) {
1963 if (DBG) log("Validated " + nai.name());
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001964 nai.networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09001965 if (!nai.everValidated) {
1966 nai.everValidated = true;
Paul Jensenb10e37f2014-11-25 12:33:08 -05001967 rematchNetworkAndRequests(nai, NascentState.JUST_VALIDATED,
1968 ReapUnvalidatedNetworks.REAP);
1969 // If score has changed, rebroadcast to NetworkFactories. b/17726566
Paul Jensenc8b9a742014-09-30 15:37:41 -04001970 sendUpdatedScoreToFactories(nai);
1971 }
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001972 } else {
1973 nai.networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensenad50a1f2014-09-05 12:06:44 -04001974 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001975 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07001976 // Let the NetworkAgent know the state of its network
1977 nai.asyncChannel.sendMessage(
1978 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
1979 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
1980 0, null);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001981
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001982 if (validationChanged) {
1983 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
1984 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001985 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001986 break;
1987 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001988 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001989 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001990 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
1991 handleLingerComplete(nai);
1992 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001993 break;
1994 }
Paul Jensen869868be2014-05-15 10:33:05 -04001995 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04001996 if (msg.arg1 == 0) {
1997 setProvNotificationVisibleIntent(false, msg.arg2, 0, null, null);
1998 } else {
Lorenzo Colittid49159f2015-05-14 23:15:10 +09001999 final NetworkAgentInfo nai;
Paul Jensen5df4bec2014-08-25 22:45:39 -04002000 synchronized (mNetworkForNetId) {
2001 nai = mNetworkForNetId.get(msg.arg2);
2002 }
2003 if (nai == null) {
2004 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2005 break;
2006 }
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002007 nai.captivePortalDetected = true;
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002008 setProvNotificationVisibleIntent(true, msg.arg2, nai.networkInfo.getType(),
2009 nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj);
Paul Jensen869868be2014-05-15 10:33:05 -04002010 }
Paul Jensen869868be2014-05-15 10:33:05 -04002011 break;
2012 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002013 }
2014 }
2015 }
2016
Paul Jensen0cc17322014-11-25 15:26:53 -05002017 // Cancel any lingering so the linger timeout doesn't teardown a network.
2018 // This should be called when a network begins satisfying a NetworkRequest.
2019 // Note: depending on what state the NetworkMonitor is in (e.g.,
2020 // if it's awaiting captive portal login, or if validation failed), this
2021 // may trigger a re-evaluation of the network.
2022 private void unlinger(NetworkAgentInfo nai) {
2023 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen573a0352015-01-08 10:49:34 -05002024 // If network has never been validated, it cannot have been lingered, so don't bother
2025 // needlessly triggering a re-evaluation.
2026 if (!nai.everValidated) return;
Paul Jensen0cc17322014-11-25 15:26:53 -05002027 nai.networkLingered.clear();
2028 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2029 }
2030
Robert Greenwalt7b816022014-04-18 15:25:25 -07002031 private void handleAsyncChannelHalfConnect(Message msg) {
2032 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002033 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002034 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2035 if (VDBG) log("NetworkFactory connected");
2036 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002037 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002038 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002039 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002040 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002041 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002042 }
2043 } else {
2044 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002045 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002046 }
2047 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2048 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2049 if (VDBG) log("NetworkAgent connected");
2050 // A network agent has requested a connection. Establish the connection.
2051 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2052 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2053 } else {
2054 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002055 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002056 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002057 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002058 synchronized (mNetworkForNetId) {
2059 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002060 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002061 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002062 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002063 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002064 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002065 }
2066 }
2067 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002068
Robert Greenwalt7b816022014-04-18 15:25:25 -07002069 private void handleAsyncChannelDisconnected(Message msg) {
2070 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2071 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002072 if (DBG) {
2073 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2074 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002075 // A network agent has disconnected.
Paul Jenseneec75412014-08-04 12:21:19 -04002076 if (nai.created) {
2077 // Tell netd to clean up the configuration for this network
2078 // (routing rules, DNS, etc).
2079 try {
2080 mNetd.removeNetwork(nai.network.netId);
2081 } catch (Exception e) {
2082 loge("Exception removing network: " + e);
2083 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002084 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07002085 // TODO - if we move the logic to the network agent (have them disconnect
2086 // because they lost all their requests or because their score isn't good)
2087 // then they would disconnect organically, report their new state and then
2088 // disconnect the channel.
2089 if (nai.networkInfo.isConnected()) {
2090 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2091 null, null);
2092 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002093 final boolean wasDefault = isDefaultNetwork(nai);
2094 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002095 mDefaultInetConditionPublished = 0;
2096 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002097 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002098 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002099 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002100 mNetworkAgentInfos.remove(msg.replyTo);
2101 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002102 synchronized (mNetworkForNetId) {
2103 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002104 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002105 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002106 // Since we've lost the network, go through all the requests that
2107 // it was satisfying and see if any other factory can satisfy them.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002108 // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
Paul Jensenca8f16a2014-05-09 12:47:55 -04002109 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07002110 for (int i = 0; i < nai.networkRequests.size(); i++) {
2111 NetworkRequest request = nai.networkRequests.valueAt(i);
2112 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2113 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002114 if (DBG) {
2115 log("Checking for replacement network to handle request " + request );
2116 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002117 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002118 sendUpdatedScoreToFactories(request, 0);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002119 NetworkAgentInfo alternative = null;
Paul Jensen0cc17322014-11-25 15:26:53 -05002120 for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) {
2121 if (existing.satisfies(request) &&
Paul Jensenca8f16a2014-05-09 12:47:55 -04002122 (alternative == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002123 alternative.getCurrentScore() < existing.getCurrentScore())) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04002124 alternative = existing;
2125 }
2126 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002127 if (alternative != null) {
2128 if (DBG) log(" found replacement in " + alternative.name());
2129 if (!toActivate.contains(alternative)) {
2130 toActivate.add(alternative);
2131 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002132 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002133 }
2134 }
2135 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2136 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002137 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002138 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002139 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002140 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002141 for (NetworkAgentInfo networkToActivate : toActivate) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002142 unlinger(networkToActivate);
Paul Jensenb10e37f2014-11-25 12:33:08 -05002143 rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED,
2144 ReapUnvalidatedNetworks.DONT_REAP);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002145 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002146 }
Maunik Shah4b647f42015-03-30 11:36:42 +05302147 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2148 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002149 }
2150
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002151 // If this method proves to be too slow then we can maintain a separate
2152 // pendingIntent => NetworkRequestInfo map.
2153 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2154 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2155 Intent intent = pendingIntent.getIntent();
2156 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2157 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2158 if (existingPendingIntent != null &&
2159 existingPendingIntent.getIntent().filterEquals(intent)) {
2160 return entry.getValue();
2161 }
2162 }
2163 return null;
2164 }
2165
2166 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2167 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2168
2169 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2170 if (existingRequest != null) { // remove the existing request.
2171 if (DBG) log("Replacing " + existingRequest.request + " with "
2172 + nri.request + " because their intents matched.");
2173 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2174 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002175 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002176 }
2177
Erik Klineda4bfa82015-04-30 12:58:40 +09002178 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002179 mNetworkRequests.put(nri.request, nri);
2180
Paul Jensen0cc17322014-11-25 15:26:53 -05002181 // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
2182
Robert Greenwalt9258c642014-03-26 16:47:06 -07002183 // Check for the best currently alive network that satisfies this request
2184 NetworkAgentInfo bestNetwork = null;
2185 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002186 if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002187 if (network.satisfies(nri.request)) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04002188 if (DBG) log("apparently satisfied. currentScore=" + network.getCurrentScore());
Paul Jensen0cc17322014-11-25 15:26:53 -05002189 if (!nri.isRequest) {
2190 // Not setting bestNetwork here as a listening NetworkRequest may be
2191 // satisfied by multiple Networks. Instead the request is added to
2192 // each satisfying Network and notified about each.
2193 network.addRequest(nri.request);
2194 notifyNetworkCallback(network, nri);
2195 } else if (bestNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002196 bestNetwork.getCurrentScore() < network.getCurrentScore()) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002197 bestNetwork = network;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002198 }
2199 }
2200 }
2201 if (bestNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002202 if (DBG) log("using " + bestNetwork.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002203 unlinger(bestNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07002204 bestNetwork.addRequest(nri.request);
Robert Greenwalt2d370702014-06-03 17:22:11 -07002205 mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002206 notifyNetworkCallback(bestNetwork, nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04002207 if (nri.request.legacyType != TYPE_NONE) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09002208 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2209 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002210 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002211
Lorenzo Colittia793a672014-07-31 23:20:17 +09002212 if (nri.isRequest) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002213 if (DBG) log("sending new NetworkRequest to factories");
Paul Jensen0cc17322014-11-25 15:26:53 -05002214 final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
Robert Greenwalta67be032014-05-16 15:49:14 -07002215 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002216 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
Robert Greenwalt562cc542014-05-15 18:07:26 -07002217 0, nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002218 }
2219 }
2220 }
2221
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002222 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2223 int callingUid) {
2224 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2225 if (nri != null) {
2226 handleReleaseNetworkRequest(nri.request, callingUid);
2227 }
2228 }
2229
Paul Jensen99364842014-12-09 11:43:45 -05002230 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2231 // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2232 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2233 // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2234 private boolean unneeded(NetworkAgentInfo nai) {
2235 if (!nai.created || nai.isVPN()) return false;
2236 boolean unneeded = true;
2237 if (nai.everValidated) {
2238 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2239 final NetworkRequest nr = nai.networkRequests.valueAt(i);
2240 try {
2241 if (isRequest(nr)) unneeded = false;
2242 } catch (Exception e) {
2243 loge("Request " + nr + " not found in mNetworkRequests.");
2244 loge(" it came from request list of " + nai.name());
2245 }
2246 }
2247 } else {
2248 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2249 // If this Network is already the highest scoring Network for a request, or if
2250 // there is hope for it to become one if it validated, then it is needed.
2251 if (nri.isRequest && nai.satisfies(nri.request) &&
2252 (nai.networkRequests.get(nri.request.requestId) != null ||
2253 // Note that this catches two important cases:
2254 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2255 // is currently satisfying the request. This is desirable when
2256 // cellular ends up validating but WiFi does not.
2257 // 2. Unvalidated WiFi will not be reaped when validated cellular
2258 // is currently satsifying the request. This is desirable when
2259 // WiFi ends up validating and out scoring cellular.
2260 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2261 nai.getCurrentScoreAsValidated())) {
2262 unneeded = false;
2263 break;
2264 }
2265 }
2266 }
2267 return unneeded;
2268 }
2269
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002270 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2271 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002272 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002273 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002274 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2275 return;
2276 }
2277 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002278 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002279 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002280 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002281 // Find all networks that are satisfying this request and remove the request
2282 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002283 // TODO - it's my understanding that for a request there is only a single
2284 // network satisfying it, so this loop is wasteful
2285 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002286 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2287 if (nai.networkRequests.get(nri.request.requestId) != null) {
2288 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002289 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002290 log(" Removing from current network " + nai.name() +
2291 ", leaving " + nai.networkRequests.size() +
2292 " requests.");
2293 }
Paul Jensen99364842014-12-09 11:43:45 -05002294 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002295 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002296 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002297 } else {
2298 // suspect there should only be one pass through here
2299 // but if any were kept do the check below
2300 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002301 }
2302 }
2303 }
2304
Robert Greenwalt51481852015-01-08 14:43:31 -08002305 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2306 if (nai != null) {
2307 mNetworkForRequestId.remove(nri.request.requestId);
2308 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002309 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002310 // that a network connected to serve it, even though the network was already
2311 // connected. Now that this request has gone away, we might have to pretend
2312 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002313 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002314 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2315 boolean doRemove = true;
2316 if (wasKept) {
2317 // check if any of the remaining requests for this network are for the
2318 // same legacy type - if so, don't remove the nai
2319 for (int i = 0; i < nai.networkRequests.size(); i++) {
2320 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2321 if (otherRequest.legacyType == nri.request.legacyType &&
2322 isRequest(otherRequest)) {
2323 if (DBG) log(" still have other legacy request - leaving");
2324 doRemove = false;
2325 }
2326 }
2327 }
2328
2329 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002330 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002331 }
2332 }
2333
Robert Greenwalta67be032014-05-16 15:49:14 -07002334 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002335 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2336 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002337 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002338 } else {
2339 // listens don't have a singular affectedNetwork. Check all networks to see
2340 // if this listen request applies and remove it.
2341 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2342 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002343 }
2344 }
2345 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2346 }
2347 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002348
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002349 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2350 enforceConnectivityInternalPermission();
2351 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2352 accept ? 1 : 0, always ? 1: 0, network));
2353 }
2354
2355 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2356 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2357 " accept=" + accept + " always=" + always);
2358
2359 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2360 if (nai == null) {
2361 // Nothing to do.
2362 return;
2363 }
2364
2365 if (nai.everValidated) {
2366 // The network validated while the dialog box was up. Don't make any changes. There's a
2367 // TODO in the dialog code to make it go away if the network validates; once that's
2368 // implemented, taking action here will be confusing.
2369 return;
2370 }
2371
2372 if (!nai.networkMisc.explicitlySelected) {
2373 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2374 }
2375
2376 if (accept != nai.networkMisc.acceptUnvalidated) {
2377 int oldScore = nai.getCurrentScore();
2378 nai.networkMisc.acceptUnvalidated = accept;
2379 rematchAllNetworksAndRequests(nai, oldScore);
2380 sendUpdatedScoreToFactories(nai);
2381 }
2382
2383 if (always) {
2384 nai.asyncChannel.sendMessage(
2385 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2386 }
2387
2388 // TODO: should we also disconnect from the network if accept is false?
2389 }
2390
2391 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
2392 mHandler.sendMessageDelayed(
2393 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2394 PROMPT_UNVALIDATED_DELAY_MS);
2395 }
2396
2397 private void handlePromptUnvalidated(Network network) {
2398 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2399
2400 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2401 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002402 // Also don't prompt on captive portals because we're already prompting the user to sign in.
2403 if (nai == null || nai.everValidated || nai.captivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002404 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2405 return;
2406 }
2407
2408 // TODO: What should we do if we've already switched to this network because we had no
2409 // better option? There are two obvious alternatives.
2410 //
2411 // 1. Decide that there's no point prompting because this is our only usable network.
2412 // However, because we didn't prompt, if later on a validated network comes along, we'll
2413 // either a) silently switch to it - bad if the user wanted to connect to stay on this
2414 // unvalidated network - or b) prompt the user at that later time - bad because the user
2415 // might not understand why they are now being prompted.
2416 //
2417 // 2. Always prompt the user, even if we have no other network to use. The user could then
2418 // try to find an alternative network to join (remember, if we got here, then the user
2419 // selected this network manually). This is bad because the prompt isn't really very
2420 // useful.
2421 //
2422 // For now we do #1, but we can revisit that later.
2423 if (isDefaultNetwork(nai)) {
2424 return;
2425 }
2426
2427 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
2428 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, network);
2429 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2430 intent.setClassName("com.android.settings",
2431 "com.android.settings.wifi.WifiNoInternetDialog");
2432 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
2433 }
2434
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002435 private class InternalHandler extends Handler {
2436 public InternalHandler(Looper looper) {
2437 super(looper);
2438 }
2439
2440 @Override
2441 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002442 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002443 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002444 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002445 String causedBy = null;
2446 synchronized (ConnectivityService.this) {
2447 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2448 mNetTransitionWakeLock.isHeld()) {
2449 mNetTransitionWakeLock.release();
2450 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002451 } else {
2452 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002453 }
2454 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002455 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2456 log("Failed to find a new network - expiring NetTransition Wakelock");
2457 } else {
2458 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2459 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002460 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002461 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002462 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002463 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002464 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002465 break;
2466 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002467 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002468 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002469 sendStickyBroadcast(intent);
2470 break;
2471 }
Jason Monkdecd2952013-10-10 14:02:51 -04002472 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002473 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002474 break;
2475 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002476 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002477 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2478 break;
2479 }
2480 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2481 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002482 break;
2483 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002484 case EVENT_REGISTER_NETWORK_AGENT: {
2485 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2486 break;
2487 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002488 case EVENT_REGISTER_NETWORK_REQUEST:
2489 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002490 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002491 break;
2492 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002493 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: {
2494 handleRegisterNetworkRequestWithIntent(msg);
2495 break;
2496 }
2497 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2498 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2499 break;
2500 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002501 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002502 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002503 break;
2504 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002505 case EVENT_SET_ACCEPT_UNVALIDATED: {
2506 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2507 break;
2508 }
2509 case EVENT_PROMPT_UNVALIDATED: {
2510 handlePromptUnvalidated((Network) msg.obj);
2511 break;
2512 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002513 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2514 handleMobileDataAlwaysOn();
2515 break;
2516 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002517 case EVENT_SYSTEM_READY: {
2518 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2519 nai.networkMonitor.systemReady = true;
2520 }
2521 break;
2522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 }
2524 }
2525 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002526
2527 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002528 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002529 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002530 if (isTetheringSupported()) {
2531 return mTethering.tether(iface);
2532 } else {
2533 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2534 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002535 }
2536
2537 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002538 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002539 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002540
2541 if (isTetheringSupported()) {
2542 return mTethering.untether(iface);
2543 } else {
2544 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2545 }
2546 }
2547
2548 // javadoc from interface
2549 public int getLastTetherError(String iface) {
2550 enforceTetherAccessPermission();
2551
2552 if (isTetheringSupported()) {
2553 return mTethering.getLastTetherError(iface);
2554 } else {
2555 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2556 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002557 }
2558
2559 // TODO - proper iface API for selection by property, inspection, etc
2560 public String[] getTetherableUsbRegexs() {
2561 enforceTetherAccessPermission();
2562 if (isTetheringSupported()) {
2563 return mTethering.getTetherableUsbRegexs();
2564 } else {
2565 return new String[0];
2566 }
2567 }
2568
2569 public String[] getTetherableWifiRegexs() {
2570 enforceTetherAccessPermission();
2571 if (isTetheringSupported()) {
2572 return mTethering.getTetherableWifiRegexs();
2573 } else {
2574 return new String[0];
2575 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002576 }
2577
Danica Chang6fdd0c62010-08-11 14:54:43 -07002578 public String[] getTetherableBluetoothRegexs() {
2579 enforceTetherAccessPermission();
2580 if (isTetheringSupported()) {
2581 return mTethering.getTetherableBluetoothRegexs();
2582 } else {
2583 return new String[0];
2584 }
2585 }
2586
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002587 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002588 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002589 if (isTetheringSupported()) {
2590 return mTethering.setUsbTethering(enable);
2591 } else {
2592 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2593 }
2594 }
2595
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002596 // TODO - move iface listing, queries, etc to new module
2597 // javadoc from interface
2598 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002599 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002600 return mTethering.getTetherableIfaces();
2601 }
2602
2603 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002604 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002605 return mTethering.getTetheredIfaces();
2606 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002607
Robert Greenwalt5a735062010-03-02 17:25:02 -08002608 public String[] getTetheringErroredIfaces() {
2609 enforceTetherAccessPermission();
2610 return mTethering.getErroredIfaces();
2611 }
2612
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002613 public String[] getTetheredDhcpRanges() {
2614 enforceConnectivityInternalPermission();
2615 return mTethering.getTetheredDhcpRanges();
2616 }
2617
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002618 // if ro.tether.denied = true we default to no tethering
2619 // gservices could set the secure setting to 1 though to enable it on a build where it
2620 // had previously been turned off.
2621 public boolean isTetheringSupported() {
2622 enforceTetherAccessPermission();
2623 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002624 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002625 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2626 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002627 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2628 mTethering.getTetherableWifiRegexs().length != 0 ||
2629 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2630 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002631 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002632
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002633 // Called when we lose the default network and have no replacement yet.
2634 // This will automatically be cleared after X seconds or a new default network
2635 // becomes CONNECTED, whichever happens first. The timer is started by the
2636 // first caller and not restarted by subsequent callers.
2637 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002638 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002639 synchronized (this) {
2640 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002641 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002642 mNetTransitionWakeLock.acquire();
2643 mNetTransitionWakeLockCausedBy = forWhom;
2644 }
2645 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002646 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002647 mNetTransitionWakeLockTimeout);
2648 return;
2649 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002650
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002651 // 100 percent is full good, 0 is full bad.
2652 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002653 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002654 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002655 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002656 }
2657
Paul Jensenbfd17b72015-04-07 12:43:13 -04002658 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002659 enforceAccessPermission();
2660 enforceInternetPermission();
2661
Paul Jensenbfd17b72015-04-07 12:43:13 -04002662 NetworkAgentInfo nai;
2663 if (network == null) {
2664 nai = getDefaultNetwork();
2665 } else {
2666 nai = getNetworkAgentInfoForNetwork(network);
2667 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002668 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002669 // Revalidate if the app report does not match our current validated state.
2670 if (hasConnectivity == nai.lastValidated) return;
2671 final int uid = Binder.getCallingUid();
2672 if (DBG) {
2673 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2674 ") by " + uid);
2675 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002676 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002677 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2678 // which isn't meant to work on uncreated networks.
2679 if (!nai.created) return;
2680
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002681 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002682
2683 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2684 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002685 }
2686
Paul Jensen25a217c2015-02-27 22:55:47 -05002687 public void captivePortalAppResponse(Network network, int response, String actionToken) {
2688 if (response == ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS) {
2689 enforceConnectivityInternalPermission();
2690 }
2691 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2692 if (nai == null) return;
2693 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_CAPTIVE_PORTAL_APP_FINISHED, response, 0,
2694 actionToken);
2695 }
2696
Paul Jensencee9b512015-05-06 07:32:40 -04002697 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002698 // this information is already available as a world read/writable jvm property
2699 // so this API change wouldn't have a benifit. It also breaks the passing
2700 // of proxy info to all the JVMs.
2701 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002702 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002703 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002704 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2705 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002706 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002707 }
2708
Paul Jensencee9b512015-05-06 07:32:40 -04002709 public ProxyInfo getProxyForNetwork(Network network) {
2710 if (network == null) return getDefaultProxy();
2711 final ProxyInfo globalProxy = getGlobalProxy();
2712 if (globalProxy != null) return globalProxy;
2713 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2714 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2715 // caller may not have.
2716 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2717 if (nai == null) return null;
2718 synchronized (nai) {
2719 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2720 if (proxyInfo == null) return null;
2721 return new ProxyInfo(proxyInfo);
2722 }
2723 }
2724
Paul Jensene0bef712014-12-10 15:12:18 -05002725 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2726 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2727 // proxy is null then there is no proxy in place).
2728 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2729 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2730 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2731 proxy = null;
2732 }
2733 return proxy;
2734 }
2735
2736 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2737 // better for determining if a new proxy broadcast is necessary:
2738 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2739 // avoid unnecessary broadcasts.
2740 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2741 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2742 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2743 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2744 // all set.
2745 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2746 a = canonicalizeProxyInfo(a);
2747 b = canonicalizeProxyInfo(b);
2748 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2749 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2750 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2751 }
2752
Jason Monk207900c2014-04-25 15:00:09 -04002753 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002754 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002755
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002756 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002757 if (proxyProperties == mGlobalProxy) return;
2758 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2759 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2760
2761 String host = "";
2762 int port = 0;
2763 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002764 String pacFileUrl = "";
2765 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002766 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002767 if (!proxyProperties.isValid()) {
2768 if (DBG)
2769 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2770 return;
2771 }
Jason Monk207900c2014-04-25 15:00:09 -04002772 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002773 host = mGlobalProxy.getHost();
2774 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002775 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002776 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002777 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002778 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002779 } else {
2780 mGlobalProxy = null;
2781 }
2782 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002783 final long token = Binder.clearCallingIdentity();
2784 try {
2785 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2786 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2787 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2788 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002789 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002790 } finally {
2791 Binder.restoreCallingIdentity(token);
2792 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002793
Jason Monkcf0f97a2014-10-02 15:39:38 -04002794 if (mGlobalProxy == null) {
2795 proxyProperties = mDefaultProxy;
2796 }
2797 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002798 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002799 }
2800
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002801 private void loadGlobalProxy() {
2802 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002803 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2804 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2805 String exclList = Settings.Global.getString(res,
2806 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002807 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2808 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002809 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002810 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002811 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002812 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002813 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002814 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002815 if (!proxyProperties.isValid()) {
2816 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2817 return;
2818 }
2819
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002820 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002821 mGlobalProxy = proxyProperties;
2822 }
2823 }
2824 }
2825
Jason Monk207900c2014-04-25 15:00:09 -04002826 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002827 // this information is already available as a world read/writable jvm property
2828 // so this API change wouldn't have a benifit. It also breaks the passing
2829 // of proxy info to all the JVMs.
2830 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002831 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002832 return mGlobalProxy;
2833 }
2834 }
2835
Jason Monk207900c2014-04-25 15:00:09 -04002836 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002837 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002838 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002839 proxy = null;
2840 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002841 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002842 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002843 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002844 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002845 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2846 return;
2847 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002848
2849 // This call could be coming from the PacManager, containing the port of the local
2850 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2851 // global (to get the correct local port), and send a broadcast.
2852 // TODO: Switch PacManager to have its own message to send back rather than
2853 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002854 if ((mGlobalProxy != null) && (proxy != null)
2855 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002856 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2857 mGlobalProxy = proxy;
2858 sendProxyBroadcast(mGlobalProxy);
2859 return;
2860 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002861 mDefaultProxy = proxy;
2862
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002863 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002864 if (!mDefaultProxyDisabled) {
2865 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002866 }
2867 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002868 }
2869
Paul Jensene0bef712014-12-10 15:12:18 -05002870 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2871 // This method gets called when any network changes proxy, but the broadcast only ever contains
2872 // the default proxy (even if it hasn't changed).
2873 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2874 // world where an app might be bound to a non-default network.
2875 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2876 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2877 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2878
2879 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2880 sendProxyBroadcast(getDefaultProxy());
2881 }
2882 }
2883
Robert Greenwalt434203a2010-10-11 16:00:27 -07002884 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002885 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2886 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002887 if (!TextUtils.isEmpty(proxy)) {
2888 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002889 if (data.length == 0) {
2890 return;
2891 }
2892
Robert Greenwalt434203a2010-10-11 16:00:27 -07002893 String proxyHost = data[0];
2894 int proxyPort = 8080;
2895 if (data.length > 1) {
2896 try {
2897 proxyPort = Integer.parseInt(data[1]);
2898 } catch (NumberFormatException e) {
2899 return;
2900 }
2901 }
Jason Monk207900c2014-04-25 15:00:09 -04002902 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002903 setGlobalProxy(p);
2904 }
2905 }
2906
Jason Monk207900c2014-04-25 15:00:09 -04002907 private void sendProxyBroadcast(ProxyInfo proxy) {
2908 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002909 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002910 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002911 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002912 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2913 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002914 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002915 final long ident = Binder.clearCallingIdentity();
2916 try {
2917 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2918 } finally {
2919 Binder.restoreCallingIdentity(ident);
2920 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002921 }
2922
2923 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002924 final private HashMap<Uri, Integer> mUriEventMap;
2925 final private Context mContext;
2926 final private Handler mHandler;
2927
2928 SettingsObserver(Context context, Handler handler) {
2929 super(null);
2930 mUriEventMap = new HashMap<Uri, Integer>();
2931 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002932 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002933 }
2934
Erik Klineda4bfa82015-04-30 12:58:40 +09002935 void observe(Uri uri, int what) {
2936 mUriEventMap.put(uri, what);
2937 final ContentResolver resolver = mContext.getContentResolver();
2938 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002939 }
2940
2941 @Override
2942 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002943 Slog.wtf(TAG, "Should never be reached.");
2944 }
2945
2946 @Override
2947 public void onChange(boolean selfChange, Uri uri) {
2948 final Integer what = mUriEventMap.get(uri);
2949 if (what != null) {
2950 mHandler.obtainMessage(what.intValue()).sendToTarget();
2951 } else {
2952 loge("No matching event to send for URI=" + uri);
2953 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002954 }
2955 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002956
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002957 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002958 Slog.d(TAG, s);
2959 }
2960
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002961 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002962 Slog.e(TAG, s);
2963 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002964
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002965 private static <T> T checkNotNull(T value, String message) {
2966 if (value == null) {
2967 throw new NullPointerException(message);
2968 }
2969 return value;
2970 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002971
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002972 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002973 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01002974 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2975 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2976 *
2977 * @param oldPackage Package name of the application which currently controls VPN, which will
2978 * be replaced. If there is no such application, this should should either be
2979 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
2980 * @param newPackage Package name of the application which should gain control of VPN, or
2981 * {@code null} to disable.
2982 * @param userId User for whom to prepare the new VPN.
2983 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002984 * @hide
2985 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002986 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01002987 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
2988 int userId) {
2989 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002990 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01002991
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002992 synchronized(mVpns) {
Robin Lee3b3dd942015-05-12 18:14:58 +01002993 return mVpns.get(userId).prepare(oldPackage, newPackage);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002994 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002995 }
2996
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002997 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01002998 * Set whether the VPN package has the ability to launch VPNs without user intervention.
2999 * This method is used by system-privileged apps.
3000 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3001 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3002 *
3003 * @param packageName The package for which authorization state should change.
3004 * @param userId User for whom {@code packageName} is installed.
3005 * @param authorized {@code true} if this app should be able to start a VPN connection without
3006 * explicit user approval, {@code false} if not.
3007 *
Jeff Davidson05542602014-08-11 14:07:27 -07003008 * @hide
3009 */
3010 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003011 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3012 enforceCrossUserPermission(userId);
3013
Jeff Davidson05542602014-08-11 14:07:27 -07003014 synchronized(mVpns) {
Robin Lee3b3dd942015-05-12 18:14:58 +01003015 mVpns.get(userId).setPackageAuthorization(packageName, authorized);
Jeff Davidson05542602014-08-11 14:07:27 -07003016 }
3017 }
3018
3019 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003020 * Configure a TUN interface and return its file descriptor. Parameters
3021 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003022 * and not available in ConnectivityManager. Permissions are checked in
3023 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003024 * @hide
3025 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003026 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003027 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003028 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003029 int user = UserHandle.getUserId(Binder.getCallingUid());
3030 synchronized(mVpns) {
3031 return mVpns.get(user).establish(config);
3032 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003033 }
3034
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003035 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003036 * Start legacy VPN, controlling native daemons as needed. Creates a
3037 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003038 */
3039 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003040 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003041 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003042 final LinkProperties egress = getActiveLinkProperties();
3043 if (egress == null) {
3044 throw new IllegalStateException("Missing active network connection");
3045 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003046 int user = UserHandle.getUserId(Binder.getCallingUid());
3047 synchronized(mVpns) {
3048 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3049 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003050 }
3051
3052 /**
3053 * Return the information of the ongoing legacy VPN. This method is used
3054 * by VpnSettings and not available in ConnectivityManager. Permissions
3055 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003056 */
3057 @Override
3058 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003059 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003060 int user = UserHandle.getUserId(Binder.getCallingUid());
3061 synchronized(mVpns) {
3062 return mVpns.get(user).getLegacyVpnInfo();
3063 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003064 }
3065
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003066 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003067 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3068 * and not available in ConnectivityManager.
3069 */
3070 @Override
3071 public VpnInfo[] getAllVpnInfo() {
3072 enforceConnectivityInternalPermission();
3073 if (mLockdownEnabled) {
3074 return new VpnInfo[0];
3075 }
3076
3077 synchronized(mVpns) {
3078 List<VpnInfo> infoList = new ArrayList<>();
3079 for (int i = 0; i < mVpns.size(); i++) {
3080 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3081 if (info != null) {
3082 infoList.add(info);
3083 }
3084 }
3085 return infoList.toArray(new VpnInfo[infoList.size()]);
3086 }
3087 }
3088
3089 /**
3090 * @return VPN information for accounting, or null if we can't retrieve all required
3091 * information, e.g primary underlying iface.
3092 */
3093 @Nullable
3094 private VpnInfo createVpnInfo(Vpn vpn) {
3095 VpnInfo info = vpn.getVpnInfo();
3096 if (info == null) {
3097 return null;
3098 }
3099 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3100 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3101 // the underlyingNetworks list.
3102 if (underlyingNetworks == null) {
3103 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3104 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3105 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3106 }
3107 } else if (underlyingNetworks.length > 0) {
3108 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3109 if (linkProperties != null) {
3110 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3111 }
3112 }
3113 return info.primaryUnderlyingIface == null ? null : info;
3114 }
3115
3116 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003117 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3118 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003119 * Permissions are checked in Vpn class.
3120 * @hide
3121 */
3122 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003123 public VpnConfig getVpnConfig(int userId) {
3124 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003125 synchronized(mVpns) {
Robin Lee3b3dd942015-05-12 18:14:58 +01003126 return mVpns.get(userId).getVpnConfig();
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003127 }
3128 }
3129
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003130 @Override
3131 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003132 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3133 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3134 return false;
3135 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003136
3137 // Tear down existing lockdown if profile was removed
3138 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3139 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003140 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003141 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3142 return false;
3143 }
3144
3145 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3146 final VpnProfile profile = VpnProfile.decode(
3147 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003148 int user = UserHandle.getUserId(Binder.getCallingUid());
3149 synchronized(mVpns) {
3150 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3151 profile));
3152 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003153 } else {
3154 setLockdownTracker(null);
3155 }
3156
3157 return true;
3158 }
3159
3160 /**
3161 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3162 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3163 */
3164 private void setLockdownTracker(LockdownVpnTracker tracker) {
3165 // Shutdown any existing tracker
3166 final LockdownVpnTracker existing = mLockdownTracker;
3167 mLockdownTracker = null;
3168 if (existing != null) {
3169 existing.shutdown();
3170 }
3171
3172 try {
3173 if (tracker != null) {
3174 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003175 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003176 mLockdownTracker = tracker;
3177 mLockdownTracker.init();
3178 } else {
3179 mNetd.setFirewallEnabled(false);
3180 }
3181 } catch (RemoteException e) {
3182 // ignored; NMS lives inside system_server
3183 }
3184 }
3185
3186 private void throwIfLockdownEnabled() {
3187 if (mLockdownEnabled) {
3188 throw new IllegalStateException("Unavailable in lockdown mode");
3189 }
3190 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003191
Wink Savilleab9321d2013-06-29 21:10:57 -07003192 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003193 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003194 // TODO: Remove? Any reason to trigger a provisioning check?
3195 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003196 }
3197
3198 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3199 private volatile boolean mIsNotificationVisible = false;
3200
Paul Jensen89e0f092014-09-15 15:59:36 -04003201 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003202 if (DBG) {
3203 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003204 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003205 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003206 Intent intent = new Intent(action);
3207 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003208 // Concatenate the range of types onto the range of NetIDs.
3209 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Paul Jensen89e0f092014-09-15 15:59:36 -04003210 setProvNotificationVisibleIntent(visible, id, networkType, null, pendingIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003211 }
3212
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003213 /**
3214 * Show or hide network provisioning notificaitons.
3215 *
3216 * @param id an identifier that uniquely identifies this notification. This must match
3217 * between show and hide calls. We use the NetID value but for legacy callers
3218 * we concatenate the range of types with the range of NetIDs.
3219 */
3220 private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType,
Paul Jensen869868be2014-05-15 10:33:05 -04003221 String extraInfo, PendingIntent intent) {
3222 if (DBG) {
3223 log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
3224 networkType + " extraInfo=" + extraInfo);
3225 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003226
3227 Resources r = Resources.getSystem();
3228 NotificationManager notificationManager = (NotificationManager) mContext
3229 .getSystemService(Context.NOTIFICATION_SERVICE);
3230
3231 if (visible) {
3232 CharSequence title;
3233 CharSequence details;
3234 int icon;
Wink Saville948282b2013-08-29 08:55:16 -07003235 Notification notification = new Notification();
3236 switch (networkType) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003237 case ConnectivityManager.TYPE_WIFI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003238 title = r.getString(R.string.wifi_available_sign_in, 0);
3239 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003240 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003241 icon = R.drawable.stat_notify_wifi_in_range;
3242 break;
3243 case ConnectivityManager.TYPE_MOBILE:
3244 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003245 title = r.getString(R.string.network_available_sign_in, 0);
3246 // TODO: Change this to pull from NetworkInfo once a printable
3247 // name has been added to it
3248 details = mTelephonyManager.getNetworkOperatorName();
3249 icon = R.drawable.stat_notify_rssi_in_range;
3250 break;
3251 default:
Wink Savilleab9321d2013-06-29 21:10:57 -07003252 title = r.getString(R.string.network_available_sign_in, 0);
3253 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003254 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003255 icon = R.drawable.stat_notify_rssi_in_range;
3256 break;
3257 }
3258
Wink Savilleab9321d2013-06-29 21:10:57 -07003259 notification.when = 0;
3260 notification.icon = icon;
3261 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Savilleab9321d2013-06-29 21:10:57 -07003262 notification.tickerText = title;
Alan Viverette4a357cd2015-03-18 18:37:18 -07003263 notification.color = mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02003264 com.android.internal.R.color.system_notification_accent_color);
Wink Savilleab9321d2013-06-29 21:10:57 -07003265 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003266 notification.contentIntent = intent;
Wink Savilleab9321d2013-06-29 21:10:57 -07003267
Wink Saville948282b2013-08-29 08:55:16 -07003268 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003269 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003270 } catch (NullPointerException npe) {
3271 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
3272 npe.printStackTrace();
3273 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003274 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003275 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003276 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003277 } catch (NullPointerException npe) {
3278 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
3279 npe.printStackTrace();
3280 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003281 }
Wink Saville948282b2013-08-29 08:55:16 -07003282 mIsNotificationVisible = visible;
Wink Savilleab9321d2013-06-29 21:10:57 -07003283 }
3284
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003285 /** Location to an updatable file listing carrier provisioning urls.
3286 * An example:
3287 *
3288 * <?xml version="1.0" encoding="utf-8"?>
3289 * <provisioningUrls>
3290 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
3291 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
3292 * </provisioningUrls>
3293 */
3294 private static final String PROVISIONING_URL_PATH =
3295 "/data/misc/radio/provisioning_urls.xml";
3296 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003297
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003298 /** XML tag for root element. */
3299 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3300 /** XML tag for individual url */
3301 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3302 /** XML tag for redirected url */
3303 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
3304 /** XML attribute for mcc */
3305 private static final String ATTR_MCC = "mcc";
3306 /** XML attribute for mnc */
3307 private static final String ATTR_MNC = "mnc";
3308
3309 private static final int REDIRECTED_PROVISIONING = 1;
3310 private static final int PROVISIONING = 2;
3311
3312 private String getProvisioningUrlBaseFromFile(int type) {
3313 FileReader fileReader = null;
3314 XmlPullParser parser = null;
3315 Configuration config = mContext.getResources().getConfiguration();
3316 String tagType;
3317
3318 switch (type) {
3319 case PROVISIONING:
3320 tagType = TAG_PROVISIONING_URL;
3321 break;
3322 case REDIRECTED_PROVISIONING:
3323 tagType = TAG_REDIRECTED_URL;
3324 break;
3325 default:
3326 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
3327 type);
3328 }
3329
3330 try {
3331 fileReader = new FileReader(mProvisioningUrlFile);
3332 parser = Xml.newPullParser();
3333 parser.setInput(fileReader);
3334 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3335
3336 while (true) {
3337 XmlUtils.nextElement(parser);
3338
3339 String element = parser.getName();
3340 if (element == null) break;
3341
3342 if (element.equals(tagType)) {
3343 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3344 try {
3345 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3346 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3347 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3348 parser.next();
3349 if (parser.getEventType() == XmlPullParser.TEXT) {
3350 return parser.getText();
3351 }
3352 }
3353 }
3354 } catch (NumberFormatException e) {
3355 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3356 }
3357 }
3358 }
3359 return null;
3360 } catch (FileNotFoundException e) {
3361 loge("Carrier Provisioning Urls file not found");
3362 } catch (XmlPullParserException e) {
3363 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3364 } catch (IOException e) {
3365 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3366 } finally {
3367 if (fileReader != null) {
3368 try {
3369 fileReader.close();
3370 } catch (IOException e) {}
3371 }
3372 }
3373 return null;
3374 }
3375
Wink Saville42d4f082013-07-20 20:31:59 -07003376 @Override
3377 public String getMobileRedirectedProvisioningUrl() {
3378 enforceConnectivityInternalPermission();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003379 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
3380 if (TextUtils.isEmpty(url)) {
3381 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
3382 }
3383 return url;
3384 }
3385
Wink Saville42d4f082013-07-20 20:31:59 -07003386 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003387 public String getMobileProvisioningUrl() {
3388 enforceConnectivityInternalPermission();
3389 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
3390 if (TextUtils.isEmpty(url)) {
3391 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003392 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003393 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003394 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003395 }
Wink Saville8cf35602013-07-10 23:00:07 -07003396 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003397 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003398 String phoneNumber = mTelephonyManager.getLine1Number();
3399 if (TextUtils.isEmpty(phoneNumber)) {
3400 phoneNumber = "0000000000";
3401 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003402 url = String.format(url,
3403 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3404 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003405 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003406 }
3407
Wink Savilleab9321d2013-06-29 21:10:57 -07003408 return url;
3409 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003410
Wink Saville948282b2013-08-29 08:55:16 -07003411 @Override
3412 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003413 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003414 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003415 final long ident = Binder.clearCallingIdentity();
3416 try {
3417 setProvNotificationVisible(visible, networkType, action);
3418 } finally {
3419 Binder.restoreCallingIdentity(ident);
3420 }
Wink Saville948282b2013-08-29 08:55:16 -07003421 }
Wink Saville7788c612013-08-29 14:57:08 -07003422
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003423 @Override
3424 public void setAirplaneMode(boolean enable) {
3425 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003426 final long ident = Binder.clearCallingIdentity();
3427 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003428 final ContentResolver cr = mContext.getContentResolver();
3429 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3430 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3431 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003432 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003433 } finally {
3434 Binder.restoreCallingIdentity(ident);
3435 }
3436 }
3437
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003438 private void onUserStart(int userId) {
3439 synchronized(mVpns) {
3440 Vpn userVpn = mVpns.get(userId);
3441 if (userVpn != null) {
3442 loge("Starting user already has a VPN");
3443 return;
3444 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003445 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003446 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003447 }
3448 }
3449
3450 private void onUserStop(int userId) {
3451 synchronized(mVpns) {
3452 Vpn userVpn = mVpns.get(userId);
3453 if (userVpn == null) {
3454 loge("Stopping user has no VPN");
3455 return;
3456 }
3457 mVpns.delete(userId);
3458 }
3459 }
3460
3461 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3462 @Override
3463 public void onReceive(Context context, Intent intent) {
3464 final String action = intent.getAction();
3465 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3466 if (userId == UserHandle.USER_NULL) return;
3467
3468 if (Intent.ACTION_USER_STARTING.equals(action)) {
3469 onUserStart(userId);
3470 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3471 onUserStop(userId);
3472 }
3473 }
3474 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003475
Robert Greenwalta67be032014-05-16 15:49:14 -07003476 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3477 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003478 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3479 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003480
Robert Greenwalta67be032014-05-16 15:49:14 -07003481 private static class NetworkFactoryInfo {
3482 public final String name;
3483 public final Messenger messenger;
3484 public final AsyncChannel asyncChannel;
3485
3486 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3487 this.name = name;
3488 this.messenger = messenger;
3489 this.asyncChannel = asyncChannel;
3490 }
3491 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003492
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003493 /**
3494 * Tracks info about the requester.
3495 * Also used to notice when the calling process dies so we can self-expire
3496 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003497 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3498 static final boolean REQUEST = true;
3499 static final boolean LISTEN = false;
3500
3501 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003502 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003503 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003504 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003505 final int mPid;
3506 final int mUid;
3507 final Messenger messenger;
3508 final boolean isRequest;
3509
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003510 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3511 request = r;
3512 mPendingIntent = pi;
3513 messenger = null;
3514 mBinder = null;
3515 mPid = getCallingPid();
3516 mUid = getCallingUid();
3517 this.isRequest = isRequest;
3518 }
3519
Robert Greenwalt9258c642014-03-26 16:47:06 -07003520 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3521 super();
3522 messenger = m;
3523 request = r;
3524 mBinder = binder;
3525 mPid = getCallingPid();
3526 mUid = getCallingUid();
3527 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003528 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003529
3530 try {
3531 mBinder.linkToDeath(this, 0);
3532 } catch (RemoteException e) {
3533 binderDied();
3534 }
3535 }
3536
3537 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003538 if (mBinder != null) {
3539 mBinder.unlinkToDeath(this, 0);
3540 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003541 }
3542
3543 public void binderDied() {
3544 log("ConnectivityService NetworkRequestInfo binderDied(" +
3545 request + ", " + mBinder + ")");
3546 releaseNetworkRequest(request);
3547 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003548
3549 public String toString() {
3550 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003551 mPid + " for " + request +
3552 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003553 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003554 }
3555
3556 @Override
3557 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003558 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003559 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003560 enforceNetworkRequestPermissions(networkCapabilities);
3561 enforceMeteredApnPolicy(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003562
Robert Greenwalt6078b502014-06-11 16:05:07 -07003563 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003564 throw new IllegalArgumentException("Bad timeout specified");
3565 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003566
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003567 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3568 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003569 if (DBG) log("requestNetwork for " + networkRequest);
3570 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3571 NetworkRequestInfo.REQUEST);
3572
3573 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003574 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003575 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003576 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003577 }
3578 return networkRequest;
3579 }
3580
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003581 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003582 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003583 enforceConnectivityInternalPermission();
3584 } else {
3585 enforceChangePermission();
3586 }
3587 }
3588
fenglub15e72b2015-03-20 11:29:56 -07003589 @Override
fengludb571472015-04-21 17:12:05 -07003590 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003591 enforceAccessPermission();
3592 NetworkAgentInfo nai = null;
3593 if (network == null) {
3594 return false;
3595 }
3596 synchronized (mNetworkForNetId) {
3597 nai = mNetworkForNetId.get(network.netId);
3598 }
3599 if (nai != null) {
3600 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3601 return true;
3602 }
3603 return false;
3604 }
3605
3606
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003607 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3608 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003609 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003610 final int uidRules;
3611 final int uid = Binder.getCallingUid();
3612 synchronized(mRulesLock) {
3613 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3614 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003615 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003616 // we could silently fail or we can filter the available nets to only give
3617 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003618 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003619 }
3620 }
3621 }
3622
Robert Greenwalt9258c642014-03-26 16:47:06 -07003623 @Override
3624 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3625 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003626 checkNotNull(operation, "PendingIntent cannot be null.");
3627 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3628 enforceNetworkRequestPermissions(networkCapabilities);
3629 enforceMeteredApnPolicy(networkCapabilities);
3630
3631 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3632 nextNetworkRequestId());
3633 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3634 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3635 NetworkRequestInfo.REQUEST);
3636 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3637 nri));
3638 return networkRequest;
3639 }
3640
Jeremy Joslin79294842014-12-03 17:15:28 -08003641 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3642 mHandler.sendMessageDelayed(
3643 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3644 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3645 }
3646
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003647 @Override
3648 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003649 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003650 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3651 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003652 }
3653
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003654 // In order to implement the compatibility measure for pre-M apps that call
3655 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3656 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3657 // This ensures it has permission to do so.
3658 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3659 if (nc == null) {
3660 return false;
3661 }
3662 int[] transportTypes = nc.getTransportTypes();
3663 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3664 return false;
3665 }
3666 try {
3667 mContext.enforceCallingOrSelfPermission(
3668 android.Manifest.permission.ACCESS_WIFI_STATE,
3669 "ConnectivityService");
3670 } catch (SecurityException e) {
3671 return false;
3672 }
3673 return true;
3674 }
3675
Robert Greenwalt9258c642014-03-26 16:47:06 -07003676 @Override
3677 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3678 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003679 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3680 enforceAccessPermission();
3681 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003682
3683 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003684 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003685 if (DBG) log("listenForNetwork for " + networkRequest);
3686 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3687 NetworkRequestInfo.LISTEN);
3688
3689 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3690 return networkRequest;
3691 }
3692
3693 @Override
3694 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3695 PendingIntent operation) {
3696 }
3697
3698 @Override
3699 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003700 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3701 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003702 }
3703
3704 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003705 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003706 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003707 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3708 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003709 }
3710
Robert Greenwalta67be032014-05-16 15:49:14 -07003711 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003712 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003713 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3714 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3715 }
3716
3717 @Override
3718 public void unregisterNetworkFactory(Messenger messenger) {
3719 enforceConnectivityInternalPermission();
3720 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3721 }
3722
3723 private void handleUnregisterNetworkFactory(Messenger messenger) {
3724 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3725 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003726 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003727 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003728 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003729 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003730 }
3731
Robert Greenwalt7b816022014-04-18 15:25:25 -07003732 /**
3733 * NetworkAgentInfo supporting a request by requestId.
3734 * These have already been vetted (their Capabilities satisfy the request)
3735 * and the are the highest scored network available.
3736 * the are keyed off the Requests requestId.
3737 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003738 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003739 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3740 new SparseArray<NetworkAgentInfo>();
3741
Paul Jensen31a94f42015-02-13 14:18:39 -05003742 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3743 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003744 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3745 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003746 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3747 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3748 // there may not be a strict 1:1 correlation between the two.
3749 @GuardedBy("mNetworkForNetId")
3750 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003751
Robert Greenwalt7b816022014-04-18 15:25:25 -07003752 // NetworkAgentInfo keyed off its connecting messenger
3753 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003754 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003755 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3756 new HashMap<Messenger, NetworkAgentInfo>();
3757
Paul Jensen2c311d62014-11-17 12:34:51 -05003758 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003759 private final NetworkRequest mDefaultRequest;
3760
Erik Klineda4bfa82015-04-30 12:58:40 +09003761 // Request used to optionally keep mobile data active even when higher
3762 // priority networks like Wi-Fi are active.
3763 private final NetworkRequest mDefaultMobileDataRequest;
3764
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003765 private NetworkAgentInfo getDefaultNetwork() {
3766 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3767 }
3768
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003769 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003770 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003771 }
3772
Paul Jensen31a94f42015-02-13 14:18:39 -05003773 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003774 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003775 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003776 enforceConnectivityInternalPermission();
3777
Paul Jensen2c311d62014-11-17 12:34:51 -05003778 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3779 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003780 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003781 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3782 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3783 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003784 synchronized (this) {
3785 nai.networkMonitor.systemReady = mSystemReady;
3786 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003787 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003788 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003789 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003790 }
3791
3792 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3793 if (VDBG) log("Got NetworkAgent Messenger");
3794 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003795 synchronized (mNetworkForNetId) {
3796 mNetworkForNetId.put(na.network.netId, na);
3797 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003798 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3799 NetworkInfo networkInfo = na.networkInfo;
3800 na.networkInfo = null;
3801 updateNetworkInfo(na, networkInfo);
3802 }
3803
3804 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3805 LinkProperties newLp = networkAgent.linkProperties;
3806 int netId = networkAgent.network.netId;
3807
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003808 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3809 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003810 if (networkAgent.clatd != null) {
3811 networkAgent.clatd.fixupLinkProperties(oldLp);
3812 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003813
Paul Jensen992f2522014-04-28 10:33:11 -04003814 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003815 updateMtu(newLp, oldLp);
3816 // TODO - figure out what to do for clat
3817// for (LinkProperties lp : newLp.getStackedLinks()) {
3818// updateMtu(lp, null);
3819// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003820 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003821
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003822 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3823 // In L, we used it only when the network had Internet access but provided no DNS servers.
3824 // For now, just disable it, and if disabling it doesn't break things, remove it.
3825 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3826 // NET_CAPABILITY_INTERNET);
3827 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003828 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003829 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3830
Paul Jensen3b759822014-05-13 11:44:01 -04003831 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003832 if (isDefaultNetwork(networkAgent)) {
3833 handleApplyDefaultProxy(newLp.getHttpProxy());
3834 } else {
3835 updateProxy(newLp, oldLp, networkAgent);
3836 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003837 // TODO - move this check to cover the whole function
3838 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003839 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003840 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3841 }
Paul Jensen3b759822014-05-13 11:44:01 -04003842 }
3843
Lorenzo Colitti95439462014-10-09 13:44:48 +09003844 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3845 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3846 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003847
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003848 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003849 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3850 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003851 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003852 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003853 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003854 }
Paul Jensen992f2522014-04-28 10:33:11 -04003855
3856 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3857 CompareResult<String> interfaceDiff = new CompareResult<String>();
3858 if (oldLp != null) {
3859 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3860 } else if (newLp != null) {
3861 interfaceDiff.added = newLp.getAllInterfaceNames();
3862 }
3863 for (String iface : interfaceDiff.added) {
3864 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003865 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003866 mNetd.addInterfaceToNetwork(iface, netId);
3867 } catch (Exception e) {
3868 loge("Exception adding interface: " + e);
3869 }
3870 }
3871 for (String iface : interfaceDiff.removed) {
3872 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003873 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003874 mNetd.removeInterfaceFromNetwork(iface, netId);
3875 } catch (Exception e) {
3876 loge("Exception removing interface: " + e);
3877 }
3878 }
3879 }
3880
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003881 /**
3882 * Have netd update routes from oldLp to newLp.
3883 * @return true if routes changed between oldLp and newLp
3884 */
3885 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003886 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3887 if (oldLp != null) {
3888 routeDiff = oldLp.compareAllRoutes(newLp);
3889 } else if (newLp != null) {
3890 routeDiff.added = newLp.getAllRoutes();
3891 }
3892
3893 // add routes before removing old in case it helps with continuous connectivity
3894
3895 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3896 for (RouteInfo route : routeDiff.added) {
3897 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003898 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003899 try {
3900 mNetd.addRoute(netId, route);
3901 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003902 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3903 loge("Exception in addRoute for non-gateway: " + e);
3904 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003905 }
3906 }
3907 for (RouteInfo route : routeDiff.added) {
3908 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003909 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003910 try {
3911 mNetd.addRoute(netId, route);
3912 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003913 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3914 loge("Exception in addRoute for gateway: " + e);
3915 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003916 }
3917 }
3918
3919 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003920 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003921 try {
3922 mNetd.removeRoute(netId, route);
3923 } catch (Exception e) {
3924 loge("Exception in removeRoute: " + e);
3925 }
3926 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003927 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003928 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003929 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3930 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003931 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Robert Greenwaltdf2b8782014-06-06 10:30:11 -07003932 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003933 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003934 dnses = new ArrayList();
3935 dnses.add(mDefaultDns);
3936 if (DBG) {
3937 loge("no dns provided for netId " + netId + ", so using defaults");
3938 }
3939 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003940 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003941 try {
3942 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3943 newLp.getDomains());
3944 } catch (Exception e) {
3945 loge("Exception in setDnsServersForNetwork: " + e);
3946 }
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003947 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
3948 if (defaultNai != null && defaultNai.network.netId == netId) {
3949 setDefaultDnsSystemProperties(dnses);
3950 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003951 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003952 } else if (flush) {
3953 try {
3954 mNetd.flushNetworkDnsCache(netId);
3955 } catch (Exception e) {
3956 loge("Exception in flushNetworkDnsCache: " + e);
3957 }
3958 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003959 }
3960 }
3961
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003962 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3963 int last = 0;
3964 for (InetAddress dns : dnses) {
3965 ++last;
3966 String key = "net.dns" + last;
3967 String value = dns.getHostAddress();
3968 SystemProperties.set(key, value);
3969 }
3970 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
3971 String key = "net.dns" + i;
3972 SystemProperties.set(key, "");
3973 }
3974 mNumDnsEntries = last;
3975 }
3976
Robert Greenwalt7b816022014-04-18 15:25:25 -07003977 private void updateCapabilities(NetworkAgentInfo networkAgent,
3978 NetworkCapabilities networkCapabilities) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003979 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
3980 synchronized (networkAgent) {
3981 networkAgent.networkCapabilities = networkCapabilities;
3982 }
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003983 if (networkAgent.lastValidated) {
3984 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
3985 // There's no need to remove the capability if we think the network is unvalidated,
3986 // because NetworkAgents don't set the validated capability.
3987 }
Jeff Davidson9634abe2014-11-04 16:48:27 -08003988 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore());
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003989 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07003990 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003991 }
3992
Paul Jensenc8b9a742014-09-30 15:37:41 -04003993 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
3994 for (int i = 0; i < nai.networkRequests.size(); i++) {
3995 NetworkRequest nr = nai.networkRequests.valueAt(i);
3996 // Don't send listening requests to factories. b/17393458
3997 if (!isRequest(nr)) continue;
3998 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
3999 }
4000 }
4001
Robert Greenwalt7b816022014-04-18 15:25:25 -07004002 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4003 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004004 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004005 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4006 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004007 }
4008 }
4009
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004010 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4011 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004012 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004013 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004014 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4015 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004016 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004017 sendIntent(nri.mPendingIntent, intent);
4018 }
4019 // else not handled
4020 }
4021
4022 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4023 mPendingIntentWakeLock.acquire();
4024 try {
4025 if (DBG) log("Sending " + pendingIntent);
4026 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4027 } catch (PendingIntent.CanceledException e) {
4028 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4029 mPendingIntentWakeLock.release();
4030 releasePendingNetworkRequest(pendingIntent);
4031 }
4032 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4033 }
4034
4035 @Override
4036 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4037 String resultData, Bundle resultExtras) {
4038 if (DBG) log("Finished sending " + pendingIntent);
4039 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004040 // Release with a delay so the receiving client has an opportunity to put in its
4041 // own request.
4042 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004043 }
4044
Robert Greenwalt9258c642014-03-26 16:47:06 -07004045 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004046 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004047 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004048 Bundle bundle = new Bundle();
4049 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4050 new NetworkRequest(nri.request));
4051 Message msg = Message.obtain();
4052 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4053 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4054 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4055 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004056 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004057 case ConnectivityManager.CALLBACK_LOSING: {
4058 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4059 break;
4060 }
4061 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4062 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4063 new NetworkCapabilities(networkAgent.networkCapabilities));
4064 break;
4065 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004066 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004067 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4068 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004069 break;
4070 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004071 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004072 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004073 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004074 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004075 if (VDBG) {
4076 log("sending notification " + notifyTypeToName(notificationType) +
4077 " for " + nri.request);
4078 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004079 nri.messenger.send(msg);
4080 } catch (RemoteException e) {
4081 // may occur naturally in the race of binder death.
4082 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4083 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004084 }
4085
Paul Jensenc8b9a742014-09-30 15:37:41 -04004086 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4087 for (int i = 0; i < nai.networkRequests.size(); i++) {
4088 NetworkRequest nr = nai.networkRequests.valueAt(i);
4089 // Ignore listening requests.
4090 if (!isRequest(nr)) continue;
4091 loge("Dead network still had at least " + nr);
4092 break;
4093 }
4094 nai.asyncChannel.disconnect();
4095 }
4096
Robert Greenwalt7b816022014-04-18 15:25:25 -07004097 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4098 if (oldNetwork == null) {
4099 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4100 return;
4101 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004102 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4103 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004104 }
4105
Paul Jensen27b02b72014-07-14 12:03:33 -04004106 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004107 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004108 setupDataActivityTracking(newNetwork);
4109 try {
4110 mNetd.setDefaultNetId(newNetwork.network.netId);
4111 } catch (Exception e) {
4112 loge("Exception setting default network :" + e);
4113 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004114 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004115 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004116 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004117 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004118 }
4119
Paul Jensen2161a8e2014-09-11 11:00:39 -04004120 // Handles a network appearing or improving its score.
4121 //
4122 // - Evaluates all current NetworkRequests that can be
4123 // satisfied by newNetwork, and reassigns to newNetwork
4124 // any such requests for which newNetwork is the best.
4125 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004126 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004127 // needed. A network is needed if it is the best network for
4128 // one or more NetworkRequests, or if it is a VPN.
4129 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004130 // - Tears down newNetwork if it just became validated
Paul Jensenb10e37f2014-11-25 12:33:08 -05004131 // (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
4132 //
4133 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4134 // networks that have no chance (i.e. even if validated)
4135 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004136 //
4137 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4138 // it does not remove NetworkRequests that other Networks could better satisfy.
4139 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4140 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4141 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004142 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004143 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004144 // @param nascent indicates if newNetwork just became validated, in which case it should be
Paul Jensenb10e37f2014-11-25 12:33:08 -05004145 // torn down if unneeded.
4146 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4147 // performed to tear down unvalidated networks that have no chance (i.e. even if
4148 // validated) of becoming the highest scoring network.
4149 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
4150 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004151 if (!newNetwork.created) return;
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004152 if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004153 loge("ERROR: nascent network not validated.");
4154 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004155 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004156 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004157 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004158 if (DBG) log("rematching " + newNetwork.name());
4159 // Find and migrate to this Network any NetworkRequests for
4160 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004161 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004162 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004163 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004164 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4165 if (newNetwork == currentNetwork) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004166 if (DBG) {
4167 log("Network " + newNetwork.name() + " was already satisfying" +
4168 " request " + nri.request.requestId + ". No change.");
4169 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004170 keep = true;
4171 continue;
4172 }
4173
4174 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004175 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004176 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004177 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004178 // This is not a request, it's a callback listener.
4179 // Add it to newNetwork regardless of score.
Paul Jensen0311b2b2014-08-19 10:31:40 -04004180 newNetwork.addRequest(nri.request);
4181 continue;
4182 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004183
Robert Greenwalt7b816022014-04-18 15:25:25 -07004184 // next check if it's better than any current network we're using for
4185 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004186 if (VDBG) {
4187 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004188 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4189 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004190 }
4191 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004192 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004193 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004194 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004195 currentNetwork.networkRequests.remove(nri.request.requestId);
4196 currentNetwork.networkLingered.add(nri.request);
4197 affectedNetworks.add(currentNetwork);
4198 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004199 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004200 }
Paul Jensen573a0352015-01-08 10:49:34 -05004201 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004202 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07004203 newNetwork.addRequest(nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004204 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004205 // Tell NetworkFactories about the new score, so they can stop
4206 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004207 // TODO - this could get expensive if we have alot of requests for this
4208 // network. Think about if there is a way to reduce this. Push
4209 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004210 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004211 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004212 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004213 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004214 }
4215 }
4216 }
4217 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004218 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004219 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensen99364842014-12-09 11:43:45 -05004220 if (nai.everValidated && unneeded(nai)) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004221 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4222 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4223 } else {
Paul Jensen0cc17322014-11-25 15:26:53 -05004224 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004225 }
4226 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004227 if (keep) {
4228 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004229 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004230 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004231 synchronized (ConnectivityService.this) {
4232 // have a new default network, release the transition wakelock in
4233 // a second if it's held. The second pause is to allow apps
4234 // to reconnect over the new network
4235 if (mNetTransitionWakeLock.isHeld()) {
4236 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4237 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4238 mNetTransitionWakeLockSerialNumber, 0),
4239 1000);
4240 }
4241 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004242 }
4243
4244 // do this after the default net is switched, but
4245 // before LegacyTypeTracker sends legacy broadcasts
4246 notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
4247
4248 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004249 // Maintain the illusion: since the legacy API only
4250 // understands one network at a time, we must pretend
4251 // that the current default network disconnected before
4252 // the new one connected.
4253 if (oldDefaultNetwork != null) {
4254 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09004255 oldDefaultNetwork, true);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004256 }
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004257 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004258 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4259 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004260 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004261
4262 // Notify battery stats service about this network, both the normal
4263 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004264 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004265 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004266 final IBatteryStats bs = BatteryStatsService.getService();
4267 final int type = newNetwork.networkInfo.getType();
4268
4269 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4270 bs.noteNetworkInterfaceType(baseIface, type);
4271 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4272 final String stackedIface = stacked.getInterfaceName();
4273 bs.noteNetworkInterfaceType(stackedIface, type);
4274 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4275 }
4276 } catch (RemoteException ignored) {
4277 }
4278
Robert Greenwalt152ed372014-12-17 17:19:53 -08004279 // This has to happen after the notifyNetworkCallbacks as that tickles each
4280 // ConnectivityManager instance so that legacy requests correctly bind dns
4281 // requests to this network. The legacy users are listening for this bcast
4282 // and will generally do a dns request so they can ensureRouteToHost and if
4283 // they do that before the callbacks happen they'll use the default network.
4284 //
4285 // TODO: Is there still a race here? We send the broadcast
4286 // after sending the callback, but if the app can receive the
4287 // broadcast before the callback, it might still break.
4288 //
4289 // This *does* introduce a race where if the user uses the new api
4290 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4291 // they may get old info. Reverse this after the old startUsing api is removed.
4292 // This is on top of the multiple intent sequencing referenced in the todo above.
4293 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4294 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4295 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4296 // legacy type tracker filters out repeat adds
4297 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4298 }
4299 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004300
4301 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4302 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4303 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4304 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4305 if (newNetwork.isVPN()) {
4306 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4307 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004308 } else if (nascent == NascentState.JUST_VALIDATED) {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004309 // Only tear down newly validated networks here. Leave unvalidated to either become
Paul Jensenb10e37f2014-11-25 12:33:08 -05004310 // validated (and get evaluated against peers, one losing here), or get reaped (see
4311 // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4312 // network. Networks that have been up for a while and are validated should be torn
4313 // down via the lingering process so communication on that network is given time to
4314 // wrap up.
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004315 if (DBG) log("Validated network turns out to be unwanted. Tear it down.");
Paul Jensenc8b9a742014-09-30 15:37:41 -04004316 teardownUnneededNetwork(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004317 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004318 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4319 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen99364842014-12-09 11:43:45 -05004320 if (!nai.everValidated && unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004321 if (DBG) log("Reaping " + nai.name());
4322 teardownUnneededNetwork(nai);
4323 }
4324 }
4325 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004326 }
4327
Paul Jensen2161a8e2014-09-11 11:00:39 -04004328 // Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4329 // being disconnected.
4330 // If only one Network's score or capabilities have been modified since the last time
4331 // this function was called, pass this Network in via the "changed" arugment, otherwise
4332 // pass null.
4333 // If only one Network has been changed but its NetworkCapabilities have not changed,
4334 // pass in the Network's score (from getCurrentScore()) prior to the change via
4335 // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
4336 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4337 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4338 // to avoid the slowness. It is not simply enough to process just "changed", for
4339 // example in the case where "changed"'s score decreases and another network should begin
4340 // satifying a NetworkRequest that "changed" currently satisfies.
4341
4342 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4343 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4344 // rematchNetworkAndRequests() handles.
4345 if (changed != null && oldScore < changed.getCurrentScore()) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004346 rematchNetworkAndRequests(changed, NascentState.NOT_JUST_VALIDATED,
4347 ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004348 } else {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004349 for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4350 rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4351 NascentState.NOT_JUST_VALIDATED,
4352 // Only reap the last time through the loop. Reaping before all rematching
4353 // is complete could incorrectly teardown a network that hasn't yet been
4354 // rematched.
4355 i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4356 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004357 }
4358 }
4359 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004360
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004361 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004362 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004363 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004364 // For now only update icons for default connection.
4365 // TODO: Update WiFi and cellular icons separately. b/17237507
4366 if (!isDefaultNetwork(nai)) return;
4367
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004368 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004369 // Don't repeat publish.
4370 if (newInetCondition == mDefaultInetConditionPublished) return;
4371
4372 mDefaultInetConditionPublished = newInetCondition;
4373 sendInetConditionBroadcast(nai.networkInfo);
4374 }
4375
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004376 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4377 if (mLockdownTracker != null) {
4378 if (nai != null && nai.isVPN()) {
4379 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4380 } else {
4381 mLockdownTracker.onNetworkInfoChanged();
4382 }
4383 }
4384 }
4385
Robert Greenwalt7b816022014-04-18 15:25:25 -07004386 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4387 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004388 NetworkInfo oldInfo = null;
4389 synchronized (networkAgent) {
4390 oldInfo = networkAgent.networkInfo;
4391 networkAgent.networkInfo = newInfo;
4392 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004393 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004394
4395 if (oldInfo != null && oldInfo.getState() == state) {
4396 if (VDBG) log("ignoring duplicate network state non-change");
4397 return;
4398 }
4399 if (DBG) {
4400 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4401 (oldInfo == null ? "null" : oldInfo.getState()) +
4402 " to " + state);
4403 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004404
Paul Jenseneec75412014-08-04 12:21:19 -04004405 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004406 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004407 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004408 if (networkAgent.isVPN()) {
4409 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004410 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4411 (networkAgent.networkMisc == null ||
4412 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004413 } else {
4414 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4415 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004416 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004417 loge("Error creating network " + networkAgent.network.netId + ": "
4418 + e.getMessage());
4419 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004420 }
Paul Jenseneec75412014-08-04 12:21:19 -04004421 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004422 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004423 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004424
Paul Jensenca8f16a2014-05-09 12:47:55 -04004425 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004426 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004427
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004428 if (networkAgent.isVPN()) {
4429 // Temporarily disable the default proxy (not global).
4430 synchronized (mProxyLock) {
4431 if (!mDefaultProxyDisabled) {
4432 mDefaultProxyDisabled = true;
4433 if (mGlobalProxy == null && mDefaultProxy != null) {
4434 sendProxyBroadcast(null);
4435 }
4436 }
4437 }
4438 // TODO: support proxy per network.
4439 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004440
Paul Jensen2161a8e2014-09-11 11:00:39 -04004441 // Consider network even though it is not yet validated.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004442 rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4443 ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004444
4445 // This has to happen after matching the requests, because callbacks are just requests.
4446 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004447 } else if (state == NetworkInfo.State.DISCONNECTED ||
4448 state == NetworkInfo.State.SUSPENDED) {
4449 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004450 if (networkAgent.isVPN()) {
4451 synchronized (mProxyLock) {
4452 if (mDefaultProxyDisabled) {
4453 mDefaultProxyDisabled = false;
4454 if (mGlobalProxy == null && mDefaultProxy != null) {
4455 sendProxyBroadcast(mDefaultProxy);
4456 }
4457 }
4458 }
4459 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004460 }
4461 }
4462
Robert Greenwaltac96c522014-06-03 16:43:57 -07004463 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4464 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004465 if (score < 0) {
4466 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4467 "). Bumping score to min of 0");
4468 score = 0;
4469 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004470
Paul Jensen2161a8e2014-09-11 11:00:39 -04004471 final int oldScore = nai.getCurrentScore();
4472 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004473
Paul Jensen57a767f2014-11-19 13:01:46 -05004474 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004475
Paul Jensenc8b9a742014-09-30 15:37:41 -04004476 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004477 }
4478
Robert Greenwalt9258c642014-03-26 16:47:06 -07004479 // notify only this one new request of the current state
4480 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4481 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4482 // TODO - read state from monitor to decide what to send.
4483// if (nai.networkMonitor.isLingering()) {
4484// notifyType = NetworkCallbacks.LOSING;
4485// } else if (nai.networkMonitor.isEvaluating()) {
4486// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4487// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004488 if (nri.mPendingIntent == null) {
4489 callCallbackForRequest(nri, nai, notifyType);
4490 } else {
4491 sendPendingIntentForRequest(nri, nai, notifyType);
4492 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004493 }
4494
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004495 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004496 // The NetworkInfo we actually send out has no bearing on the real
4497 // state of affairs. For example, if the default connection is mobile,
4498 // and a request for HIPRI has just gone away, we need to pretend that
4499 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4500 // the state to DISCONNECTED, even though the network is of type MOBILE
4501 // and is still connected.
4502 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4503 info.setType(type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004504 if (connected) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004505 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004506 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004507 } else {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004508 info.setDetailedState(DetailedState.DISCONNECTED, null, info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004509 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4510 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4511 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4512 if (info.isFailover()) {
4513 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4514 nai.networkInfo.setFailover(false);
4515 }
4516 if (info.getReason() != null) {
4517 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4518 }
4519 if (info.getExtraInfo() != null) {
4520 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4521 }
4522 NetworkAgentInfo newDefaultAgent = null;
4523 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4524 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4525 if (newDefaultAgent != null) {
4526 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4527 newDefaultAgent.networkInfo);
4528 } else {
4529 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4530 }
4531 }
4532 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4533 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004534 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004535 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004536 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004537 }
4538 }
4539 }
4540
Robert Greenwalt7b816022014-04-18 15:25:25 -07004541 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004542 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004543 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004544 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4545 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4546 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004547 if (nri.mPendingIntent == null) {
4548 callCallbackForRequest(nri, networkAgent, notifyType);
4549 } else {
4550 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4551 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004552 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004553 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004554
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004555 private String notifyTypeToName(int notifyType) {
4556 switch (notifyType) {
4557 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4558 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4559 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4560 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4561 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4562 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4563 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4564 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4565 }
4566 return "UNKNOWN";
4567 }
4568
Jeff Sharkey69736342014-12-08 14:50:12 -08004569 /**
4570 * Notify other system services that set of active ifaces has changed.
4571 */
4572 private void notifyIfacesChanged() {
4573 try {
4574 mStatsService.forceUpdateIfaces();
4575 } catch (Exception ignored) {
4576 }
4577 }
4578
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004579 @Override
4580 public boolean addVpnAddress(String address, int prefixLength) {
4581 throwIfLockdownEnabled();
4582 int user = UserHandle.getUserId(Binder.getCallingUid());
4583 synchronized (mVpns) {
4584 return mVpns.get(user).addAddress(address, prefixLength);
4585 }
4586 }
4587
4588 @Override
4589 public boolean removeVpnAddress(String address, int prefixLength) {
4590 throwIfLockdownEnabled();
4591 int user = UserHandle.getUserId(Binder.getCallingUid());
4592 synchronized (mVpns) {
4593 return mVpns.get(user).removeAddress(address, prefixLength);
4594 }
4595 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004596
4597 @Override
4598 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4599 throwIfLockdownEnabled();
4600 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004601 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004602 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004603 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004604 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004605 if (success) {
4606 notifyIfacesChanged();
4607 }
4608 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004609 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004610
4611 @Override
4612 public void factoryReset() {
4613 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004614
4615 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4616 return;
4617 }
4618
Robin Lee3b3dd942015-05-12 18:14:58 +01004619 final int userId = UserHandle.getCallingUserId();
4620
Stuart Scottf1fb3972015-04-02 18:00:02 -07004621 // Turn airplane mode off
4622 setAirplaneMode(false);
4623
Stuart Scotte3e314d2015-04-20 14:07:45 -07004624 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4625 // Untether
4626 for (String tether : getTetheredIfaces()) {
4627 untether(tether);
4628 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004629 }
4630
Stuart Scotte3e314d2015-04-20 14:07:45 -07004631 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4632 // Turn VPN off
4633 VpnConfig vpnConfig = getVpnConfig(userId);
4634 if (vpnConfig != null) {
4635 if (vpnConfig.legacy) {
4636 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4637 } else {
4638 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4639 // in the future without user intervention.
4640 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004641
Stuart Scotte3e314d2015-04-20 14:07:45 -07004642 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4643 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004644 }
4645 }
4646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004647}