blob: 3c1357742f482ee3b8c37662c4452f5b0c1ceeec [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;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070031import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Amith Yamasani15e472352015-04-24 19:06:07 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070033import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070034
Wenchao Tongf5ea3402015-03-04 13:26:38 -080035import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080036import android.app.BroadcastOptions;
Wink Savilleab9321d2013-06-29 21:10:57 -070037import android.app.Notification;
38import android.app.NotificationManager;
39import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070040import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.ContentResolver;
42import android.content.Context;
43import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070044import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070046import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090047import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070048import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090050import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070052import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070053import android.net.INetworkPolicyListener;
54import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070055import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080056import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070057import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070058import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070059import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070060import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070061import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070063import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070064import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070065import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070066import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070067import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070068import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070069import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040070import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070071import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040072import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040073import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080075import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070076import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040077import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070079import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070080import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070081import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.Looper;
83import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070084import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070085import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070086import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070087import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070088import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080089import android.os.ResultReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070091import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040092import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070094import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070095import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070096import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070097import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070098import android.util.LocalLog;
99import android.util.LocalLog.ReadOnlyLocalLog;
100import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800101import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700102import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500103import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700104import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700105import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106
Wink Savilleab9321d2013-06-29 21:10:57 -0700107import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400108import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400109import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700110import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700111import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700112import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700113import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800114import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700115import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700116import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700117import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700118import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700119import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400120import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900121import com.android.server.connectivity.KeepaliveTracker;
Erik Kline379747a2015-06-05 17:47:34 +0900122import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900123import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700124import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400125import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400126import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700127import com.android.server.connectivity.PermissionMonitor;
Paul Jensen578a76e2016-01-14 14:54:39 -0500128import com.android.server.connectivity.ApfFilter;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800129import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700130import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700131import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700132import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700133import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700134import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700135
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700136import org.xmlpull.v1.XmlPullParser;
137import org.xmlpull.v1.XmlPullParserException;
138
139import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700141import java.io.FileNotFoundException;
142import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700143import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700145import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700146import java.net.InetAddress;
147import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700148import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700149import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700150import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700151import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700152import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700153import java.util.HashSet;
Lorenzo Colittic3f21f32015-07-06 23:50:27 +0900154import java.util.SortedSet;
155import java.util.TreeSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700156import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700157import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700158import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
160/**
161 * @hide
162 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800163public class ConnectivityService extends IConnectivityManager.Stub
164 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700165 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166
Joe Onorato12acbd72016-02-01 17:49:31 -0800167 private static final boolean DBG = false;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700168 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169
Jake Hamby786e71a2014-02-06 14:43:50 -0800170 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900171 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700172
Jeff Sharkey899223b2012-08-04 15:24:58 -0700173 // TODO: create better separation between radio types and network types
174
Robert Greenwalt42acef32009-08-12 16:08:25 -0700175 // how long to wait before switching back to a radio's default network
176 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
177 // system property that can override the above value
178 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
179 "android.telephony.apn-restore";
180
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900181 // How long to wait before putting up a "This network doesn't have an Internet connection,
182 // connect anyway?" dialog after the user selects a network that doesn't validate.
183 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
184
Jeremy Joslin79294842014-12-03 17:15:28 -0800185 // How long to delay to removal of a pending intent based request.
186 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
187 private final int mReleasePendingIntentDelayMs;
188
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800189 private Tethering mTethering;
190
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700191 private final PermissionMonitor mPermissionMonitor;
192
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700193 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700194
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700195 @GuardedBy("mVpns")
196 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700197
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700198 private boolean mLockdownEnabled;
199 private LockdownVpnTracker mLockdownTracker;
200
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700201 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
202 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700203 /** Currently active network rules by UID. */
204 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700205 /** Set of ifaces that are costly. */
206 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700207
Erik Klineda4bfa82015-04-30 12:58:40 +0900208 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700210 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700211 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800213 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
215 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700216 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700218 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800219 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700220 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700221
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700222 private String mCurrentTcpBufferSizes;
223
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700224 private static final int ENABLED = 1;
225 private static final int DISABLED = 0;
226
Paul Jensenb10e37f2014-11-25 12:33:08 -0500227 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400228 // Tear down networks that have no chance (e.g. even if validated) of becoming
229 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500230 // all networks have been rematched against all NetworkRequests.
231 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400232 // Don't reap networks. This should be passed when some networks have not yet been
233 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500234 DONT_REAP
235 };
236
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700237 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700238 * used internally to change our mobile data enabled flag
239 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700240 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700241
242 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700243 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700244 * from one net to another. Clear happens when we get a new
245 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
246 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700247 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700248 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700249
Robert Greenwalt434203a2010-10-11 16:00:27 -0700250 /**
251 * used internally to reload global proxy settings
252 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700253 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700254
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700255 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400256 * PAC manager has received new port.
257 */
258 private static final int EVENT_PROXY_HAS_CHANGED = 16;
259
Robert Greenwalte049c232014-04-11 15:53:27 -0700260 /**
261 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700262 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700263 */
264 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
265
Robert Greenwalt7b816022014-04-18 15:25:25 -0700266 /**
267 * used internally when registering NetworkAgents
268 * obj = Messenger
269 */
270 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
271
Robert Greenwalt9258c642014-03-26 16:47:06 -0700272 /**
273 * used to add a network request
274 * includes a NetworkRequestInfo
275 */
276 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
277
278 /**
279 * indicates a timeout period is over - check if we had a network yet or not
280 * and if not, call the timeout calback (but leave the request live until they
281 * cancel it.
282 * includes a NetworkRequestInfo
283 */
284 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
285
286 /**
287 * used to add a network listener - no request
288 * includes a NetworkRequestInfo
289 */
290 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
291
292 /**
293 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400294 * arg1 = UID of caller
295 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700296 */
297 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
298
Robert Greenwalta67be032014-05-16 15:49:14 -0700299 /**
300 * used internally when registering NetworkFactories
301 * obj = Messenger
302 */
303 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
304
Robert Greenwalt27711812014-06-25 16:45:57 -0700305 /**
306 * used internally to expire a wakelock when transitioning
307 * from one net to another. Expire happens when we fail to find
308 * a new network (typically after 1 minute) -
309 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
310 * a replacement network.
311 */
312 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
313
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700314 /**
315 * Used internally to indicate the system is ready.
316 */
317 private static final int EVENT_SYSTEM_READY = 25;
318
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800319 /**
320 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400321 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800322 */
323 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
324
325 /**
326 * used to remove a pending intent and its associated network request.
327 * arg1 = UID of caller
328 * obj = PendingIntent
329 */
330 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
331
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900332 /**
333 * used to specify whether a network should be used even if unvalidated.
334 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
335 * arg2 = whether to remember this choice in the future (1 or 0)
336 * obj = network
337 */
338 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
339
340 /**
341 * used to ask the user to confirm a connection to an unvalidated network.
342 * obj = network
343 */
344 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700345
Erik Klineda4bfa82015-04-30 12:58:40 +0900346 /**
347 * used internally to (re)configure mobile data always-on settings.
348 */
349 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
350
Paul Jensen694f2b82015-06-17 14:15:39 -0400351 /**
352 * used to add a network listener with a pending intent
353 * obj = NetworkRequestInfo
354 */
355 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
356
Paul Jensen578a76e2016-01-14 14:54:39 -0500357 /**
358 * used to push APF program to NetworkAgent
359 * replyTo = NetworkAgent message handler
360 * obj = byte[] of APF program
361 */
362 private static final int EVENT_PUSH_APF_PROGRAM_TO_NETWORK = 32;
363
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900364 /** Handler thread used for both of the handlers below. */
365 @VisibleForTesting
366 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700367 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700368 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700369 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700370 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700371
Mike Lockwood0f79b542009-08-14 14:18:49 -0400372 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800373 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400374
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700375 private PowerManager.WakeLock mNetTransitionWakeLock;
376 private String mNetTransitionWakeLockCausedBy = "";
377 private int mNetTransitionWakeLockSerialNumber;
378 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800379 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700380
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700381 private InetAddress mDefaultDns;
382
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700383 // used in DBG mode to track inet condition reports
384 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
385 private ArrayList mInetLog;
386
Robert Greenwalt434203a2010-10-11 16:00:27 -0700387 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400388 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700389 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700390 private boolean mDefaultProxyDisabled = false;
391
Robert Greenwalt434203a2010-10-11 16:00:27 -0700392 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400393 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700394
Jason Monk602b2322013-07-03 17:04:33 -0400395 private PacManager mPacManager = null;
396
Erik Klineda4bfa82015-04-30 12:58:40 +0900397 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700398
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400399 private UserManager mUserManager;
400
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700401 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700402 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700403
Robert Greenwalt50393202011-06-21 17:26:14 -0700404 // the set of network types that can only be enabled by system/sig apps
405 List mProtectedNetworks;
406
John Spurlockbf991a82013-06-24 14:20:23 -0400407 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700408
Wink Savilleab9321d2013-06-29 21:10:57 -0700409 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400410
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900411 private KeepaliveTracker mKeepaliveTracker;
412
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700413 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
414 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700415 private final static int MAX_NET_ID = 65535;
416 private int mNextNetId = MIN_NET_ID;
417
Robert Greenwalt34524f02014-05-18 16:22:10 -0700418 // sequence number of NetworkRequests
419 private int mNextNetworkRequestId = 1;
420
Erik Kline7523eb32015-07-09 18:24:03 +0900421 // NetworkRequest activity String log entries.
422 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
423 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
424
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700425 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
426 private static final int MAX_VALIDATION_LOGS = 10;
427 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
428 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
429
430 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
431 synchronized(mValidationLogs) {
432 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
433 mValidationLogs.removeLast();
434 }
435 mValidationLogs.addFirst(new Pair(network, log));
436 }
437 }
438
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700439 /**
440 * Implements support for the legacy "one network per network type" model.
441 *
442 * We used to have a static array of NetworkStateTrackers, one for each
443 * network type, but that doesn't work any more now that we can have,
444 * for example, more that one wifi network. This class stores all the
445 * NetworkAgentInfo objects that support a given type, but the legacy
446 * API will only see the first one.
447 *
448 * It serves two main purposes:
449 *
450 * 1. Provide information about "the network for a given type" (since this
451 * API only supports one).
452 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
453 * the first network for a given type changes, or if the default network
454 * changes.
455 */
456 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900457
Joe Onorato12acbd72016-02-01 17:49:31 -0800458 private static final boolean DBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900459 private static final boolean VDBG = false;
460 private static final String TAG = "CSLegacyTypeTracker";
461
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700462 /**
463 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
464 * Each list holds references to all NetworkAgentInfos that are used to
465 * satisfy requests for that network type.
466 *
467 * This array is built out at startup such that an unsupported network
468 * doesn't get an ArrayList instance, making this a tristate:
469 * unsupported, supported but not active and active.
470 *
471 * The actual lists are populated when we scan the network types that
472 * are supported on this device.
473 */
474 private ArrayList<NetworkAgentInfo> mTypeLists[];
475
476 public LegacyTypeTracker() {
477 mTypeLists = (ArrayList<NetworkAgentInfo>[])
478 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
479 }
480
481 public void addSupportedType(int type) {
482 if (mTypeLists[type] != null) {
483 throw new IllegalStateException(
484 "legacy list for type " + type + "already initialized");
485 }
486 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
487 }
488
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700489 public boolean isTypeSupported(int type) {
490 return isNetworkTypeValid(type) && mTypeLists[type] != null;
491 }
492
493 public NetworkAgentInfo getNetworkForType(int type) {
494 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
495 return mTypeLists[type].get(0);
496 } else {
497 return null;
498 }
499 }
500
Robert Greenwalt8d482522015-06-24 13:23:42 -0700501 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900502 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900503 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700504 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900505 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900506 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900507 }
508 }
509
510 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700511 public void add(int type, NetworkAgentInfo nai) {
512 if (!isTypeSupported(type)) {
513 return; // Invalid network type.
514 }
515 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
516
517 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
518 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700519 return;
520 }
521
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900522 list.add(nai);
523
524 // 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 +0900525 final boolean isDefaultNetwork = isDefaultNetwork(nai);
526 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700527 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
528 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700529 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700530 }
531
Lorenzo Colittia793a672014-07-31 23:20:17 +0900532 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900533 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900534 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
535 if (list == null || list.isEmpty()) {
536 return;
537 }
538
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900539 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900540
541 if (!list.remove(nai)) {
542 return;
543 }
544
Robert Greenwalt8d482522015-06-24 13:23:42 -0700545 final DetailedState state = DetailedState.DISCONNECTED;
546
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900547 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700548 maybeLogBroadcast(nai, state, type, wasDefault);
549 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900550 }
551
552 if (!list.isEmpty() && wasFirstNetwork) {
553 if (DBG) log("Other network available for type " + type +
554 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900555 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700556 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
557 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900558 }
559 }
560
561 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900562 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
563 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700564 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900565 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700566 }
567 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700568
Robert Greenwalt8d482522015-06-24 13:23:42 -0700569 // send out another legacy broadcast - currently only used for suspend/unsuspend
570 // toggle
571 public void update(NetworkAgentInfo nai) {
572 final boolean isDefault = isDefaultNetwork(nai);
573 final DetailedState state = nai.networkInfo.getDetailedState();
574 for (int type = 0; type < mTypeLists.length; type++) {
575 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700576 final boolean contains = (list != null && list.contains(nai));
Robert Greenwalt8d482522015-06-24 13:23:42 -0700577 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700578 if (isFirst || (contains && isDefault)) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700579 maybeLogBroadcast(nai, state, type, isDefault);
580 sendLegacyNetworkBroadcast(nai, state, type);
581 }
582 }
583 }
584
Lorenzo Colittia793a672014-07-31 23:20:17 +0900585 private String naiToString(NetworkAgentInfo nai) {
586 String name = (nai != null) ? nai.name() : "null";
587 String state = (nai.networkInfo != null) ?
588 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
589 "???/???";
590 return name + " " + state;
591 }
592
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700593 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900594 pw.println("mLegacyTypeTracker:");
595 pw.increaseIndent();
596 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700597 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900598 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700599 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900600 pw.println();
601 pw.println("Current state:");
602 pw.increaseIndent();
603 for (int type = 0; type < mTypeLists.length; type++) {
604 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
605 for (NetworkAgentInfo nai : mTypeLists[type]) {
606 pw.println(type + " " + naiToString(nai));
607 }
608 }
609 pw.decreaseIndent();
610 pw.decreaseIndent();
611 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700612 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900613
614 // This class needs its own log method because it has a different TAG.
615 private void log(String s) {
616 Slog.d(TAG, s);
617 }
618
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700619 }
620 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
621
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900622 @VisibleForTesting
623 protected HandlerThread createHandlerThread() {
624 return new HandlerThread("ConnectivityServiceThread");
625 }
626
Jeff Sharkey899223b2012-08-04 15:24:58 -0700627 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700628 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800629 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800630
Erik Klineda4bfa82015-04-30 12:58:40 +0900631 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900632 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
633 new Binder(), NetworkRequestInfo.REQUEST);
634 mNetworkRequests.put(mDefaultRequest, defaultNRI);
635 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900636
637 mDefaultMobileDataRequest = createInternetRequestForTransport(
638 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700639
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900640 mHandlerThread = createHandlerThread();
641 mHandlerThread.start();
642 mHandler = new InternalHandler(mHandlerThread.getLooper());
643 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700644
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800645 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800646 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
647 String id = Settings.Secure.getString(context.getContentResolver(),
648 Settings.Secure.ANDROID_ID);
649 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700650 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800651 SystemProperties.set("net.hostname", name);
652 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800653 }
654
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700655 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700656 String dns = Settings.Global.getString(context.getContentResolver(),
657 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700658 if (dns == null || dns.length() == 0) {
659 dns = context.getResources().getString(
660 com.android.internal.R.string.config_default_dns_server);
661 }
662 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800663 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
664 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800665 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700666 }
667
Jeremy Joslin79294842014-12-03 17:15:28 -0800668 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
669 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
670
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700671 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700672 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800673 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700674 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700675 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700676 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700677
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700678 try {
679 mPolicyManager.registerListener(mPolicyListener);
680 } catch (RemoteException e) {
681 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700682 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700683 }
684
685 final PowerManager powerManager = (PowerManager) context.getSystemService(
686 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700687 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
688 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
689 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800690 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700691
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700692 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700693
Wink Saville51f456f2013-04-23 14:26:51 -0700694 // TODO: What is the "correct" way to do determine if this is a wifi only device?
695 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
696 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700697 String[] naStrings = context.getResources().getStringArray(
698 com.android.internal.R.array.networkAttributes);
699 for (String naString : naStrings) {
700 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700701 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700702 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700703 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800704 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700705 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700706 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700707 }
Wink Saville51f456f2013-04-23 14:26:51 -0700708 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
709 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
710 n.type);
711 continue;
712 }
Wink Saville975c8482011-04-07 14:23:45 -0700713 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800714 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700715 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700716 continue;
717 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700718 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700719
Wink Saville975c8482011-04-07 14:23:45 -0700720 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700721 mNetworksDefined++;
722 } catch(Exception e) {
723 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700724 }
725 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700726
727 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
728 if (mNetConfigs[TYPE_VPN] == null) {
729 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
730 // don't need to add TYPE_VPN to mNetConfigs.
731 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
732 mNetworksDefined++; // used only in the log() statement below.
733 }
734
Wink Saville5e56bc52013-07-29 15:00:57 -0700735 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700736
Robert Greenwalt50393202011-06-21 17:26:14 -0700737 mProtectedNetworks = new ArrayList<Integer>();
738 int[] protectedNetworks = context.getResources().getIntArray(
739 com.android.internal.R.array.config_protectedNetworks);
740 for (int p : protectedNetworks) {
741 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
742 mProtectedNetworks.add(p);
743 } else {
744 if (DBG) loge("Ignoring protectedNetwork " + p);
745 }
746 }
747
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700748 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
749 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700750
Jeremy Kleinfa8712b2016-01-26 11:10:55 -0800751 mTethering = new Tethering(mContext, mNetd, statsService);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800752
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700753 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
754
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700755 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700756 IntentFilter intentFilter = new IntentFilter();
757 intentFilter.addAction(Intent.ACTION_USER_STARTING);
758 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700759 intentFilter.addAction(Intent.ACTION_USER_ADDED);
760 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000761 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700762 mContext.registerReceiverAsUser(
763 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900764
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700765 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700766 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700767 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700768 } catch (RemoteException e) {
769 loge("Error registering observer :" + e);
770 }
771
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700772 if (DBG) {
773 mInetLog = new ArrayList();
774 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700775
Erik Klineda4bfa82015-04-30 12:58:40 +0900776 mSettingsObserver = new SettingsObserver(mContext, mHandler);
777 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800778
John Spurlockbf991a82013-06-24 14:20:23 -0400779 mDataConnectionStats = new DataConnectionStats(mContext);
780 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400781
Jason Monkdecd2952013-10-10 14:02:51 -0400782 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700783
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400784 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900785
786 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700788
Erik Klineda4bfa82015-04-30 12:58:40 +0900789 private NetworkRequest createInternetRequestForTransport(int transportType) {
790 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900791 netCap.addCapability(NET_CAPABILITY_INTERNET);
792 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900793 if (transportType > -1) {
794 netCap.addTransportType(transportType);
795 }
796 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
797 }
798
799 private void handleMobileDataAlwaysOn() {
800 final boolean enable = (Settings.Global.getInt(
801 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
802 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
803 if (enable == isEnabled) {
804 return; // Nothing to do.
805 }
806
807 if (enable) {
808 handleRegisterNetworkRequest(new NetworkRequestInfo(
809 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
810 } else {
811 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
812 }
813 }
814
815 private void registerSettingsCallbacks() {
816 // Watch for global HTTP proxy changes.
817 mSettingsObserver.observe(
818 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
819 EVENT_APPLY_GLOBAL_HTTP_PROXY);
820
821 // Watch for whether or not to keep mobile data always on.
822 mSettingsObserver.observe(
823 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
824 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
825 }
826
Robert Greenwalt34524f02014-05-18 16:22:10 -0700827 private synchronized int nextNetworkRequestId() {
828 return mNextNetworkRequestId++;
829 }
830
Paul Jensen67b0b072015-06-10 11:22:17 -0400831 @VisibleForTesting
832 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400833 synchronized (mNetworkForNetId) {
834 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
835 int netId = mNextNetId;
836 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
837 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500838 if (!mNetIdInUse.get(netId)) {
839 mNetIdInUse.put(netId, true);
840 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400841 }
842 }
843 }
844 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700845 }
846
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800847 private NetworkState getFilteredNetworkState(int networkType, int uid) {
848 NetworkInfo info = null;
849 LinkProperties lp = null;
850 NetworkCapabilities nc = null;
851 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800852 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800853
854 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
855 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
856 if (nai != null) {
857 synchronized (nai) {
858 info = new NetworkInfo(nai.networkInfo);
859 lp = new LinkProperties(nai.linkProperties);
860 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400861 // Network objects are outwardly immutable so there is no point to duplicating.
862 // Duplicating also precludes sharing socket factories and connection pools.
863 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800864 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800865 }
866 info.setType(networkType);
867 } else {
868 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
869 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
870 info.setIsAvailable(true);
871 lp = new LinkProperties();
872 nc = new NetworkCapabilities();
873 network = null;
874 }
875 info = getFilteredNetworkInfo(info, lp, uid);
876 }
877
Jeff Sharkey32566012014-12-02 18:30:14 -0800878 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400879 }
880
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800881 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
882 if (network == null) {
883 return null;
884 }
885 synchronized (mNetworkForNetId) {
886 return mNetworkForNetId.get(network.netId);
887 }
888 };
889
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900890 private Network[] getVpnUnderlyingNetworks(int uid) {
891 if (!mLockdownEnabled) {
892 int user = UserHandle.getUserId(uid);
893 synchronized (mVpns) {
894 Vpn vpn = mVpns.get(user);
895 if (vpn != null && vpn.appliesToUid(uid)) {
896 return vpn.getUnderlyingNetworks();
897 }
898 }
899 }
900 return null;
901 }
902
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800903 private NetworkState getUnfilteredActiveNetworkState(int uid) {
904 NetworkInfo info = null;
905 LinkProperties lp = null;
906 NetworkCapabilities nc = null;
907 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800908 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800909
Paul Jensen85cf78e2015-06-25 13:25:07 -0400910 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800911
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900912 final Network[] networks = getVpnUnderlyingNetworks(uid);
913 if (networks != null) {
914 // getUnderlyingNetworks() returns:
915 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
916 // empty array => the VPN explicitly said "no default network".
917 // non-empty array => the VPN specified one or more default networks; we use the
918 // first one.
919 if (networks.length > 0) {
920 nai = getNetworkAgentInfoForNetwork(networks[0]);
921 } else {
922 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800923 }
924 }
925
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800926 if (nai != null) {
927 synchronized (nai) {
928 info = new NetworkInfo(nai.networkInfo);
929 lp = new LinkProperties(nai.linkProperties);
930 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400931 // Network objects are outwardly immutable so there is no point to duplicating.
932 // Duplicating also precludes sharing socket factories and connection pools.
933 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800934 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800935 }
936 }
937
Jeff Sharkey32566012014-12-02 18:30:14 -0800938 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400939 }
940
941 /**
942 * Check if UID should be blocked from using the network with the given LinkProperties.
943 */
944 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700945 final boolean networkCostly;
946 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700947
Robert Greenwalt12e67352014-05-13 21:41:06 -0700948 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700949 synchronized (mRulesLock) {
950 networkCostly = mMeteredIfaces.contains(iface);
951 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700952 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700953
Jeff Sharkeydc988062015-09-14 10:09:47 -0700954 if (uidRules == RULE_REJECT_ALL) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700955 return true;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700956 } else if ((uidRules == RULE_REJECT_METERED) && networkCostly) {
957 return true;
958 } else {
959 return false;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700960 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700961 }
962
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900963 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
964 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) return;
965 boolean removed = false;
966 boolean added = false;
967 synchronized (mBlockedAppUids) {
968 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
969 added = true;
970 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
971 removed = true;
972 }
973 }
974 if (added) log("Returning blocked NetworkInfo to uid=" + uid);
975 else if (removed) log("Returning unblocked NetworkInfo to uid=" + uid);
976 }
977
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700978 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700979 * Return a filtered {@link NetworkInfo}, potentially marked
980 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800981 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700982 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800983 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
984 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400985 // network is blocked; clone and override state
986 info = new NetworkInfo(info);
987 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700988 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800989 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700990 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900991 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700992 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700993 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700994 }
995
996 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 * Return NetworkInfo for the active (i.e., connected) network interface.
998 * It is assumed that at most one network is active at a time. If more
999 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001000 * @return the info for the active network, or {@code null} if none is
1001 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001003 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001005 enforceAccessPermission();
1006 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001007 NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001008 NetworkInfo ni = getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1009 maybeLogBlockedNetworkInfo(ni, uid);
1010 return ni;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 }
1012
Paul Jensen31a94f42015-02-13 14:18:39 -05001013 @Override
1014 public Network getActiveNetwork() {
1015 enforceAccessPermission();
1016 final int uid = Binder.getCallingUid();
1017 final int user = UserHandle.getUserId(uid);
1018 int vpnNetId = NETID_UNSET;
1019 synchronized (mVpns) {
1020 final Vpn vpn = mVpns.get(user);
1021 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1022 }
1023 NetworkAgentInfo nai;
1024 if (vpnNetId != NETID_UNSET) {
1025 synchronized (mNetworkForNetId) {
1026 nai = mNetworkForNetId.get(vpnNetId);
1027 }
1028 if (nai != null) return nai.network;
1029 }
1030 nai = getDefaultNetwork();
1031 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
1032 return nai != null ? nai.network : null;
1033 }
1034
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001035 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1036 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001037 final int uid = Binder.getCallingUid();
1038 NetworkState state = getUnfilteredActiveNetworkState(uid);
1039 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001040 }
1041
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001042 @Override
1043 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1044 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001045 NetworkState state = getUnfilteredActiveNetworkState(uid);
1046 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001047 }
1048
1049 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 public NetworkInfo getNetworkInfo(int networkType) {
1051 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001052 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001053 if (getVpnUnderlyingNetworks(uid) != null) {
1054 // A VPN is active, so we may need to return one of its underlying networks. This
1055 // information is not available in LegacyTypeTracker, so we have to get it from
1056 // getUnfilteredActiveNetworkState.
1057 NetworkState state = getUnfilteredActiveNetworkState(uid);
1058 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1059 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1060 }
1061 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001062 NetworkState state = getFilteredNetworkState(networkType, uid);
1063 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 }
1065
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001066 @Override
1067 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1068 enforceAccessPermission();
1069 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001070 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001071 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1072 if (nai != null) {
1073 synchronized (nai) {
1074 info = new NetworkInfo(nai.networkInfo);
1075 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001076 }
1077 }
1078 return info;
1079 }
1080
1081 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 public NetworkInfo[] getAllNetworkInfo() {
1083 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001084 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001085 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1086 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001087 NetworkInfo info = getNetworkInfo(networkType);
1088 if (info != null) {
1089 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001092 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 }
1094
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001095 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001096 public Network getNetworkForType(int networkType) {
1097 enforceAccessPermission();
1098 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001099 NetworkState state = getFilteredNetworkState(networkType, uid);
1100 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1101 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001102 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001103 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001104 }
1105
1106 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001107 public Network[] getAllNetworks() {
1108 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001109 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001110 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001111 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001112 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001113 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001114 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001115 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001116 }
1117
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001118 @Override
1119 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1120 // The basic principle is: if an app's traffic could possibly go over a
1121 // network, without the app doing anything multinetwork-specific,
1122 // (hence, by "default"), then include that network's capabilities in
1123 // the array.
1124 //
1125 // In the normal case, app traffic only goes over the system's default
1126 // network connection, so that's the only network returned.
1127 //
1128 // With a VPN in force, some app traffic may go into the VPN, and thus
1129 // over whatever underlying networks the VPN specifies, while other app
1130 // traffic may go over the system default network (e.g.: a split-tunnel
1131 // VPN, or an app disallowed by the VPN), so the set of networks
1132 // returned includes the VPN's underlying networks and the system
1133 // default.
1134 enforceAccessPermission();
1135
1136 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1137
1138 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001139 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001140 if (nc != null) {
1141 result.put(nai.network, nc);
1142 }
1143
1144 if (!mLockdownEnabled) {
1145 synchronized (mVpns) {
1146 Vpn vpn = mVpns.get(userId);
1147 if (vpn != null) {
1148 Network[] networks = vpn.getUnderlyingNetworks();
1149 if (networks != null) {
1150 for (Network network : networks) {
1151 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001152 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001153 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001154 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001155 }
1156 }
1157 }
1158 }
1159 }
1160 }
1161
1162 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1163 out = result.values().toArray(out);
1164 return out;
1165 }
1166
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001167 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001168 public boolean isNetworkSupported(int networkType) {
1169 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001170 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001171 }
1172
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001173 /**
1174 * Return LinkProperties for the active (i.e., connected) default
1175 * network interface. It is assumed that at most one default network
1176 * is active at a time. If more than one is active, it is indeterminate
1177 * which will be returned.
1178 * @return the ip properties for the active network, or {@code null} if
1179 * none is active
1180 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001181 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001182 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001183 enforceAccessPermission();
1184 final int uid = Binder.getCallingUid();
1185 NetworkState state = getUnfilteredActiveNetworkState(uid);
1186 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001187 }
1188
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001189 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001190 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001191 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001192 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1193 if (nai != null) {
1194 synchronized (nai) {
1195 return new LinkProperties(nai.linkProperties);
1196 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001197 }
1198 return null;
1199 }
1200
Robert Greenwalt12e67352014-05-13 21:41:06 -07001201 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001202 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001203 public LinkProperties getLinkProperties(Network network) {
1204 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001205 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001206 if (nai != null) {
1207 synchronized (nai) {
1208 return new LinkProperties(nai.linkProperties);
1209 }
1210 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001211 return null;
1212 }
1213
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001214 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001215 if (nai != null) {
1216 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001217 if (nai.networkCapabilities != null) {
1218 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001219 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001220 }
1221 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001222 return null;
1223 }
1224
1225 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001226 public NetworkCapabilities getNetworkCapabilities(Network network) {
1227 enforceAccessPermission();
1228 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1229 }
1230
1231 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001232 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001233 // Require internal since we're handing out IMSI details
1234 enforceConnectivityInternalPermission();
1235
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001236 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001237 for (Network network : getAllNetworks()) {
1238 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1239 if (nai != null) {
1240 synchronized (nai) {
1241 final String subscriberId = (nai.networkMisc != null)
1242 ? nai.networkMisc.subscriberId : null;
1243 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1244 nai.networkCapabilities, network, subscriberId, null));
1245 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001246 }
1247 }
1248 return result.toArray(new NetworkState[result.size()]);
1249 }
1250
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001251 @Override
1252 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1253 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001254 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001255 final long token = Binder.clearCallingIdentity();
1256 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001257 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1258 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001259 try {
1260 return mPolicyManager.getNetworkQuotaInfo(state);
1261 } catch (RemoteException e) {
1262 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001263 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001264 return null;
1265 } finally {
1266 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001267 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001268 }
1269
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001270 @Override
1271 public boolean isActiveNetworkMetered() {
1272 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001273 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001274 final long token = Binder.clearCallingIdentity();
1275 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001276 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001277 } finally {
1278 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001279 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001280 }
1281
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001282 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1283 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1284 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001285 try {
1286 return mPolicyManager.isNetworkMetered(state);
1287 } catch (RemoteException e) {
1288 }
1289 }
1290 return false;
1291 }
1292
Jeff Sharkey216c1812012-08-05 14:29:23 -07001293 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1294 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001295 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001296 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001297 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001298 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001299 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001300
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001301 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 * Ensure that a network route exists to deliver traffic to the specified
1303 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001304 * @param networkType the type of the network over which traffic to the
1305 * specified host is to be routed
1306 * @param hostAddress the IP address of the host to which the route is
1307 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 * @return {@code true} on success, {@code false} on failure
1309 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001310 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001312 if (mProtectedNetworks.contains(networkType)) {
1313 enforceConnectivityInternalPermission();
1314 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001315
Chad Brubakerc0234532014-02-14 13:24:29 -08001316 InetAddress addr;
1317 try {
1318 addr = InetAddress.getByAddress(hostAddress);
1319 } catch (UnknownHostException e) {
1320 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1321 return false;
1322 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001325 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 return false;
1327 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001328
1329 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1330 if (nai == null) {
1331 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1332 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1333 } else {
1334 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1335 }
1336 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001337 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001338
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001339 DetailedState netState;
1340 synchronized (nai) {
1341 netState = nai.networkInfo.getDetailedState();
1342 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001343
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001344 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001345 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001346 log("requestRouteToHostAddress on down network "
1347 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001348 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001349 }
1350 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001352
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001353 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001354 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001355 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001356 LinkProperties lp;
1357 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001358 synchronized (nai) {
1359 lp = nai.linkProperties;
1360 netId = nai.network.netId;
1361 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001362 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001363 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1364 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001365 } finally {
1366 Binder.restoreCallingIdentity(token);
1367 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001368 }
1369
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001370 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001371 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001372 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001373 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001374 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001375 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001376 if (bestRoute.getGateway().equals(addr)) {
1377 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001378 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001379 } else {
1380 // if we will connect to this through another route, add a direct route
1381 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001382 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001383 }
1384 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001385 if (DBG) log("Adding legacy route " + bestRoute +
1386 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001387 try {
1388 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1389 } catch (Exception e) {
1390 // never crash - catch them all
1391 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001392 return false;
1393 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001394 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 }
1396
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001397 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1398 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001399 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001400 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001401 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001402 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001403 }
1404
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001405 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001406 // skip update when we've already applied rules
1407 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1408 if (oldRules == uidRules) return;
1409
1410 mUidRules.put(uid, uidRules);
1411 }
1412
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001413 // TODO: notify UID when it has requested targeted updates
1414 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001415
1416 @Override
1417 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001418 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001419 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001420 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001421 }
1422
1423 synchronized (mRulesLock) {
1424 mMeteredIfaces.clear();
1425 for (String iface : meteredIfaces) {
1426 mMeteredIfaces.add(iface);
1427 }
1428 }
1429 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001430
1431 @Override
1432 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1433 // caller is NPMS, since we only register with them
1434 if (LOGD_RULES) {
1435 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1436 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001437 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001438 };
1439
Robin Lee3b3dd942015-05-12 18:14:58 +01001440 /**
1441 * Require that the caller is either in the same user or has appropriate permission to interact
1442 * across users.
1443 *
1444 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1445 */
1446 private void enforceCrossUserPermission(int userId) {
1447 if (userId == UserHandle.getCallingUserId()) {
1448 // Not a cross-user call.
1449 return;
1450 }
1451 mContext.enforceCallingOrSelfPermission(
1452 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1453 "ConnectivityService");
1454 }
1455
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001456 private void enforceInternetPermission() {
1457 mContext.enforceCallingOrSelfPermission(
1458 android.Manifest.permission.INTERNET,
1459 "ConnectivityService");
1460 }
1461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001463 mContext.enforceCallingOrSelfPermission(
1464 android.Manifest.permission.ACCESS_NETWORK_STATE,
1465 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 }
1467
1468 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001469 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 }
1471
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001472 private void enforceTetherAccessPermission() {
1473 mContext.enforceCallingOrSelfPermission(
1474 android.Manifest.permission.ACCESS_NETWORK_STATE,
1475 "ConnectivityService");
1476 }
1477
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001478 private void enforceConnectivityInternalPermission() {
1479 mContext.enforceCallingOrSelfPermission(
1480 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1481 "ConnectivityService");
1482 }
1483
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001484 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001485 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001486 }
1487
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001488 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001489 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001490 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001491 }
1492
1493 private void sendInetConditionBroadcast(NetworkInfo info) {
1494 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1495 }
1496
Wink Saville628b0852011-08-04 15:01:58 -07001497 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001498 if (mLockdownTracker != null) {
1499 info = mLockdownTracker.augmentNetworkInfo(info);
1500 }
1501
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001502 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001503 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001504 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 if (info.isFailover()) {
1506 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1507 info.setFailover(false);
1508 }
1509 if (info.getReason() != null) {
1510 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1511 }
1512 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001513 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1514 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001516 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001517 return intent;
1518 }
1519
1520 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1521 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1522 }
1523
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001524 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001525 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1526 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1527 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001528 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001529 final long ident = Binder.clearCallingIdentity();
1530 try {
1531 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1532 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1533 } finally {
1534 Binder.restoreCallingIdentity(ident);
1535 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001536 }
1537
Mike Lockwood0f79b542009-08-14 14:18:49 -04001538 private void sendStickyBroadcast(Intent intent) {
1539 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001540 if (!mSystemReady) {
1541 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001542 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001543 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001544 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001545 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001546 }
1547
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001548 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001549 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001550 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001551 final NetworkInfo ni = intent.getParcelableExtra(
1552 ConnectivityManager.EXTRA_NETWORK_INFO);
1553 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1554 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1555 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001556 } else {
1557 BroadcastOptions opts = BroadcastOptions.makeBasic();
1558 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1559 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001560 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001561 final IBatteryStats bs = BatteryStatsService.getService();
1562 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001563 bs.noteConnectivityChanged(intent.getIntExtra(
1564 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1565 ni != null ? ni.getState().toString() : "?");
1566 } catch (RemoteException e) {
1567 }
1568 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001569 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001570 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001571 } finally {
1572 Binder.restoreCallingIdentity(ident);
1573 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001574 }
1575 }
1576
1577 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001578 loadGlobalProxy();
1579
Mike Lockwood0f79b542009-08-14 14:18:49 -04001580 synchronized(this) {
1581 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001582 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001583 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001584 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001585 }
1586 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001587 // load the global proxy at startup
1588 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001589
Robin Lee244ce8e2016-01-05 18:03:46 +00001590 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1591 // for user to unlock device too.
1592 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001593
Erik Klineda4bfa82015-04-30 12:58:40 +09001594 // Configure whether mobile data is always on.
1595 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1596
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001597 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001598
1599 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 }
1601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001603 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001604 *
1605 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001606 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001607 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001608 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1609 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001610
1611 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001612 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001613
Robert Greenwalt7b816022014-04-18 15:25:25 -07001614 if (networkAgent.networkCapabilities.hasTransport(
1615 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001616 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1617 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001618 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001619 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001620 } else if (networkAgent.networkCapabilities.hasTransport(
1621 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001622 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1623 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001624 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001625 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001626 } else {
1627 // do not track any other networks
1628 timeout = 0;
1629 }
1630
Robert Greenwalt7b816022014-04-18 15:25:25 -07001631 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001632 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001633 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001634 } catch (Exception e) {
1635 // You shall not crash!
1636 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001637 }
1638 }
1639 }
1640
1641 /**
1642 * Remove data activity tracking when network disconnects.
1643 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001644 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1645 final String iface = networkAgent.linkProperties.getInterfaceName();
1646 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001647
Robert Greenwalt7b816022014-04-18 15:25:25 -07001648 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1649 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001650 try {
1651 // the call fails silently if no idletimer setup for this interface
1652 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001653 } catch (Exception e) {
1654 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001655 }
1656 }
1657 }
1658
1659 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001660 * Reads the network specific MTU size from reources.
1661 * and set it on it's iface.
1662 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001663 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1664 final String iface = newLp.getInterfaceName();
1665 final int mtu = newLp.getMtu();
1666 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1667 if (VDBG) log("identical MTU - not setting");
1668 return;
1669 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001670
Robert Greenwalt43074032014-08-15 17:53:05 -07001671 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001672 loge("Unexpected mtu value: " + mtu + ", " + iface);
1673 return;
1674 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001675
w1997615afd812014-08-05 15:18:11 -07001676 // Cannot set MTU without interface name
1677 if (TextUtils.isEmpty(iface)) {
1678 loge("Setting MTU size with null iface.");
1679 return;
1680 }
1681
Robert Greenwalt7b816022014-04-18 15:25:25 -07001682 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001683 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001684 mNetd.setMtu(iface, mtu);
1685 } catch (Exception e) {
1686 Slog.e(TAG, "exception in setMtu()" + e);
1687 }
1688 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001689
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001690 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001691 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1692
1693 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001694 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001695 protected int getDefaultTcpRwnd() {
1696 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1697 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001698
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001699 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1700 if (isDefaultNetwork(nai) == false) {
1701 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001702 }
1703
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001704 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1705 String[] values = null;
1706 if (tcpBufferSizes != null) {
1707 values = tcpBufferSizes.split(",");
1708 }
1709
1710 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001711 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001712 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1713 values = tcpBufferSizes.split(",");
1714 }
1715
1716 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1717
1718 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001719 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001720
1721 final String prefix = "/sys/kernel/ipv4/tcp_";
1722 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1723 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1724 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1725 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1726 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1727 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1728 mCurrentTcpBufferSizes = tcpBufferSizes;
1729 } catch (IOException e) {
1730 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001731 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001732
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001733 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001734 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001735 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1736 if (rwndValue != 0) {
1737 SystemProperties.set(sysctlKey, rwndValue.toString());
1738 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001739 }
1740
Mattias Falk8b47b362011-08-23 14:15:13 +02001741 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001742 /*
1743 * Tell the VMs to toss their DNS caches
1744 */
1745 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1746 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001747 /*
1748 * Connectivity events can happen before boot has completed ...
1749 */
1750 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001751 final long ident = Binder.clearCallingIdentity();
1752 try {
1753 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1754 } finally {
1755 Binder.restoreCallingIdentity(ident);
1756 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001757 }
1758
Robert Greenwalt562cc542014-05-15 18:07:26 -07001759 @Override
1760 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001761 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1762 NETWORK_RESTORE_DELAY_PROP_NAME);
1763 if(restoreDefaultNetworkDelayStr != null &&
1764 restoreDefaultNetworkDelayStr.length() != 0) {
1765 try {
1766 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1767 } catch (NumberFormatException e) {
1768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001770 // if the system property isn't set, use the value for the apn type
1771 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1772
1773 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1774 (mNetConfigs[networkType] != null)) {
1775 ret = mNetConfigs[networkType].restoreTime;
1776 }
1777 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 }
1779
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001780 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001781 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001782 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001783 }
1784 return false;
1785 }
1786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001788 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1789 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001790 if (mContext.checkCallingOrSelfPermission(
1791 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001793 pw.println("Permission Denial: can't dump ConnectivityService " +
1794 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1795 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 return;
1797 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001798
Erik Kline379747a2015-06-05 17:47:34 +09001799 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001800 if (argsContain(args, "--diag")) {
Erik Kline379747a2015-06-05 17:47:34 +09001801 final long DIAG_TIME_MS = 5000;
1802 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1803 // Start gathering diagnostic information.
1804 netDiags.add(new NetworkDiagnostics(
1805 nai.network,
Lorenzo Colitti87cfc702015-07-27 16:35:33 +09001806 new LinkProperties(nai.linkProperties), // Must be a copy.
Erik Kline379747a2015-06-05 17:47:34 +09001807 DIAG_TIME_MS));
1808 }
1809
1810 for (NetworkDiagnostics netDiag : netDiags) {
1811 pw.println();
1812 netDiag.waitForMeasurements();
1813 netDiag.dump(pw);
1814 }
1815
1816 return;
1817 }
1818
Lorenzo Colittie3805462015-06-03 11:18:24 +09001819 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001820 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001821 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001822 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001823 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001824 pw.println();
1825
Paul Jensen85cf78e2015-06-25 13:25:07 -04001826 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001827 pw.print("Active default network: ");
1828 if (defaultNai == null) {
1829 pw.println("none");
1830 } else {
1831 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001833 pw.println();
1834
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001835 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001836 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001837 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1838 pw.println(nai.toString());
1839 pw.increaseIndent();
1840 pw.println("Requests:");
1841 pw.increaseIndent();
1842 for (int i = 0; i < nai.networkRequests.size(); i++) {
1843 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001844 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001845 pw.decreaseIndent();
1846 pw.println("Lingered:");
1847 pw.increaseIndent();
1848 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1849 pw.decreaseIndent();
1850 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001851 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001852 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001853 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001854
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001855 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001856 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001857 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1858 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001859 }
1860 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001861 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001862
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001863 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001864
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001865 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001866 pw.print("mNetTransitionWakeLock: currently " +
1867 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1868 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1869 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1870 } else {
1871 pw.println(", last requested never");
1872 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001873 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001874
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001875 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001876 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001877
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001878 pw.println();
1879 mKeepaliveTracker.dump(pw);
1880
Lorenzo Colittie3805462015-06-03 11:18:24 +09001881 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001882 pw.println();
1883 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001884 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001885 for(int i = 0; i < mInetLog.size(); i++) {
1886 pw.println(mInetLog.get(i));
1887 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001888 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001889 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001890
1891 if (argsContain(args, "--short") == false) {
1892 pw.println();
1893 synchronized (mValidationLogs) {
1894 pw.println("mValidationLogs (most recent first):");
1895 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1896 pw.println(p.first);
1897 pw.increaseIndent();
1898 p.second.dump(fd, pw, args);
1899 pw.decreaseIndent();
1900 }
1901 }
Erik Kline7523eb32015-07-09 18:24:03 +09001902
1903 pw.println();
1904 pw.println("mNetworkRequestInfoLogs (most recent first):");
1905 pw.increaseIndent();
1906 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1907 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 }
1910
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001911 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001912 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001913 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001914 if (officialNai != null && officialNai.equals(nai)) return true;
1915 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001916 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001917 " - " + nai);
1918 }
1919 return false;
1920 }
1921
Paul Jensenc8b9a742014-09-30 15:37:41 -04001922 private boolean isRequest(NetworkRequest request) {
1923 return mNetworkRequests.get(request).isRequest;
1924 }
1925
Robert Greenwalt42acef32009-08-12 16:08:25 -07001926 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001927 private class NetworkStateTrackerHandler extends Handler {
1928 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001929 super(looper);
1930 }
1931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 @Override
1933 public void handleMessage(Message msg) {
1934 NetworkInfo info;
1935 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001936 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001937 handleAsyncChannelHalfConnect(msg);
1938 break;
1939 }
1940 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1941 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1942 if (nai != null) nai.asyncChannel.disconnect();
1943 break;
1944 }
1945 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1946 handleAsyncChannelDisconnected(msg);
1947 break;
1948 }
1949 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1950 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1951 if (nai == null) {
1952 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1953 } else {
Paul Jensen1c7ba022015-06-16 14:27:36 -04001954 final NetworkCapabilities networkCapabilities =
1955 (NetworkCapabilities)msg.obj;
1956 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1957 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001958 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Paul Jensen1c7ba022015-06-16 14:27:36 -04001959 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09001960 if (nai.created && !nai.networkCapabilities.equalImmutableCapabilities(
1961 networkCapabilities)) {
1962 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
1963 + nai.networkCapabilities + " -> " + networkCapabilities);
1964 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04001965 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001966 }
1967 break;
1968 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001969 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1970 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1971 if (nai == null) {
1972 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1973 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001974 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001975 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001976 "; created=" + nai.created);
1977 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001978 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001979 synchronized (nai) {
1980 nai.linkProperties = (LinkProperties)msg.obj;
1981 }
Paul Jenseneec75412014-08-04 12:21:19 -04001982 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001983 }
1984 break;
1985 }
1986 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1987 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1988 if (nai == null) {
1989 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1990 break;
1991 }
1992 info = (NetworkInfo) msg.obj;
1993 updateNetworkInfo(nai, info);
1994 break;
1995 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001996 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1997 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1998 if (nai == null) {
1999 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
2000 break;
2001 }
2002 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002003 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002004 break;
2005 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002006 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
2007 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2008 if (nai == null) {
2009 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
2010 break;
2011 }
2012 try {
2013 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002014 } catch (Exception e) {
2015 // Never crash!
2016 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002017 }
2018 break;
2019 }
2020 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
2021 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2022 if (nai == null) {
2023 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
2024 break;
2025 }
2026 try {
2027 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002028 } catch (Exception e) {
2029 // Never crash!
2030 loge("Exception in removeVpnUidRanges: " + e);
2031 }
2032 break;
2033 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002034 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
2035 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2036 if (nai == null) {
2037 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
2038 break;
2039 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002040 if (nai.created && !nai.networkMisc.explicitlySelected) {
2041 loge("ERROR: created network explicitly selected.");
2042 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002043 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002044 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002045 break;
2046 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002047 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
2048 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2049 if (nai == null) {
2050 loge("EVENT_PACKET_KEEPALIVE from unknown NetworkAgent");
2051 break;
2052 }
2053 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2054 break;
2055 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04002056 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002057 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002058 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
2059 final boolean valid =
2060 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002061 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
2062 if (valid != nai.lastValidated) {
2063 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002064 nai.lastValidated = valid;
2065 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002066 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002067 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2068 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002069 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002070 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002071 // Let the NetworkAgent know the state of its network
2072 nai.asyncChannel.sendMessage(
2073 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2074 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2075 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002076 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002077 break;
2078 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002079 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002080 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002081 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2082 handleLingerComplete(nai);
2083 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002084 break;
2085 }
Paul Jensen869868be2014-05-15 10:33:05 -04002086 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002087 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002088 final boolean visible = (msg.arg1 != 0);
2089 final NetworkAgentInfo nai;
2090 synchronized (mNetworkForNetId) {
2091 nai = mNetworkForNetId.get(netId);
2092 }
2093 // If captive portal status has changed, update capabilities.
2094 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2095 nai.lastCaptivePortalDetected = visible;
2096 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002097 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002098 }
2099 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002100 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002101 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002102 if (nai == null) {
2103 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2104 break;
2105 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002106 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002107 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2108 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002109 }
Paul Jensen869868be2014-05-15 10:33:05 -04002110 break;
2111 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002112 }
2113 }
2114 }
2115
Paul Jensen85cf78e2015-06-25 13:25:07 -04002116 private void linger(NetworkAgentInfo nai) {
2117 nai.lingering = true;
2118 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2119 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2120 }
2121
Paul Jensen0cc17322014-11-25 15:26:53 -05002122 // Cancel any lingering so the linger timeout doesn't teardown a network.
2123 // This should be called when a network begins satisfying a NetworkRequest.
2124 // Note: depending on what state the NetworkMonitor is in (e.g.,
2125 // if it's awaiting captive portal login, or if validation failed), this
2126 // may trigger a re-evaluation of the network.
2127 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002128 nai.networkLingered.clear();
2129 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002130 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002131 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002132 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2133 }
2134
Robert Greenwalt7b816022014-04-18 15:25:25 -07002135 private void handleAsyncChannelHalfConnect(Message msg) {
2136 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002137 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002138 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2139 if (VDBG) log("NetworkFactory connected");
2140 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002141 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002142 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002143 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002144 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002145 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002146 }
2147 } else {
2148 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002149 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002150 }
2151 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2152 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2153 if (VDBG) log("NetworkAgent connected");
2154 // A network agent has requested a connection. Establish the connection.
2155 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2156 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2157 } else {
2158 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002159 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002160 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002161 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002162 synchronized (mNetworkForNetId) {
2163 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002164 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002165 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002166 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002167 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002168 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002169 }
2170 }
2171 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002172
Robert Greenwalt7b816022014-04-18 15:25:25 -07002173 private void handleAsyncChannelDisconnected(Message msg) {
2174 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2175 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002176 if (DBG) {
2177 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2178 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002179 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002180 // TODO - if we move the logic to the network agent (have them disconnect
2181 // because they lost all their requests or because their score isn't good)
2182 // then they would disconnect organically, report their new state and then
2183 // disconnect the channel.
2184 if (nai.networkInfo.isConnected()) {
2185 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2186 null, null);
2187 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002188 final boolean wasDefault = isDefaultNetwork(nai);
2189 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002190 mDefaultInetConditionPublished = 0;
2191 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002192 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002193 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2194 // by other networks that are already connected. Perhaps that can be done by
2195 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2196 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002197 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002198 mKeepaliveTracker.handleStopAllKeepalives(nai,
2199 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002200 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen578a76e2016-01-14 14:54:39 -05002201 if (nai.apfFilter != null) nai.apfFilter.shutdown();
Paul Jensen3b759822014-05-13 11:44:01 -04002202 mNetworkAgentInfos.remove(msg.replyTo);
2203 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002204 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002205 // Remove the NetworkAgent, but don't mark the netId as
2206 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002207 mNetworkForNetId.remove(nai.network.netId);
2208 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002209 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002210 for (int i = 0; i < nai.networkRequests.size(); i++) {
2211 NetworkRequest request = nai.networkRequests.valueAt(i);
2212 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2213 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2214 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002215 sendUpdatedScoreToFactories(request, 0);
2216 }
2217 }
2218 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2219 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002220 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002221 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002222 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002223 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002224 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002225 if (nai.created) {
2226 // Tell netd to clean up the configuration for this network
2227 // (routing rules, DNS, etc).
2228 // This may be slow as it requires a lot of netd shelling out to ip and
2229 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2230 // after we've rematched networks with requests which should make a potential
2231 // fallback network the default or requested a new network from the
2232 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2233 // long time.
2234 try {
2235 mNetd.removeNetwork(nai.network.netId);
2236 } catch (Exception e) {
2237 loge("Exception removing network: " + e);
2238 }
2239 }
2240 synchronized (mNetworkForNetId) {
2241 mNetIdInUse.delete(nai.network.netId);
2242 }
2243 } else {
2244 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2245 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002246 }
2247 }
2248
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002249 // If this method proves to be too slow then we can maintain a separate
2250 // pendingIntent => NetworkRequestInfo map.
2251 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2252 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2253 Intent intent = pendingIntent.getIntent();
2254 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2255 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2256 if (existingPendingIntent != null &&
2257 existingPendingIntent.getIntent().filterEquals(intent)) {
2258 return entry.getValue();
2259 }
2260 }
2261 return null;
2262 }
2263
2264 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2265 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2266
2267 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2268 if (existingRequest != null) { // remove the existing request.
2269 if (DBG) log("Replacing " + existingRequest.request + " with "
2270 + nri.request + " because their intents matched.");
2271 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2272 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002273 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002274 }
2275
Erik Klineda4bfa82015-04-30 12:58:40 +09002276 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002277 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002278 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002279 if (!nri.isRequest) {
2280 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002281 if (nri.request.networkCapabilities.hasSignalStrength() &&
2282 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2283 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002284 }
2285 }
2286 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002287 rematchAllNetworksAndRequests(null, 0);
2288 if (nri.isRequest && mNetworkForRequestId.get(nri.request.requestId) == null) {
2289 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002290 }
2291 }
2292
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002293 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2294 int callingUid) {
2295 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2296 if (nri != null) {
2297 handleReleaseNetworkRequest(nri.request, callingUid);
2298 }
2299 }
2300
Paul Jensen99364842014-12-09 11:43:45 -05002301 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002302 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2303 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002304 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002305 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002306 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2307 // If this Network is already the highest scoring Network for a request, or if
2308 // there is hope for it to become one if it validated, then it is needed.
2309 if (nri.isRequest && nai.satisfies(nri.request) &&
2310 (nai.networkRequests.get(nri.request.requestId) != null ||
2311 // Note that this catches two important cases:
2312 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2313 // is currently satisfying the request. This is desirable when
2314 // cellular ends up validating but WiFi does not.
2315 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002316 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002317 // WiFi ends up validating and out scoring cellular.
2318 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2319 nai.getCurrentScoreAsValidated())) {
2320 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002321 }
2322 }
Paul Jensene0988542015-06-25 15:30:08 -04002323 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002324 }
2325
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002326 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2327 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002328 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002329 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002330 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2331 return;
2332 }
2333 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002334 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002335 mNetworkRequests.remove(request);
Erik Kline7523eb32015-07-09 18:24:03 +09002336 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002337 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002338 // Find all networks that are satisfying this request and remove the request
2339 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002340 // TODO - it's my understanding that for a request there is only a single
2341 // network satisfying it, so this loop is wasteful
2342 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002343 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2344 if (nai.networkRequests.get(nri.request.requestId) != null) {
2345 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002346 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002347 log(" Removing from current network " + nai.name() +
2348 ", leaving " + nai.networkRequests.size() +
2349 " requests.");
2350 }
Paul Jensen99364842014-12-09 11:43:45 -05002351 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002352 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002353 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002354 } else {
2355 // suspect there should only be one pass through here
2356 // but if any were kept do the check below
2357 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002358 }
2359 }
2360 }
2361
Robert Greenwalt51481852015-01-08 14:43:31 -08002362 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2363 if (nai != null) {
2364 mNetworkForRequestId.remove(nri.request.requestId);
2365 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002366 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002367 // that a network connected to serve it, even though the network was already
2368 // connected. Now that this request has gone away, we might have to pretend
2369 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002370 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002371 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2372 boolean doRemove = true;
2373 if (wasKept) {
2374 // check if any of the remaining requests for this network are for the
2375 // same legacy type - if so, don't remove the nai
2376 for (int i = 0; i < nai.networkRequests.size(); i++) {
2377 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2378 if (otherRequest.legacyType == nri.request.legacyType &&
2379 isRequest(otherRequest)) {
2380 if (DBG) log(" still have other legacy request - leaving");
2381 doRemove = false;
2382 }
2383 }
2384 }
2385
2386 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002387 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002388 }
2389 }
2390
Robert Greenwalta67be032014-05-16 15:49:14 -07002391 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002392 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2393 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002394 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002395 } else {
2396 // listens don't have a singular affectedNetwork. Check all networks to see
2397 // if this listen request applies and remove it.
2398 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2399 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002400 if (nri.request.networkCapabilities.hasSignalStrength() &&
2401 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2402 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002403 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002404 }
2405 }
2406 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2407 }
2408 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002409
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002410 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2411 enforceConnectivityInternalPermission();
2412 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2413 accept ? 1 : 0, always ? 1: 0, network));
2414 }
2415
Paul Jensen578a76e2016-01-14 14:54:39 -05002416 public void pushApfProgramToNetwork(NetworkAgentInfo nai, byte[] program) {
2417 enforceConnectivityInternalPermission();
2418 Message msg = mHandler.obtainMessage(EVENT_PUSH_APF_PROGRAM_TO_NETWORK, program);
2419 msg.replyTo = nai.messenger;
2420 mHandler.sendMessage(msg);
2421 }
2422
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002423 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2424 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2425 " accept=" + accept + " always=" + always);
2426
2427 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2428 if (nai == null) {
2429 // Nothing to do.
2430 return;
2431 }
2432
2433 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002434 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002435 return;
2436 }
2437
2438 if (!nai.networkMisc.explicitlySelected) {
2439 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2440 }
2441
2442 if (accept != nai.networkMisc.acceptUnvalidated) {
2443 int oldScore = nai.getCurrentScore();
2444 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002445 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002446 sendUpdatedScoreToFactories(nai);
2447 }
2448
2449 if (always) {
2450 nai.asyncChannel.sendMessage(
2451 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2452 }
2453
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002454 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002455 // Tell the NetworkAgent to not automatically reconnect to the network.
2456 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2457 // Teardown the nework.
2458 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002459 }
2460
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002461 }
2462
2463 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002464 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002465 mHandler.sendMessageDelayed(
2466 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2467 PROMPT_UNVALIDATED_DELAY_MS);
2468 }
2469
2470 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002471 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002472 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2473
2474 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2475 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002476 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002477 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002478 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2479 return;
2480 }
2481
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002482 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002483 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002484 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2485 intent.setClassName("com.android.settings",
2486 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002487
2488 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2489 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2490 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002491 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002492 }
2493
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002494 private class InternalHandler extends Handler {
2495 public InternalHandler(Looper looper) {
2496 super(looper);
2497 }
2498
2499 @Override
2500 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002501 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002502 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002503 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002504 String causedBy = null;
2505 synchronized (ConnectivityService.this) {
2506 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2507 mNetTransitionWakeLock.isHeld()) {
2508 mNetTransitionWakeLock.release();
2509 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002510 } else {
2511 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002512 }
2513 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002514 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2515 log("Failed to find a new network - expiring NetTransition Wakelock");
2516 } else {
2517 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2518 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002519 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002520 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002521 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002522 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002523 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002524 break;
2525 }
Jason Monkdecd2952013-10-10 14:02:51 -04002526 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002527 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002528 break;
2529 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002530 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002531 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2532 break;
2533 }
2534 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2535 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002536 break;
2537 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002538 case EVENT_REGISTER_NETWORK_AGENT: {
2539 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2540 break;
2541 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002542 case EVENT_REGISTER_NETWORK_REQUEST:
2543 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002544 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002545 break;
2546 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002547 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2548 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002549 handleRegisterNetworkRequestWithIntent(msg);
2550 break;
2551 }
2552 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2553 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2554 break;
2555 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002556 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002557 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002558 break;
2559 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002560 case EVENT_SET_ACCEPT_UNVALIDATED: {
2561 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2562 break;
2563 }
2564 case EVENT_PROMPT_UNVALIDATED: {
2565 handlePromptUnvalidated((Network) msg.obj);
2566 break;
2567 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002568 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2569 handleMobileDataAlwaysOn();
2570 break;
2571 }
Paul Jensen578a76e2016-01-14 14:54:39 -05002572 case EVENT_PUSH_APF_PROGRAM_TO_NETWORK: {
2573 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2574 if (nai == null) {
2575 loge("EVENT_PUSH_APF_PROGRAM_TO_NETWORK from unknown NetworkAgent");
2576 } else {
2577 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PUSH_APF_PROGRAM,
2578 (byte[]) msg.obj);
2579 }
2580 break;
2581 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002582 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2583 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2584 mKeepaliveTracker.handleStartKeepalive(msg);
2585 break;
2586 }
2587 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2588 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2589 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2590 int slot = msg.arg1;
2591 int reason = msg.arg2;
2592 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2593 break;
2594 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002595 case EVENT_SYSTEM_READY: {
2596 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2597 nai.networkMonitor.systemReady = true;
2598 }
2599 break;
2600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 }
2602 }
2603 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002604
2605 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002606 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002607 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002608 if (isTetheringSupported()) {
2609 return mTethering.tether(iface);
2610 } else {
2611 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2612 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002613 }
2614
2615 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002616 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002617 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002618
2619 if (isTetheringSupported()) {
2620 return mTethering.untether(iface);
2621 } else {
2622 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2623 }
2624 }
2625
2626 // javadoc from interface
2627 public int getLastTetherError(String iface) {
2628 enforceTetherAccessPermission();
2629
2630 if (isTetheringSupported()) {
2631 return mTethering.getLastTetherError(iface);
2632 } else {
2633 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2634 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002635 }
2636
2637 // TODO - proper iface API for selection by property, inspection, etc
2638 public String[] getTetherableUsbRegexs() {
2639 enforceTetherAccessPermission();
2640 if (isTetheringSupported()) {
2641 return mTethering.getTetherableUsbRegexs();
2642 } else {
2643 return new String[0];
2644 }
2645 }
2646
2647 public String[] getTetherableWifiRegexs() {
2648 enforceTetherAccessPermission();
2649 if (isTetheringSupported()) {
2650 return mTethering.getTetherableWifiRegexs();
2651 } else {
2652 return new String[0];
2653 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002654 }
2655
Danica Chang6fdd0c62010-08-11 14:54:43 -07002656 public String[] getTetherableBluetoothRegexs() {
2657 enforceTetherAccessPermission();
2658 if (isTetheringSupported()) {
2659 return mTethering.getTetherableBluetoothRegexs();
2660 } else {
2661 return new String[0];
2662 }
2663 }
2664
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002665 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002666 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002667 if (isTetheringSupported()) {
2668 return mTethering.setUsbTethering(enable);
2669 } else {
2670 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2671 }
2672 }
2673
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002674 // TODO - move iface listing, queries, etc to new module
2675 // javadoc from interface
2676 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002677 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002678 return mTethering.getTetherableIfaces();
2679 }
2680
2681 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002682 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002683 return mTethering.getTetheredIfaces();
2684 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002685
Robert Greenwalt5a735062010-03-02 17:25:02 -08002686 public String[] getTetheringErroredIfaces() {
2687 enforceTetherAccessPermission();
2688 return mTethering.getErroredIfaces();
2689 }
2690
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002691 public String[] getTetheredDhcpRanges() {
2692 enforceConnectivityInternalPermission();
2693 return mTethering.getTetheredDhcpRanges();
2694 }
2695
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002696 // if ro.tether.denied = true we default to no tethering
2697 // gservices could set the secure setting to 1 though to enable it on a build where it
2698 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002699 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002700 public boolean isTetheringSupported() {
2701 enforceTetherAccessPermission();
2702 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002703 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002704 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2705 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002706 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2707 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002708 mTethering.getTetherableWifiRegexs().length != 0 ||
2709 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2710 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002711 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002712
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002713 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002714 public void startTethering(int type, ResultReceiver receiver,
2715 boolean showProvisioningUi) {
2716 ConnectivityManager.enforceTetherChangePermission(mContext);
2717 if (!isTetheringSupported()) {
2718 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2719 return;
2720 }
2721 mTethering.startTethering(type, receiver, showProvisioningUi);
2722 }
2723
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002724 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002725 public void stopTethering(int type) {
2726 ConnectivityManager.enforceTetherChangePermission(mContext);
2727 mTethering.stopTethering(type);
2728 }
2729
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002730 // Called when we lose the default network and have no replacement yet.
2731 // This will automatically be cleared after X seconds or a new default network
2732 // becomes CONNECTED, whichever happens first. The timer is started by the
2733 // first caller and not restarted by subsequent callers.
2734 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002735 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002736 synchronized (this) {
2737 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002738 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002739 mNetTransitionWakeLock.acquire();
2740 mNetTransitionWakeLockCausedBy = forWhom;
2741 }
2742 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002743 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002744 mNetTransitionWakeLockTimeout);
2745 return;
2746 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002747
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002748 // 100 percent is full good, 0 is full bad.
2749 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002750 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002751 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002752 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002753 }
2754
Paul Jensenbfd17b72015-04-07 12:43:13 -04002755 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002756 enforceAccessPermission();
2757 enforceInternetPermission();
2758
Paul Jensenbfd17b72015-04-07 12:43:13 -04002759 NetworkAgentInfo nai;
2760 if (network == null) {
2761 nai = getDefaultNetwork();
2762 } else {
2763 nai = getNetworkAgentInfoForNetwork(network);
2764 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002765 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2766 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2767 return;
2768 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002769 // Revalidate if the app report does not match our current validated state.
2770 if (hasConnectivity == nai.lastValidated) return;
2771 final int uid = Binder.getCallingUid();
2772 if (DBG) {
2773 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2774 ") by " + uid);
2775 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002776 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002777 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2778 // which isn't meant to work on uncreated networks.
2779 if (!nai.created) return;
2780
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002781 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002782
2783 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2784 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002785 }
2786
Paul Jensencee9b512015-05-06 07:32:40 -04002787 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002788 // this information is already available as a world read/writable jvm property
2789 // so this API change wouldn't have a benifit. It also breaks the passing
2790 // of proxy info to all the JVMs.
2791 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002792 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002793 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002794 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2795 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002796 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002797 }
2798
Paul Jensencee9b512015-05-06 07:32:40 -04002799 public ProxyInfo getProxyForNetwork(Network network) {
2800 if (network == null) return getDefaultProxy();
2801 final ProxyInfo globalProxy = getGlobalProxy();
2802 if (globalProxy != null) return globalProxy;
2803 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2804 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2805 // caller may not have.
2806 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2807 if (nai == null) return null;
2808 synchronized (nai) {
2809 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2810 if (proxyInfo == null) return null;
2811 return new ProxyInfo(proxyInfo);
2812 }
2813 }
2814
Paul Jensene0bef712014-12-10 15:12:18 -05002815 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2816 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2817 // proxy is null then there is no proxy in place).
2818 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2819 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2820 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2821 proxy = null;
2822 }
2823 return proxy;
2824 }
2825
2826 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2827 // better for determining if a new proxy broadcast is necessary:
2828 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2829 // avoid unnecessary broadcasts.
2830 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2831 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2832 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2833 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2834 // all set.
2835 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2836 a = canonicalizeProxyInfo(a);
2837 b = canonicalizeProxyInfo(b);
2838 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2839 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2840 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2841 }
2842
Jason Monk207900c2014-04-25 15:00:09 -04002843 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002844 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002845
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002846 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002847 if (proxyProperties == mGlobalProxy) return;
2848 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2849 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2850
2851 String host = "";
2852 int port = 0;
2853 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002854 String pacFileUrl = "";
2855 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002856 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002857 if (!proxyProperties.isValid()) {
2858 if (DBG)
2859 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2860 return;
2861 }
Jason Monk207900c2014-04-25 15:00:09 -04002862 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002863 host = mGlobalProxy.getHost();
2864 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002865 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002866 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002867 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002868 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002869 } else {
2870 mGlobalProxy = null;
2871 }
2872 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002873 final long token = Binder.clearCallingIdentity();
2874 try {
2875 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2876 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2877 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2878 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002879 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002880 } finally {
2881 Binder.restoreCallingIdentity(token);
2882 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002883
Jason Monkcf0f97a2014-10-02 15:39:38 -04002884 if (mGlobalProxy == null) {
2885 proxyProperties = mDefaultProxy;
2886 }
2887 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002888 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002889 }
2890
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002891 private void loadGlobalProxy() {
2892 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002893 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2894 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2895 String exclList = Settings.Global.getString(res,
2896 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002897 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2898 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002899 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002900 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002901 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002902 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002903 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002904 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002905 if (!proxyProperties.isValid()) {
2906 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2907 return;
2908 }
2909
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002910 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002911 mGlobalProxy = proxyProperties;
2912 }
2913 }
2914 }
2915
Jason Monk207900c2014-04-25 15:00:09 -04002916 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002917 // this information is already available as a world read/writable jvm property
2918 // so this API change wouldn't have a benifit. It also breaks the passing
2919 // of proxy info to all the JVMs.
2920 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002921 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002922 return mGlobalProxy;
2923 }
2924 }
2925
Jason Monk207900c2014-04-25 15:00:09 -04002926 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002927 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002928 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002929 proxy = null;
2930 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002931 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002932 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002933 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002934 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002935 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2936 return;
2937 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002938
2939 // This call could be coming from the PacManager, containing the port of the local
2940 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2941 // global (to get the correct local port), and send a broadcast.
2942 // TODO: Switch PacManager to have its own message to send back rather than
2943 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002944 if ((mGlobalProxy != null) && (proxy != null)
2945 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002946 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2947 mGlobalProxy = proxy;
2948 sendProxyBroadcast(mGlobalProxy);
2949 return;
2950 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002951 mDefaultProxy = proxy;
2952
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002953 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002954 if (!mDefaultProxyDisabled) {
2955 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002956 }
2957 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002958 }
2959
Paul Jensene0bef712014-12-10 15:12:18 -05002960 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2961 // This method gets called when any network changes proxy, but the broadcast only ever contains
2962 // the default proxy (even if it hasn't changed).
2963 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2964 // world where an app might be bound to a non-default network.
2965 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2966 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2967 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2968
2969 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2970 sendProxyBroadcast(getDefaultProxy());
2971 }
2972 }
2973
Robert Greenwalt434203a2010-10-11 16:00:27 -07002974 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002975 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2976 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002977 if (!TextUtils.isEmpty(proxy)) {
2978 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002979 if (data.length == 0) {
2980 return;
2981 }
2982
Robert Greenwalt434203a2010-10-11 16:00:27 -07002983 String proxyHost = data[0];
2984 int proxyPort = 8080;
2985 if (data.length > 1) {
2986 try {
2987 proxyPort = Integer.parseInt(data[1]);
2988 } catch (NumberFormatException e) {
2989 return;
2990 }
2991 }
Jason Monk207900c2014-04-25 15:00:09 -04002992 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002993 setGlobalProxy(p);
2994 }
2995 }
2996
Jason Monk207900c2014-04-25 15:00:09 -04002997 private void sendProxyBroadcast(ProxyInfo proxy) {
2998 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002999 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003000 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003001 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003002 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3003 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003004 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003005 final long ident = Binder.clearCallingIdentity();
3006 try {
3007 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3008 } finally {
3009 Binder.restoreCallingIdentity(ident);
3010 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003011 }
3012
3013 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003014 final private HashMap<Uri, Integer> mUriEventMap;
3015 final private Context mContext;
3016 final private Handler mHandler;
3017
3018 SettingsObserver(Context context, Handler handler) {
3019 super(null);
3020 mUriEventMap = new HashMap<Uri, Integer>();
3021 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003022 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003023 }
3024
Erik Klineda4bfa82015-04-30 12:58:40 +09003025 void observe(Uri uri, int what) {
3026 mUriEventMap.put(uri, what);
3027 final ContentResolver resolver = mContext.getContentResolver();
3028 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003029 }
3030
3031 @Override
3032 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003033 Slog.wtf(TAG, "Should never be reached.");
3034 }
3035
3036 @Override
3037 public void onChange(boolean selfChange, Uri uri) {
3038 final Integer what = mUriEventMap.get(uri);
3039 if (what != null) {
3040 mHandler.obtainMessage(what.intValue()).sendToTarget();
3041 } else {
3042 loge("No matching event to send for URI=" + uri);
3043 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003044 }
3045 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003046
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003047 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003048 Slog.d(TAG, s);
3049 }
3050
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003051 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003052 Slog.e(TAG, s);
3053 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003054
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003055 private static <T> T checkNotNull(T value, String message) {
3056 if (value == null) {
3057 throw new NullPointerException(message);
3058 }
3059 return value;
3060 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003061
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003062 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003063 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003064 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3065 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3066 *
3067 * @param oldPackage Package name of the application which currently controls VPN, which will
3068 * be replaced. If there is no such application, this should should either be
3069 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3070 * @param newPackage Package name of the application which should gain control of VPN, or
3071 * {@code null} to disable.
3072 * @param userId User for whom to prepare the new VPN.
3073 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003074 * @hide
3075 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003076 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003077 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3078 int userId) {
3079 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003080 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003081
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003082 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003083 Vpn vpn = mVpns.get(userId);
3084 if (vpn != null) {
3085 return vpn.prepare(oldPackage, newPackage);
3086 } else {
3087 return false;
3088 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003089 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003090 }
3091
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003092 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003093 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3094 * This method is used by system-privileged apps.
3095 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3096 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3097 *
3098 * @param packageName The package for which authorization state should change.
3099 * @param userId User for whom {@code packageName} is installed.
3100 * @param authorized {@code true} if this app should be able to start a VPN connection without
3101 * explicit user approval, {@code false} if not.
3102 *
Jeff Davidson05542602014-08-11 14:07:27 -07003103 * @hide
3104 */
3105 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003106 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3107 enforceCrossUserPermission(userId);
3108
Jeff Davidson05542602014-08-11 14:07:27 -07003109 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003110 Vpn vpn = mVpns.get(userId);
3111 if (vpn != null) {
3112 vpn.setPackageAuthorization(packageName, authorized);
3113 }
Jeff Davidson05542602014-08-11 14:07:27 -07003114 }
3115 }
3116
3117 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003118 * Configure a TUN interface and return its file descriptor. Parameters
3119 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003120 * and not available in ConnectivityManager. Permissions are checked in
3121 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003122 * @hide
3123 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003124 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003125 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003126 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003127 int user = UserHandle.getUserId(Binder.getCallingUid());
3128 synchronized(mVpns) {
3129 return mVpns.get(user).establish(config);
3130 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003131 }
3132
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003133 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003134 * Start legacy VPN, controlling native daemons as needed. Creates a
3135 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003136 */
3137 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003138 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003139 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003140 final LinkProperties egress = getActiveLinkProperties();
3141 if (egress == null) {
3142 throw new IllegalStateException("Missing active network connection");
3143 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003144 int user = UserHandle.getUserId(Binder.getCallingUid());
3145 synchronized(mVpns) {
3146 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3147 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003148 }
3149
3150 /**
3151 * Return the information of the ongoing legacy VPN. This method is used
3152 * by VpnSettings and not available in ConnectivityManager. Permissions
3153 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003154 */
3155 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003156 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3157 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003158 if (mLockdownEnabled) {
3159 return null;
3160 }
3161
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003162 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003163 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003164 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003165 }
3166
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003167 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003168 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3169 * and not available in ConnectivityManager.
3170 */
3171 @Override
3172 public VpnInfo[] getAllVpnInfo() {
3173 enforceConnectivityInternalPermission();
3174 if (mLockdownEnabled) {
3175 return new VpnInfo[0];
3176 }
3177
3178 synchronized(mVpns) {
3179 List<VpnInfo> infoList = new ArrayList<>();
3180 for (int i = 0; i < mVpns.size(); i++) {
3181 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3182 if (info != null) {
3183 infoList.add(info);
3184 }
3185 }
3186 return infoList.toArray(new VpnInfo[infoList.size()]);
3187 }
3188 }
3189
3190 /**
3191 * @return VPN information for accounting, or null if we can't retrieve all required
3192 * information, e.g primary underlying iface.
3193 */
3194 @Nullable
3195 private VpnInfo createVpnInfo(Vpn vpn) {
3196 VpnInfo info = vpn.getVpnInfo();
3197 if (info == null) {
3198 return null;
3199 }
3200 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3201 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3202 // the underlyingNetworks list.
3203 if (underlyingNetworks == null) {
3204 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3205 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3206 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3207 }
3208 } else if (underlyingNetworks.length > 0) {
3209 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3210 if (linkProperties != null) {
3211 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3212 }
3213 }
3214 return info.primaryUnderlyingIface == null ? null : info;
3215 }
3216
3217 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003218 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3219 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003220 * Permissions are checked in Vpn class.
3221 * @hide
3222 */
3223 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003224 public VpnConfig getVpnConfig(int userId) {
3225 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003226 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003227 Vpn vpn = mVpns.get(userId);
3228 if (vpn != null) {
3229 return vpn.getVpnConfig();
3230 } else {
3231 return null;
3232 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003233 }
3234 }
3235
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003236 @Override
3237 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003238 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3239 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3240 return false;
3241 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003242
3243 // Tear down existing lockdown if profile was removed
3244 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3245 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003246 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3247 final VpnProfile profile = VpnProfile.decode(
3248 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003249 if (profile == null) {
3250 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3251 setLockdownTracker(null);
3252 return true;
3253 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003254 int user = UserHandle.getUserId(Binder.getCallingUid());
3255 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003256 Vpn vpn = mVpns.get(user);
3257 if (vpn == null) {
3258 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3259 return false;
3260 }
3261 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003262 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003263 } else {
3264 setLockdownTracker(null);
3265 }
3266
3267 return true;
3268 }
3269
3270 /**
3271 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3272 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3273 */
3274 private void setLockdownTracker(LockdownVpnTracker tracker) {
3275 // Shutdown any existing tracker
3276 final LockdownVpnTracker existing = mLockdownTracker;
3277 mLockdownTracker = null;
3278 if (existing != null) {
3279 existing.shutdown();
3280 }
3281
3282 try {
3283 if (tracker != null) {
3284 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003285 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003286 mLockdownTracker = tracker;
3287 mLockdownTracker.init();
3288 } else {
3289 mNetd.setFirewallEnabled(false);
3290 }
3291 } catch (RemoteException e) {
3292 // ignored; NMS lives inside system_server
3293 }
3294 }
3295
3296 private void throwIfLockdownEnabled() {
3297 if (mLockdownEnabled) {
3298 throw new IllegalStateException("Unavailable in lockdown mode");
3299 }
3300 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003301
Robin Lee244ce8e2016-01-05 18:03:46 +00003302 /**
3303 * Sets up or tears down the always-on VPN for user {@param user} as appropriate.
3304 *
3305 * @return {@code false} in case of errors; {@code true} otherwise.
3306 */
3307 private boolean updateAlwaysOnVpn(int user) {
3308 final String lockdownPackage = getAlwaysOnVpnPackage(user);
3309 if (lockdownPackage == null) {
3310 return true;
3311 }
3312
3313 // Create an intent to start the VPN service declared in the app's manifest.
3314 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
3315 serviceIntent.setPackage(lockdownPackage);
3316
3317 try {
3318 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(user)) != null;
3319 } catch (RuntimeException e) {
3320 return false;
3321 }
3322 }
3323
3324 @Override
3325 public boolean setAlwaysOnVpnPackage(int userId, String packageName) {
3326 enforceConnectivityInternalPermission();
3327 enforceCrossUserPermission(userId);
3328
3329 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3330 if (LockdownVpnTracker.isEnabled()) {
3331 return false;
3332 }
3333
3334 // If the current VPN package is the same as the new one, this is a no-op
3335 final String oldPackage = getAlwaysOnVpnPackage(userId);
3336 if (TextUtils.equals(oldPackage, packageName)) {
3337 return true;
3338 }
3339
3340 synchronized (mVpns) {
3341 Vpn vpn = mVpns.get(userId);
3342 if (vpn == null) {
3343 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3344 return false;
3345 }
3346 if (!vpn.setAlwaysOnPackage(packageName)) {
3347 return false;
3348 }
3349 if (!updateAlwaysOnVpn(userId)) {
3350 vpn.setAlwaysOnPackage(null);
3351 return false;
3352 }
3353 }
3354 return true;
3355 }
3356
3357 @Override
3358 public String getAlwaysOnVpnPackage(int userId) {
3359 enforceConnectivityInternalPermission();
3360 enforceCrossUserPermission(userId);
3361
3362 synchronized (mVpns) {
3363 Vpn vpn = mVpns.get(userId);
3364 if (vpn == null) {
3365 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3366 return null;
3367 }
3368 return vpn.getAlwaysOnPackage();
3369 }
3370 }
3371
Wink Savilleab9321d2013-06-29 21:10:57 -07003372 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003373 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003374 // TODO: Remove? Any reason to trigger a provisioning check?
3375 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003376 }
3377
3378 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003379 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003380
Paul Jensen89e0f092014-09-15 15:59:36 -04003381 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003382 if (DBG) {
3383 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003384 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003385 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003386 Intent intent = new Intent(action);
3387 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003388 // Concatenate the range of types onto the range of NetIDs.
3389 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003390 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003391 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003392 }
3393
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003394 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003395 * Show or hide network provisioning notifications.
3396 *
3397 * We use notifications for two purposes: to notify that a network requires sign in
3398 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3399 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3400 * particular network we can display the notification type that was most recently requested.
3401 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3402 * might first display NO_INTERNET, and then when the captive portal check completes, display
3403 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003404 *
3405 * @param id an identifier that uniquely identifies this notification. This must match
3406 * between show and hide calls. We use the NetID value but for legacy callers
3407 * we concatenate the range of types with the range of NetIDs.
3408 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003409 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003410 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3411 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003412 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003413 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3414 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003415 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003416 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003417
3418 Resources r = Resources.getSystem();
3419 NotificationManager notificationManager = (NotificationManager) mContext
3420 .getSystemService(Context.NOTIFICATION_SERVICE);
3421
3422 if (visible) {
3423 CharSequence title;
3424 CharSequence details;
3425 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003426 if (notifyType == NotificationType.NO_INTERNET &&
3427 networkType == ConnectivityManager.TYPE_WIFI) {
3428 title = r.getString(R.string.wifi_no_internet, 0);
3429 details = r.getString(R.string.wifi_no_internet_detailed);
3430 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3431 } else if (notifyType == NotificationType.SIGN_IN) {
3432 switch (networkType) {
3433 case ConnectivityManager.TYPE_WIFI:
3434 title = r.getString(R.string.wifi_available_sign_in, 0);
3435 details = r.getString(R.string.network_available_sign_in_detailed,
3436 extraInfo);
3437 icon = R.drawable.stat_notify_wifi_in_range;
3438 break;
3439 case ConnectivityManager.TYPE_MOBILE:
3440 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3441 title = r.getString(R.string.network_available_sign_in, 0);
3442 // TODO: Change this to pull from NetworkInfo once a printable
3443 // name has been added to it
3444 details = mTelephonyManager.getNetworkOperatorName();
3445 icon = R.drawable.stat_notify_rssi_in_range;
3446 break;
3447 default:
3448 title = r.getString(R.string.network_available_sign_in, 0);
3449 details = r.getString(R.string.network_available_sign_in_detailed,
3450 extraInfo);
3451 icon = R.drawable.stat_notify_rssi_in_range;
3452 break;
3453 }
3454 } else {
3455 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3456 + getNetworkTypeName(networkType));
3457 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003458 }
3459
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003460 Notification notification = new Notification.Builder(mContext)
3461 .setWhen(0)
3462 .setSmallIcon(icon)
3463 .setAutoCancel(true)
3464 .setTicker(title)
3465 .setColor(mContext.getColor(
3466 com.android.internal.R.color.system_notification_accent_color))
3467 .setContentTitle(title)
3468 .setContentText(details)
3469 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003470 .setLocalOnly(true)
3471 .setPriority(highPriority ?
3472 Notification.PRIORITY_HIGH :
3473 Notification.PRIORITY_DEFAULT)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003474 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003475 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003476 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003477
Wink Saville948282b2013-08-29 08:55:16 -07003478 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003479 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003480 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003481 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003482 npe.printStackTrace();
3483 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003484 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003485 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003486 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003487 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003488 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003489 npe.printStackTrace();
3490 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003491 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003492 }
3493
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003494 /** Location to an updatable file listing carrier provisioning urls.
3495 * An example:
3496 *
3497 * <?xml version="1.0" encoding="utf-8"?>
3498 * <provisioningUrls>
3499 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003500 * </provisioningUrls>
3501 */
3502 private static final String PROVISIONING_URL_PATH =
3503 "/data/misc/radio/provisioning_urls.xml";
3504 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003505
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003506 /** XML tag for root element. */
3507 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3508 /** XML tag for individual url */
3509 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003510 /** XML attribute for mcc */
3511 private static final String ATTR_MCC = "mcc";
3512 /** XML attribute for mnc */
3513 private static final String ATTR_MNC = "mnc";
3514
Paul Jensen434dde82015-06-11 09:43:30 -04003515 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003516 FileReader fileReader = null;
3517 XmlPullParser parser = null;
3518 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003519
3520 try {
3521 fileReader = new FileReader(mProvisioningUrlFile);
3522 parser = Xml.newPullParser();
3523 parser.setInput(fileReader);
3524 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3525
3526 while (true) {
3527 XmlUtils.nextElement(parser);
3528
3529 String element = parser.getName();
3530 if (element == null) break;
3531
Paul Jensen434dde82015-06-11 09:43:30 -04003532 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003533 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3534 try {
3535 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3536 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3537 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3538 parser.next();
3539 if (parser.getEventType() == XmlPullParser.TEXT) {
3540 return parser.getText();
3541 }
3542 }
3543 }
3544 } catch (NumberFormatException e) {
3545 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3546 }
3547 }
3548 }
3549 return null;
3550 } catch (FileNotFoundException e) {
3551 loge("Carrier Provisioning Urls file not found");
3552 } catch (XmlPullParserException e) {
3553 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3554 } catch (IOException e) {
3555 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3556 } finally {
3557 if (fileReader != null) {
3558 try {
3559 fileReader.close();
3560 } catch (IOException e) {}
3561 }
3562 }
3563 return null;
3564 }
3565
Wink Saville42d4f082013-07-20 20:31:59 -07003566 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003567 public String getMobileProvisioningUrl() {
3568 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003569 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003570 if (TextUtils.isEmpty(url)) {
3571 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003572 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003573 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003574 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003575 }
Wink Saville8cf35602013-07-10 23:00:07 -07003576 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003577 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003578 String phoneNumber = mTelephonyManager.getLine1Number();
3579 if (TextUtils.isEmpty(phoneNumber)) {
3580 phoneNumber = "0000000000";
3581 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003582 url = String.format(url,
3583 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3584 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003585 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003586 }
3587
Wink Savilleab9321d2013-06-29 21:10:57 -07003588 return url;
3589 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003590
Wink Saville948282b2013-08-29 08:55:16 -07003591 @Override
3592 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003593 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003594 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003595 final long ident = Binder.clearCallingIdentity();
3596 try {
3597 setProvNotificationVisible(visible, networkType, action);
3598 } finally {
3599 Binder.restoreCallingIdentity(ident);
3600 }
Wink Saville948282b2013-08-29 08:55:16 -07003601 }
Wink Saville7788c612013-08-29 14:57:08 -07003602
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003603 @Override
3604 public void setAirplaneMode(boolean enable) {
3605 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003606 final long ident = Binder.clearCallingIdentity();
3607 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003608 final ContentResolver cr = mContext.getContentResolver();
3609 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3610 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3611 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003612 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003613 } finally {
3614 Binder.restoreCallingIdentity(ident);
3615 }
3616 }
3617
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003618 private void onUserStart(int userId) {
3619 synchronized(mVpns) {
3620 Vpn userVpn = mVpns.get(userId);
3621 if (userVpn != null) {
3622 loge("Starting user already has a VPN");
3623 return;
3624 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003625 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003626 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003627 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003628 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3629 updateLockdownVpn();
3630 } else {
3631 updateAlwaysOnVpn(userId);
3632 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003633 }
3634
3635 private void onUserStop(int userId) {
3636 synchronized(mVpns) {
3637 Vpn userVpn = mVpns.get(userId);
3638 if (userVpn == null) {
3639 loge("Stopping user has no VPN");
3640 return;
3641 }
3642 mVpns.delete(userId);
3643 }
3644 }
3645
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003646 private void onUserAdded(int userId) {
3647 synchronized(mVpns) {
3648 final int vpnsSize = mVpns.size();
3649 for (int i = 0; i < vpnsSize; i++) {
3650 Vpn vpn = mVpns.valueAt(i);
3651 vpn.onUserAdded(userId);
3652 }
3653 }
3654 }
3655
3656 private void onUserRemoved(int userId) {
3657 synchronized(mVpns) {
3658 final int vpnsSize = mVpns.size();
3659 for (int i = 0; i < vpnsSize; i++) {
3660 Vpn vpn = mVpns.valueAt(i);
3661 vpn.onUserRemoved(userId);
3662 }
3663 }
3664 }
3665
Robin Lee89e7a692016-02-29 14:38:17 +00003666 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003667 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3668 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3669 updateLockdownVpn();
3670 } else {
3671 updateAlwaysOnVpn(userId);
3672 }
3673 }
3674
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003675 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3676 @Override
3677 public void onReceive(Context context, Intent intent) {
3678 final String action = intent.getAction();
3679 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3680 if (userId == UserHandle.USER_NULL) return;
3681
3682 if (Intent.ACTION_USER_STARTING.equals(action)) {
3683 onUserStart(userId);
3684 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3685 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003686 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3687 onUserAdded(userId);
3688 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3689 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003690 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3691 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003692 }
3693 }
3694 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003695
Robert Greenwalta67be032014-05-16 15:49:14 -07003696 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3697 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003698 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3699 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003700
Robert Greenwalta67be032014-05-16 15:49:14 -07003701 private static class NetworkFactoryInfo {
3702 public final String name;
3703 public final Messenger messenger;
3704 public final AsyncChannel asyncChannel;
3705
3706 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3707 this.name = name;
3708 this.messenger = messenger;
3709 this.asyncChannel = asyncChannel;
3710 }
3711 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003712
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003713 /**
3714 * Tracks info about the requester.
3715 * Also used to notice when the calling process dies so we can self-expire
3716 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003717 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3718 static final boolean REQUEST = true;
3719 static final boolean LISTEN = false;
3720
3721 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003722 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003723 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003724 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003725 final int mPid;
3726 final int mUid;
3727 final Messenger messenger;
3728 final boolean isRequest;
3729
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003730 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3731 request = r;
3732 mPendingIntent = pi;
3733 messenger = null;
3734 mBinder = null;
3735 mPid = getCallingPid();
3736 mUid = getCallingUid();
3737 this.isRequest = isRequest;
3738 }
3739
Robert Greenwalt9258c642014-03-26 16:47:06 -07003740 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3741 super();
3742 messenger = m;
3743 request = r;
3744 mBinder = binder;
3745 mPid = getCallingPid();
3746 mUid = getCallingUid();
3747 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003748 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003749
3750 try {
3751 mBinder.linkToDeath(this, 0);
3752 } catch (RemoteException e) {
3753 binderDied();
3754 }
3755 }
3756
3757 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003758 if (mBinder != null) {
3759 mBinder.unlinkToDeath(this, 0);
3760 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003761 }
3762
3763 public void binderDied() {
3764 log("ConnectivityService NetworkRequestInfo binderDied(" +
3765 request + ", " + mBinder + ")");
3766 releaseNetworkRequest(request);
3767 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003768
3769 public String toString() {
Erik Kline7523eb32015-07-09 18:24:03 +09003770 return (isRequest ? "Request" : "Listen") +
3771 " from uid/pid:" + mUid + "/" + mPid +
3772 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003773 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003774 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003775 }
3776
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003777 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3778 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3779 if (badCapability != null) {
3780 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003781 }
3782 }
3783
Erik Kline9d598e12015-07-13 16:37:51 +09003784 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003785 final SortedSet<Integer> thresholds = new TreeSet();
3786 synchronized (nai) {
3787 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3788 if (nri.request.networkCapabilities.hasSignalStrength() &&
3789 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3790 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3791 }
3792 }
3793 }
Erik Kline9d598e12015-07-13 16:37:51 +09003794 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003795 }
3796
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003797 private void updateSignalStrengthThresholds(
3798 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3799 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003800 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003801 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3802
3803 // TODO: Switch to VDBG.
3804 if (DBG) {
3805 String detail;
3806 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3807 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3808 } else {
3809 detail = reason;
3810 }
3811 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3812 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3813 }
3814
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003815 nai.asyncChannel.sendMessage(
3816 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003817 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003818 }
3819
Robert Greenwalt9258c642014-03-26 16:47:06 -07003820 @Override
3821 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003822 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003823 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003824 enforceNetworkRequestPermissions(networkCapabilities);
3825 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003826 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003827
Robert Greenwalt6078b502014-06-11 16:05:07 -07003828 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003829 throw new IllegalArgumentException("Bad timeout specified");
3830 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003831
Etan Cohenddb9ef02015-11-18 10:56:15 -08003832 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
3833 .equals(networkCapabilities.getNetworkSpecifier())) {
3834 throw new IllegalArgumentException("Invalid network specifier - must not be '"
3835 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
3836 }
3837
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003838 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3839 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003840 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3841 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003842 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003843
3844 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003845 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003846 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003847 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003848 }
3849 return networkRequest;
3850 }
3851
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003852 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003853 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003854 enforceConnectivityInternalPermission();
3855 } else {
3856 enforceChangePermission();
3857 }
3858 }
3859
fenglub15e72b2015-03-20 11:29:56 -07003860 @Override
fengludb571472015-04-21 17:12:05 -07003861 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003862 enforceAccessPermission();
3863 NetworkAgentInfo nai = null;
3864 if (network == null) {
3865 return false;
3866 }
3867 synchronized (mNetworkForNetId) {
3868 nai = mNetworkForNetId.get(network.netId);
3869 }
3870 if (nai != null) {
3871 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3872 return true;
3873 }
3874 return false;
3875 }
3876
3877
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003878 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3879 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003880 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003881 final int uidRules;
3882 final int uid = Binder.getCallingUid();
3883 synchronized(mRulesLock) {
3884 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3885 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003886 if (uidRules != RULE_ALLOW_ALL) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003887 // we could silently fail or we can filter the available nets to only give
3888 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003889 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003890 }
3891 }
3892 }
3893
Robert Greenwalt9258c642014-03-26 16:47:06 -07003894 @Override
3895 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3896 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003897 checkNotNull(operation, "PendingIntent cannot be null.");
3898 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3899 enforceNetworkRequestPermissions(networkCapabilities);
3900 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003901 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003902
3903 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3904 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003905 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3906 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003907 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003908 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3909 nri));
3910 return networkRequest;
3911 }
3912
Jeremy Joslin79294842014-12-03 17:15:28 -08003913 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3914 mHandler.sendMessageDelayed(
3915 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3916 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3917 }
3918
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003919 @Override
3920 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003921 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003922 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3923 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003924 }
3925
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003926 // In order to implement the compatibility measure for pre-M apps that call
3927 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3928 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3929 // This ensures it has permission to do so.
3930 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3931 if (nc == null) {
3932 return false;
3933 }
3934 int[] transportTypes = nc.getTransportTypes();
3935 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3936 return false;
3937 }
3938 try {
3939 mContext.enforceCallingOrSelfPermission(
3940 android.Manifest.permission.ACCESS_WIFI_STATE,
3941 "ConnectivityService");
3942 } catch (SecurityException e) {
3943 return false;
3944 }
3945 return true;
3946 }
3947
Robert Greenwalt9258c642014-03-26 16:47:06 -07003948 @Override
3949 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3950 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003951 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3952 enforceAccessPermission();
3953 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003954
Erik Kline7523eb32015-07-09 18:24:03 +09003955 NetworkRequest networkRequest = new NetworkRequest(
3956 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003957 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3958 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003959 if (DBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003960
3961 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3962 return networkRequest;
3963 }
3964
3965 @Override
3966 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3967 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003968 checkNotNull(operation, "PendingIntent cannot be null.");
3969 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3970 enforceAccessPermission();
3971 }
3972
Erik Kline7523eb32015-07-09 18:24:03 +09003973 NetworkRequest networkRequest = new NetworkRequest(
3974 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04003975 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3976 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003977 if (DBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04003978
3979 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003980 }
3981
3982 @Override
3983 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003984 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3985 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003986 }
3987
3988 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003989 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003990 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003991 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3992 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003993 }
3994
Robert Greenwalta67be032014-05-16 15:49:14 -07003995 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003996 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003997 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3998 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3999 }
4000
4001 @Override
4002 public void unregisterNetworkFactory(Messenger messenger) {
4003 enforceConnectivityInternalPermission();
4004 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4005 }
4006
4007 private void handleUnregisterNetworkFactory(Messenger messenger) {
4008 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4009 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004010 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004011 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004012 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004013 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004014 }
4015
Robert Greenwalt7b816022014-04-18 15:25:25 -07004016 /**
4017 * NetworkAgentInfo supporting a request by requestId.
4018 * These have already been vetted (their Capabilities satisfy the request)
4019 * and the are the highest scored network available.
4020 * the are keyed off the Requests requestId.
4021 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004022 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004023 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4024 new SparseArray<NetworkAgentInfo>();
4025
Paul Jensen31a94f42015-02-13 14:18:39 -05004026 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4027 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004028 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4029 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004030 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4031 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4032 // there may not be a strict 1:1 correlation between the two.
4033 @GuardedBy("mNetworkForNetId")
4034 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004035
Robert Greenwalt7b816022014-04-18 15:25:25 -07004036 // NetworkAgentInfo keyed off its connecting messenger
4037 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004038 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004039 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4040 new HashMap<Messenger, NetworkAgentInfo>();
4041
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004042 @GuardedBy("mBlockedAppUids")
4043 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4044
Paul Jensen2c311d62014-11-17 12:34:51 -05004045 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004046 private final NetworkRequest mDefaultRequest;
4047
Erik Klineda4bfa82015-04-30 12:58:40 +09004048 // Request used to optionally keep mobile data active even when higher
4049 // priority networks like Wi-Fi are active.
4050 private final NetworkRequest mDefaultMobileDataRequest;
4051
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004052 private NetworkAgentInfo getDefaultNetwork() {
4053 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4054 }
4055
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004056 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004057 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004058 }
4059
Paul Jensen31a94f42015-02-13 14:18:39 -05004060 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004061 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004062 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004063 enforceConnectivityInternalPermission();
4064
Paul Jensen2c311d62014-11-17 12:34:51 -05004065 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4066 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004067 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004068 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4069 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004070 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004071 synchronized (this) {
4072 nai.networkMonitor.systemReady = mSystemReady;
4073 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07004074 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004075 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004076 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004077 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004078 }
4079
4080 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4081 if (VDBG) log("Got NetworkAgent Messenger");
4082 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004083 synchronized (mNetworkForNetId) {
4084 mNetworkForNetId.put(na.network.netId, na);
4085 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004086 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4087 NetworkInfo networkInfo = na.networkInfo;
4088 na.networkInfo = null;
4089 updateNetworkInfo(na, networkInfo);
4090 }
4091
4092 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4093 LinkProperties newLp = networkAgent.linkProperties;
4094 int netId = networkAgent.network.netId;
4095
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004096 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4097 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004098 if (networkAgent.clatd != null) {
4099 networkAgent.clatd.fixupLinkProperties(oldLp);
4100 }
Paul Jensen578a76e2016-01-14 14:54:39 -05004101 if (networkAgent.apfFilter != null) {
4102 networkAgent.apfFilter.updateFilter();
4103 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004104
Paul Jensen992f2522014-04-28 10:33:11 -04004105 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004106 updateMtu(newLp, oldLp);
4107 // TODO - figure out what to do for clat
4108// for (LinkProperties lp : newLp.getStackedLinks()) {
4109// updateMtu(lp, null);
4110// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004111 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004112
Lorenzo Colitti93155b32015-05-14 22:12:36 +09004113 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
4114 // In L, we used it only when the network had Internet access but provided no DNS servers.
4115 // For now, just disable it, and if disabling it doesn't break things, remove it.
4116 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
4117 // NET_CAPABILITY_INTERNET);
4118 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004119 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004120 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
4121
Paul Jensen3b759822014-05-13 11:44:01 -04004122 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004123 if (isDefaultNetwork(networkAgent)) {
4124 handleApplyDefaultProxy(newLp.getHttpProxy());
4125 } else {
4126 updateProxy(newLp, oldLp, networkAgent);
4127 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004128 // TODO - move this check to cover the whole function
4129 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004130 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004131 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4132 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004133
4134 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004135 }
4136
Lorenzo Colitti95439462014-10-09 13:44:48 +09004137 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4138 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4139 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004140
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004141 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004142 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4143 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004144 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004145 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004146 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004147 }
Paul Jensen992f2522014-04-28 10:33:11 -04004148
4149 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4150 CompareResult<String> interfaceDiff = new CompareResult<String>();
4151 if (oldLp != null) {
4152 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4153 } else if (newLp != null) {
4154 interfaceDiff.added = newLp.getAllInterfaceNames();
4155 }
4156 for (String iface : interfaceDiff.added) {
4157 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004158 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004159 mNetd.addInterfaceToNetwork(iface, netId);
4160 } catch (Exception e) {
4161 loge("Exception adding interface: " + e);
4162 }
4163 }
4164 for (String iface : interfaceDiff.removed) {
4165 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004166 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004167 mNetd.removeInterfaceFromNetwork(iface, netId);
4168 } catch (Exception e) {
4169 loge("Exception removing interface: " + e);
4170 }
4171 }
4172 }
4173
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004174 /**
4175 * Have netd update routes from oldLp to newLp.
4176 * @return true if routes changed between oldLp and newLp
4177 */
4178 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004179 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4180 if (oldLp != null) {
4181 routeDiff = oldLp.compareAllRoutes(newLp);
4182 } else if (newLp != null) {
4183 routeDiff.added = newLp.getAllRoutes();
4184 }
4185
4186 // add routes before removing old in case it helps with continuous connectivity
4187
4188 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4189 for (RouteInfo route : routeDiff.added) {
4190 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004191 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004192 try {
4193 mNetd.addRoute(netId, route);
4194 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004195 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4196 loge("Exception in addRoute for non-gateway: " + e);
4197 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004198 }
4199 }
4200 for (RouteInfo route : routeDiff.added) {
4201 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004202 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004203 try {
4204 mNetd.addRoute(netId, route);
4205 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004206 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4207 loge("Exception in addRoute for gateway: " + e);
4208 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004209 }
4210 }
4211
4212 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004213 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004214 try {
4215 mNetd.removeRoute(netId, route);
4216 } catch (Exception e) {
4217 loge("Exception in removeRoute: " + e);
4218 }
4219 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004220 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004221 }
Erik Kline41368502015-06-17 13:19:54 +09004222
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004223 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
4224 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004225 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Klineb36a3132015-06-26 19:21:34 +09004226 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004227 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004228 dnses = new ArrayList();
4229 dnses.add(mDefaultDns);
4230 if (DBG) {
4231 loge("no dns provided for netId " + netId + ", so using defaults");
4232 }
4233 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004234 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004235 try {
4236 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4237 newLp.getDomains());
4238 } catch (Exception e) {
4239 loge("Exception in setDnsServersForNetwork: " + e);
4240 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04004241 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004242 if (defaultNai != null && defaultNai.network.netId == netId) {
4243 setDefaultDnsSystemProperties(dnses);
4244 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07004245 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004246 } else if (flush) {
4247 try {
4248 mNetd.flushNetworkDnsCache(netId);
4249 } catch (Exception e) {
4250 loge("Exception in flushNetworkDnsCache: " + e);
4251 }
4252 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004253 }
4254 }
4255
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004256 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4257 int last = 0;
4258 for (InetAddress dns : dnses) {
4259 ++last;
4260 String key = "net.dns" + last;
4261 String value = dns.getHostAddress();
4262 SystemProperties.set(key, value);
4263 }
4264 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4265 String key = "net.dns" + i;
4266 SystemProperties.set(key, "");
4267 }
4268 mNumDnsEntries = last;
4269 }
4270
Paul Jensen3d194ea2015-06-16 14:27:36 -04004271 /**
4272 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4273 * augmented with any stateful capabilities implied from {@code networkAgent}
4274 * (e.g., validated status and captive portal status).
4275 *
Paul Jensene0988542015-06-25 15:30:08 -04004276 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004277 * @param networkCapabilities the new network capabilities.
4278 */
Paul Jensene0988542015-06-25 15:30:08 -04004279 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004280 // Don't modify caller's NetworkCapabilities.
4281 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004282 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004283 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4284 } else {
4285 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4286 }
Paul Jensene0988542015-06-25 15:30:08 -04004287 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004288 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4289 } else {
4290 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4291 }
Paul Jensene0988542015-06-25 15:30:08 -04004292 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4293 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004294 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4295 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4296 try {
4297 mNetd.setNetworkPermission(nai.network.netId,
4298 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4299 null : NetworkManagementService.PERMISSION_SYSTEM);
4300 } catch (RemoteException e) {
4301 loge("Exception in setNetworkPermission: " + e);
4302 }
4303 }
Paul Jensene0988542015-06-25 15:30:08 -04004304 synchronized (nai) {
4305 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004306 }
Paul Jensene0988542015-06-25 15:30:08 -04004307 rematchAllNetworksAndRequests(nai, oldScore);
4308 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004309 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004310 }
4311
Paul Jensenc8b9a742014-09-30 15:37:41 -04004312 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4313 for (int i = 0; i < nai.networkRequests.size(); i++) {
4314 NetworkRequest nr = nai.networkRequests.valueAt(i);
4315 // Don't send listening requests to factories. b/17393458
4316 if (!isRequest(nr)) continue;
4317 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4318 }
4319 }
4320
Robert Greenwalt7b816022014-04-18 15:25:25 -07004321 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4322 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004323 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004324 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4325 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004326 }
4327 }
4328
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004329 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4330 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004331 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004332 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004333 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4334 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004335 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004336 sendIntent(nri.mPendingIntent, intent);
4337 }
4338 // else not handled
4339 }
4340
4341 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4342 mPendingIntentWakeLock.acquire();
4343 try {
4344 if (DBG) log("Sending " + pendingIntent);
4345 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4346 } catch (PendingIntent.CanceledException e) {
4347 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4348 mPendingIntentWakeLock.release();
4349 releasePendingNetworkRequest(pendingIntent);
4350 }
4351 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4352 }
4353
4354 @Override
4355 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4356 String resultData, Bundle resultExtras) {
4357 if (DBG) log("Finished sending " + pendingIntent);
4358 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004359 // Release with a delay so the receiving client has an opportunity to put in its
4360 // own request.
4361 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004362 }
4363
Robert Greenwalt9258c642014-03-26 16:47:06 -07004364 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004365 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004366 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004367 Bundle bundle = new Bundle();
4368 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4369 new NetworkRequest(nri.request));
4370 Message msg = Message.obtain();
4371 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4372 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4373 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4374 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004375 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004376 case ConnectivityManager.CALLBACK_LOSING: {
4377 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4378 break;
4379 }
4380 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4381 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4382 new NetworkCapabilities(networkAgent.networkCapabilities));
4383 break;
4384 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004385 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004386 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4387 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004388 break;
4389 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004390 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004391 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004392 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004393 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004394 if (VDBG) {
4395 log("sending notification " + notifyTypeToName(notificationType) +
4396 " for " + nri.request);
4397 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004398 nri.messenger.send(msg);
4399 } catch (RemoteException e) {
4400 // may occur naturally in the race of binder death.
4401 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4402 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004403 }
4404
Paul Jensenc8b9a742014-09-30 15:37:41 -04004405 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4406 for (int i = 0; i < nai.networkRequests.size(); i++) {
4407 NetworkRequest nr = nai.networkRequests.valueAt(i);
4408 // Ignore listening requests.
4409 if (!isRequest(nr)) continue;
4410 loge("Dead network still had at least " + nr);
4411 break;
4412 }
4413 nai.asyncChannel.disconnect();
4414 }
4415
Robert Greenwalt7b816022014-04-18 15:25:25 -07004416 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4417 if (oldNetwork == null) {
4418 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4419 return;
4420 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004421 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4422 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004423 }
4424
Paul Jensen27b02b72014-07-14 12:03:33 -04004425 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004426 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004427 setupDataActivityTracking(newNetwork);
4428 try {
4429 mNetd.setDefaultNetId(newNetwork.network.netId);
4430 } catch (Exception e) {
4431 loge("Exception setting default network :" + e);
4432 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004433 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004434 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004435 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004436 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004437 }
4438
Paul Jensen2161a8e2014-09-11 11:00:39 -04004439 // Handles a network appearing or improving its score.
4440 //
4441 // - Evaluates all current NetworkRequests that can be
4442 // satisfied by newNetwork, and reassigns to newNetwork
4443 // any such requests for which newNetwork is the best.
4444 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004445 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004446 // needed. A network is needed if it is the best network for
4447 // one or more NetworkRequests, or if it is a VPN.
4448 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004449 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004450 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004451 //
4452 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4453 // networks that have no chance (i.e. even if validated)
4454 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004455 //
4456 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4457 // it does not remove NetworkRequests that other Networks could better satisfy.
4458 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4459 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4460 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004461 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004462 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004463 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4464 // performed to tear down unvalidated networks that have no chance (i.e. even if
4465 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004466 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004467 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004468 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004469 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004470 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004471 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004472 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004473 // Find and migrate to this Network any NetworkRequests for
4474 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004475 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004476 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004477 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004478 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004479 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4480 final boolean satisfies = newNetwork.satisfies(nri.request);
4481 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004482 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004483 log("Network " + newNetwork.name() + " was already satisfying" +
4484 " request " + nri.request.requestId + ". No change.");
4485 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004486 keep = true;
4487 continue;
4488 }
4489
4490 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004491 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004492 if (satisfies) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004493 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004494 // This is not a request, it's a callback listener.
4495 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004496 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004497 continue;
4498 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004499
Robert Greenwalt7b816022014-04-18 15:25:25 -07004500 // next check if it's better than any current network we're using for
4501 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004502 if (VDBG) {
4503 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004504 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4505 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004506 }
4507 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004508 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004509 if (DBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004510 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004511 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004512 currentNetwork.networkRequests.remove(nri.request.requestId);
4513 currentNetwork.networkLingered.add(nri.request);
4514 affectedNetworks.add(currentNetwork);
4515 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004516 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004517 }
Paul Jensen573a0352015-01-08 10:49:34 -05004518 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004519 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004520 if (!newNetwork.addRequest(nri.request)) {
4521 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4522 }
4523 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004524 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004525 // Tell NetworkFactories about the new score, so they can stop
4526 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004527 // TODO - this could get expensive if we have alot of requests for this
4528 // network. Think about if there is a way to reduce this. Push
4529 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004530 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004531 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004532 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004533 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004534 }
4535 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004536 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4537 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4538 // mark it as no longer satisfying "nri". Because networks are processed by
4539 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4540 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4541 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4542 // This means this code doesn't have to handle the case where "currentNetwork" no
4543 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4544 if (DBG) {
4545 log("Network " + newNetwork.name() + " stopped satisfying" +
4546 " request " + nri.request.requestId);
4547 }
4548 newNetwork.networkRequests.remove(nri.request.requestId);
4549 if (currentNetwork == newNetwork) {
4550 mNetworkForRequestId.remove(nri.request.requestId);
4551 sendUpdatedScoreToFactories(nri.request, 0);
4552 } else {
4553 if (nri.isRequest == true) {
4554 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4555 newNetwork.name() +
4556 " without updating mNetworkForRequestId or factories!");
4557 }
4558 }
4559 // TODO: technically, sending CALLBACK_LOST here is
4560 // incorrect if nri is a request (not a listen) and there
4561 // is a replacement network currently connected that can
4562 // satisfy it. However, the only capability that can both
4563 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4564 // so this code is only incorrect for a network that loses
4565 // the TRUSTED capability, which is a rare case.
4566 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004567 }
4568 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004569 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004570 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004571 if (nai.lingering) {
4572 // Already lingered. Nothing to do. This can only happen if "nai" is in
4573 // "affectedNetworks" twice. The reasoning being that to get added to
4574 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4575 // (i.e. not lingered) so it could have only been lingered by this loop.
4576 // unneeded(nai) will be false and we'll call unlinger() below which would
4577 // be bad, so handle it here.
4578 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004579 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004580 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004581 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004582 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004583 }
4584 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004585 if (isNewDefault) {
4586 // Notify system services that this network is up.
4587 makeDefault(newNetwork);
4588 synchronized (ConnectivityService.this) {
4589 // have a new default network, release the transition wakelock in
4590 // a second if it's held. The second pause is to allow apps
4591 // to reconnect over the new network
4592 if (mNetTransitionWakeLock.isHeld()) {
4593 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4594 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4595 mNetTransitionWakeLockSerialNumber, 0),
4596 1000);
4597 }
4598 }
4599 }
4600
4601 // do this after the default net is switched, but
4602 // before LegacyTypeTracker sends legacy broadcasts
4603 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4604
4605 if (isNewDefault) {
4606 // Maintain the illusion: since the legacy API only
4607 // understands one network at a time, we must pretend
4608 // that the current default network disconnected before
4609 // the new one connected.
4610 if (oldDefaultNetwork != null) {
4611 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4612 oldDefaultNetwork, true);
4613 }
4614 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4615 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4616 notifyLockdownVpn(newNetwork);
4617 }
4618
Robert Greenwalt7b816022014-04-18 15:25:25 -07004619 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004620 // Notify battery stats service about this network, both the normal
4621 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004622 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004623 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004624 final IBatteryStats bs = BatteryStatsService.getService();
4625 final int type = newNetwork.networkInfo.getType();
4626
4627 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4628 bs.noteNetworkInterfaceType(baseIface, type);
4629 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4630 final String stackedIface = stacked.getInterfaceName();
4631 bs.noteNetworkInterfaceType(stackedIface, type);
4632 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4633 }
4634 } catch (RemoteException ignored) {
4635 }
4636
Robert Greenwalt152ed372014-12-17 17:19:53 -08004637 // This has to happen after the notifyNetworkCallbacks as that tickles each
4638 // ConnectivityManager instance so that legacy requests correctly bind dns
4639 // requests to this network. The legacy users are listening for this bcast
4640 // and will generally do a dns request so they can ensureRouteToHost and if
4641 // they do that before the callbacks happen they'll use the default network.
4642 //
4643 // TODO: Is there still a race here? We send the broadcast
4644 // after sending the callback, but if the app can receive the
4645 // broadcast before the callback, it might still break.
4646 //
4647 // This *does* introduce a race where if the user uses the new api
4648 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4649 // they may get old info. Reverse this after the old startUsing api is removed.
4650 // This is on top of the multiple intent sequencing referenced in the todo above.
4651 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4652 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4653 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4654 // legacy type tracker filters out repeat adds
4655 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4656 }
4657 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004658
4659 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4660 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4661 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4662 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4663 if (newNetwork.isVPN()) {
4664 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4665 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004666 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004667 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4668 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004669 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004670 if (DBG) log("Reaping " + nai.name());
4671 teardownUnneededNetwork(nai);
4672 }
4673 }
4674 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004675 }
4676
Paul Jensen1c7ba022015-06-16 14:27:36 -04004677 /**
4678 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4679 * being disconnected.
4680 * @param changed If only one Network's score or capabilities have been modified since the last
4681 * time this function was called, pass this Network in this argument, otherwise pass
4682 * null.
4683 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4684 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4685 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4686 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4687 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004688 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004689 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004690 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4691 // to avoid the slowness. It is not simply enough to process just "changed", for
4692 // example in the case where "changed"'s score decreases and another network should begin
4693 // satifying a NetworkRequest that "changed" currently satisfies.
4694
4695 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4696 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4697 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004698 if (changed != null && oldScore < changed.getCurrentScore()) {
4699 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004700 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004701 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4702 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4703 // Rematch higher scoring networks first to prevent requests first matching a lower
4704 // scoring network and then a higher scoring network, which could produce multiple
4705 // callbacks and inadvertently unlinger networks.
4706 Arrays.sort(nais);
4707 for (NetworkAgentInfo nai : nais) {
4708 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004709 // Only reap the last time through the loop. Reaping before all rematching
4710 // is complete could incorrectly teardown a network that hasn't yet been
4711 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004712 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004713 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004714 }
4715 }
4716 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004717
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004718 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004719 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004720 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004721 // For now only update icons for default connection.
4722 // TODO: Update WiFi and cellular icons separately. b/17237507
4723 if (!isDefaultNetwork(nai)) return;
4724
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004725 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004726 // Don't repeat publish.
4727 if (newInetCondition == mDefaultInetConditionPublished) return;
4728
4729 mDefaultInetConditionPublished = newInetCondition;
4730 sendInetConditionBroadcast(nai.networkInfo);
4731 }
4732
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004733 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4734 if (mLockdownTracker != null) {
4735 if (nai != null && nai.isVPN()) {
4736 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4737 } else {
4738 mLockdownTracker.onNetworkInfoChanged();
4739 }
4740 }
4741 }
4742
Robert Greenwalt7b816022014-04-18 15:25:25 -07004743 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4744 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004745 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004746 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004747 synchronized (networkAgent) {
4748 oldInfo = networkAgent.networkInfo;
4749 networkAgent.networkInfo = newInfo;
4750 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004751 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004752
4753 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004754 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4755 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4756 notifyIfacesChangedForNetworkStats();
4757 } else if (VDBG) log("ignoring duplicate network state non-change");
4758 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004759 return;
4760 }
4761 if (DBG) {
4762 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4763 (oldInfo == null ? "null" : oldInfo.getState()) +
4764 " to " + state);
4765 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004766
Paul Jenseneec75412014-08-04 12:21:19 -04004767 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004768 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004769 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004770 if (networkAgent.isVPN()) {
4771 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004772 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4773 (networkAgent.networkMisc == null ||
4774 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004775 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004776 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4777 networkAgent.networkCapabilities.hasCapability(
4778 NET_CAPABILITY_NOT_RESTRICTED) ?
4779 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004780 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004781 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004782 loge("Error creating network " + networkAgent.network.netId + ": "
4783 + e.getMessage());
4784 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004785 }
Paul Jenseneec75412014-08-04 12:21:19 -04004786 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004787 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004788 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004789
Paul Jensenca8f16a2014-05-09 12:47:55 -04004790 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004791 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004792
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004793 if (networkAgent.isVPN()) {
4794 // Temporarily disable the default proxy (not global).
4795 synchronized (mProxyLock) {
4796 if (!mDefaultProxyDisabled) {
4797 mDefaultProxyDisabled = true;
4798 if (mGlobalProxy == null && mDefaultProxy != null) {
4799 sendProxyBroadcast(null);
4800 }
4801 }
4802 }
4803 // TODO: support proxy per network.
4804 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004805
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004806 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4807 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4808 // capabilities, so it only needs to be done once on initial connect, not every time the
4809 // network's capabilities change. Note that we do this before rematching the network,
4810 // so we could decide to tear it down immediately afterwards. That's fine though - on
4811 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4812 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004813 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004814
Paul Jensen2161a8e2014-09-11 11:00:39 -04004815 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004816 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004817
4818 // This has to happen after matching the requests, because callbacks are just requests.
4819 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004820 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004821 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004822 if (networkAgent.isVPN()) {
4823 synchronized (mProxyLock) {
4824 if (mDefaultProxyDisabled) {
4825 mDefaultProxyDisabled = false;
4826 if (mGlobalProxy == null && mDefaultProxy != null) {
4827 sendProxyBroadcast(mDefaultProxy);
4828 }
4829 }
4830 }
4831 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004832 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4833 state == NetworkInfo.State.SUSPENDED) {
4834 // going into or coming out of SUSPEND: rescore and notify
4835 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004836 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004837 }
4838 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4839 ConnectivityManager.CALLBACK_SUSPENDED :
4840 ConnectivityManager.CALLBACK_RESUMED));
4841 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004842 }
4843 }
4844
Robert Greenwaltac96c522014-06-03 16:43:57 -07004845 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4846 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004847 if (score < 0) {
4848 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4849 "). Bumping score to min of 0");
4850 score = 0;
4851 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004852
Paul Jensen2161a8e2014-09-11 11:00:39 -04004853 final int oldScore = nai.getCurrentScore();
4854 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004855
Paul Jensen85cf78e2015-06-25 13:25:07 -04004856 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004857
Paul Jensenc8b9a742014-09-30 15:37:41 -04004858 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004859 }
4860
Robert Greenwalt9258c642014-03-26 16:47:06 -07004861 // notify only this one new request of the current state
4862 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4863 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4864 // TODO - read state from monitor to decide what to send.
4865// if (nai.networkMonitor.isLingering()) {
4866// notifyType = NetworkCallbacks.LOSING;
4867// } else if (nai.networkMonitor.isEvaluating()) {
4868// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4869// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004870 if (nri.mPendingIntent == null) {
4871 callCallbackForRequest(nri, nai, notifyType);
4872 } else {
4873 sendPendingIntentForRequest(nri, nai, notifyType);
4874 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004875 }
4876
Robert Greenwalt8d482522015-06-24 13:23:42 -07004877 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004878 // The NetworkInfo we actually send out has no bearing on the real
4879 // state of affairs. For example, if the default connection is mobile,
4880 // and a request for HIPRI has just gone away, we need to pretend that
4881 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4882 // the state to DISCONNECTED, even though the network is of type MOBILE
4883 // and is still connected.
4884 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4885 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004886 if (state != DetailedState.DISCONNECTED) {
4887 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004888 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004889 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004890 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004891 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4892 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4893 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4894 if (info.isFailover()) {
4895 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4896 nai.networkInfo.setFailover(false);
4897 }
4898 if (info.getReason() != null) {
4899 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4900 }
4901 if (info.getExtraInfo() != null) {
4902 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4903 }
4904 NetworkAgentInfo newDefaultAgent = null;
4905 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004906 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004907 if (newDefaultAgent != null) {
4908 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4909 newDefaultAgent.networkInfo);
4910 } else {
4911 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4912 }
4913 }
4914 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4915 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004916 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004917 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004918 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004919 }
4920 }
4921 }
4922
Robert Greenwalt7b816022014-04-18 15:25:25 -07004923 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004924 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004925 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004926 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4927 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4928 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004929 if (nri.mPendingIntent == null) {
4930 callCallbackForRequest(nri, networkAgent, notifyType);
4931 } else {
4932 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4933 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004934 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004935 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004936
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004937 private String notifyTypeToName(int notifyType) {
4938 switch (notifyType) {
4939 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4940 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4941 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4942 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4943 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4944 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4945 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4946 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4947 }
4948 return "UNKNOWN";
4949 }
4950
Jeff Sharkey69736342014-12-08 14:50:12 -08004951 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004952 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
4953 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08004954 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004955 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08004956 try {
4957 mStatsService.forceUpdateIfaces();
4958 } catch (Exception ignored) {
4959 }
4960 }
4961
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004962 @Override
4963 public boolean addVpnAddress(String address, int prefixLength) {
4964 throwIfLockdownEnabled();
4965 int user = UserHandle.getUserId(Binder.getCallingUid());
4966 synchronized (mVpns) {
4967 return mVpns.get(user).addAddress(address, prefixLength);
4968 }
4969 }
4970
4971 @Override
4972 public boolean removeVpnAddress(String address, int prefixLength) {
4973 throwIfLockdownEnabled();
4974 int user = UserHandle.getUserId(Binder.getCallingUid());
4975 synchronized (mVpns) {
4976 return mVpns.get(user).removeAddress(address, prefixLength);
4977 }
4978 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004979
4980 @Override
4981 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4982 throwIfLockdownEnabled();
4983 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004984 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004985 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004986 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004987 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004988 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004989 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004990 }
4991 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004992 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004993
4994 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08004995 public String getCaptivePortalServerUrl() {
4996 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
4997 }
4998
4999 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005000 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5001 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5002 enforceKeepalivePermission();
5003 mKeepaliveTracker.startNattKeepalive(
5004 getNetworkAgentInfoForNetwork(network),
5005 intervalSeconds, messenger, binder,
5006 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5007 }
5008
5009 @Override
5010 public void stopKeepalive(Network network, int slot) {
5011 mHandler.sendMessage(mHandler.obtainMessage(
5012 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5013 }
5014
5015 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005016 public void factoryReset() {
5017 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005018
5019 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5020 return;
5021 }
5022
Robin Lee3b3dd942015-05-12 18:14:58 +01005023 final int userId = UserHandle.getCallingUserId();
5024
Stuart Scottf1fb3972015-04-02 18:00:02 -07005025 // Turn airplane mode off
5026 setAirplaneMode(false);
5027
Stuart Scotte3e314d2015-04-20 14:07:45 -07005028 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5029 // Untether
5030 for (String tether : getTetheredIfaces()) {
5031 untether(tether);
5032 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005033 }
5034
Stuart Scotte3e314d2015-04-20 14:07:45 -07005035 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
5036 // Turn VPN off
5037 VpnConfig vpnConfig = getVpnConfig(userId);
5038 if (vpnConfig != null) {
5039 if (vpnConfig.legacy) {
5040 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5041 } else {
5042 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5043 // in the future without user intervention.
5044 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005045
Stuart Scotte3e314d2015-04-20 14:07:45 -07005046 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
5047 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005048 }
5049 }
5050 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005051
5052 @VisibleForTesting
5053 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5054 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5055 return new NetworkMonitor(context, handler, nai, defaultRequest);
5056 }
5057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005058}