blob: 5b01062a35c32ae55fa6eb8995e51e4362ea3276 [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
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001787 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1788 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1789 final long DIAG_TIME_MS = 5000;
1790 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1791 // Start gathering diagnostic information.
1792 netDiags.add(new NetworkDiagnostics(
1793 nai.network,
1794 new LinkProperties(nai.linkProperties), // Must be a copy.
1795 DIAG_TIME_MS));
1796 }
1797
1798 for (NetworkDiagnostics netDiag : netDiags) {
1799 pw.println();
1800 netDiag.waitForMeasurements();
1801 netDiag.dump(pw);
1802 }
1803 }
1804
1805 private void dumpApf(IndentingPrintWriter pw) {
1806 pw.println("APF filters:");
1807 pw.increaseIndent();
1808 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1809 if (nai.apfFilter != null) {
1810 pw.println(nai.name() + ":");
1811 pw.increaseIndent();
1812 nai.apfFilter.dump(pw);
1813 pw.decreaseIndent();
1814 }
1815 }
1816 pw.decreaseIndent();
1817 }
1818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001820 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1821 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001822 if (mContext.checkCallingOrSelfPermission(
1823 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001825 pw.println("Permission Denial: can't dump ConnectivityService " +
1826 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1827 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 return;
1829 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001830
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001831 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001832 dumpNetworkDiagnostics(pw);
1833 return;
1834 }
Erik Kline379747a2015-06-05 17:47:34 +09001835
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001836 if (argsContain(args, "apf")) {
1837 dumpApf(pw);
Erik Kline379747a2015-06-05 17:47:34 +09001838 return;
1839 }
1840
Lorenzo Colittie3805462015-06-03 11:18:24 +09001841 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001842 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001843 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001844 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001845 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001846 pw.println();
1847
Paul Jensen85cf78e2015-06-25 13:25:07 -04001848 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001849 pw.print("Active default network: ");
1850 if (defaultNai == null) {
1851 pw.println("none");
1852 } else {
1853 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001855 pw.println();
1856
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001857 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001858 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001859 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1860 pw.println(nai.toString());
1861 pw.increaseIndent();
1862 pw.println("Requests:");
1863 pw.increaseIndent();
1864 for (int i = 0; i < nai.networkRequests.size(); i++) {
1865 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001866 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001867 pw.decreaseIndent();
1868 pw.println("Lingered:");
1869 pw.increaseIndent();
1870 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1871 pw.decreaseIndent();
1872 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001873 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001874 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001875 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001876
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001877 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001878 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001879 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1880 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001881 }
1882 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001883 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001884
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001885 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001886
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001887 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001888 pw.print("mNetTransitionWakeLock: currently " +
1889 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1890 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1891 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1892 } else {
1893 pw.println(", last requested never");
1894 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001895 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001896
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001897 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001898 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001899
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001900 pw.println();
1901 mKeepaliveTracker.dump(pw);
1902
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001903 pw.println();
1904 dumpApf(pw);
1905
Lorenzo Colittie3805462015-06-03 11:18:24 +09001906 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001907 pw.println();
1908 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001909 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001910 for(int i = 0; i < mInetLog.size(); i++) {
1911 pw.println(mInetLog.get(i));
1912 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001913 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001914 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001915
1916 if (argsContain(args, "--short") == false) {
1917 pw.println();
1918 synchronized (mValidationLogs) {
1919 pw.println("mValidationLogs (most recent first):");
1920 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1921 pw.println(p.first);
1922 pw.increaseIndent();
1923 p.second.dump(fd, pw, args);
1924 pw.decreaseIndent();
1925 }
1926 }
Erik Kline7523eb32015-07-09 18:24:03 +09001927
1928 pw.println();
1929 pw.println("mNetworkRequestInfoLogs (most recent first):");
1930 pw.increaseIndent();
1931 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1932 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 }
1935
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001936 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001937 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001938 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001939 if (officialNai != null && officialNai.equals(nai)) return true;
1940 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001941 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001942 " - " + nai);
1943 }
1944 return false;
1945 }
1946
Paul Jensenc8b9a742014-09-30 15:37:41 -04001947 private boolean isRequest(NetworkRequest request) {
1948 return mNetworkRequests.get(request).isRequest;
1949 }
1950
Robert Greenwalt42acef32009-08-12 16:08:25 -07001951 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001952 private class NetworkStateTrackerHandler extends Handler {
1953 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001954 super(looper);
1955 }
1956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 @Override
1958 public void handleMessage(Message msg) {
1959 NetworkInfo info;
1960 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001961 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001962 handleAsyncChannelHalfConnect(msg);
1963 break;
1964 }
1965 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1966 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1967 if (nai != null) nai.asyncChannel.disconnect();
1968 break;
1969 }
1970 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1971 handleAsyncChannelDisconnected(msg);
1972 break;
1973 }
1974 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1975 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1976 if (nai == null) {
1977 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1978 } else {
Paul Jensen1c7ba022015-06-16 14:27:36 -04001979 final NetworkCapabilities networkCapabilities =
1980 (NetworkCapabilities)msg.obj;
1981 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1982 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001983 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Paul Jensen1c7ba022015-06-16 14:27:36 -04001984 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09001985 if (nai.created && !nai.networkCapabilities.equalImmutableCapabilities(
1986 networkCapabilities)) {
1987 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
1988 + nai.networkCapabilities + " -> " + networkCapabilities);
1989 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04001990 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001991 }
1992 break;
1993 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001994 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1995 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1996 if (nai == null) {
1997 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1998 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001999 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002000 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04002001 "; created=" + nai.created);
2002 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002003 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002004 synchronized (nai) {
2005 nai.linkProperties = (LinkProperties)msg.obj;
2006 }
Paul Jenseneec75412014-08-04 12:21:19 -04002007 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002008 }
2009 break;
2010 }
2011 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
2012 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2013 if (nai == null) {
2014 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
2015 break;
2016 }
2017 info = (NetworkInfo) msg.obj;
2018 updateNetworkInfo(nai, info);
2019 break;
2020 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002021 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
2022 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2023 if (nai == null) {
2024 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
2025 break;
2026 }
2027 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002028 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002029 break;
2030 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002031 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
2032 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2033 if (nai == null) {
2034 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
2035 break;
2036 }
2037 try {
2038 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002039 } catch (Exception e) {
2040 // Never crash!
2041 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002042 }
2043 break;
2044 }
2045 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
2046 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2047 if (nai == null) {
2048 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
2049 break;
2050 }
2051 try {
2052 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002053 } catch (Exception e) {
2054 // Never crash!
2055 loge("Exception in removeVpnUidRanges: " + e);
2056 }
2057 break;
2058 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002059 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
2060 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2061 if (nai == null) {
2062 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
2063 break;
2064 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002065 if (nai.created && !nai.networkMisc.explicitlySelected) {
2066 loge("ERROR: created network explicitly selected.");
2067 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002068 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002069 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002070 break;
2071 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002072 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
2073 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2074 if (nai == null) {
2075 loge("EVENT_PACKET_KEEPALIVE from unknown NetworkAgent");
2076 break;
2077 }
2078 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2079 break;
2080 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04002081 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002082 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002083 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
2084 final boolean valid =
2085 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002086 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
2087 if (valid != nai.lastValidated) {
2088 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002089 nai.lastValidated = valid;
2090 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002091 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002092 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2093 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002094 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002095 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002096 // Let the NetworkAgent know the state of its network
2097 nai.asyncChannel.sendMessage(
2098 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2099 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2100 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002101 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002102 break;
2103 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002104 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002105 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002106 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2107 handleLingerComplete(nai);
2108 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002109 break;
2110 }
Paul Jensen869868be2014-05-15 10:33:05 -04002111 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002112 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002113 final boolean visible = (msg.arg1 != 0);
2114 final NetworkAgentInfo nai;
2115 synchronized (mNetworkForNetId) {
2116 nai = mNetworkForNetId.get(netId);
2117 }
2118 // If captive portal status has changed, update capabilities.
2119 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2120 nai.lastCaptivePortalDetected = visible;
2121 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002122 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002123 }
2124 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002125 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002126 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002127 if (nai == null) {
2128 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2129 break;
2130 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002131 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002132 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2133 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002134 }
Paul Jensen869868be2014-05-15 10:33:05 -04002135 break;
2136 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002137 }
2138 }
2139 }
2140
Paul Jensen85cf78e2015-06-25 13:25:07 -04002141 private void linger(NetworkAgentInfo nai) {
2142 nai.lingering = true;
2143 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2144 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2145 }
2146
Paul Jensen0cc17322014-11-25 15:26:53 -05002147 // Cancel any lingering so the linger timeout doesn't teardown a network.
2148 // This should be called when a network begins satisfying a NetworkRequest.
2149 // Note: depending on what state the NetworkMonitor is in (e.g.,
2150 // if it's awaiting captive portal login, or if validation failed), this
2151 // may trigger a re-evaluation of the network.
2152 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002153 nai.networkLingered.clear();
2154 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002155 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002156 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002157 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2158 }
2159
Robert Greenwalt7b816022014-04-18 15:25:25 -07002160 private void handleAsyncChannelHalfConnect(Message msg) {
2161 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002162 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002163 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2164 if (VDBG) log("NetworkFactory connected");
2165 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002166 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002167 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002168 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002169 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002170 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002171 }
2172 } else {
2173 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002174 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002175 }
2176 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2177 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2178 if (VDBG) log("NetworkAgent connected");
2179 // A network agent has requested a connection. Establish the connection.
2180 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2181 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2182 } else {
2183 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002184 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002185 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002186 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002187 synchronized (mNetworkForNetId) {
2188 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002189 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002190 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002191 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002192 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002193 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002194 }
2195 }
2196 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002197
Robert Greenwalt7b816022014-04-18 15:25:25 -07002198 private void handleAsyncChannelDisconnected(Message msg) {
2199 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2200 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002201 if (DBG) {
2202 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2203 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002204 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002205 // TODO - if we move the logic to the network agent (have them disconnect
2206 // because they lost all their requests or because their score isn't good)
2207 // then they would disconnect organically, report their new state and then
2208 // disconnect the channel.
2209 if (nai.networkInfo.isConnected()) {
2210 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2211 null, null);
2212 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002213 final boolean wasDefault = isDefaultNetwork(nai);
2214 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002215 mDefaultInetConditionPublished = 0;
2216 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002217 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002218 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2219 // by other networks that are already connected. Perhaps that can be done by
2220 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2221 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002222 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002223 mKeepaliveTracker.handleStopAllKeepalives(nai,
2224 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002225 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen578a76e2016-01-14 14:54:39 -05002226 if (nai.apfFilter != null) nai.apfFilter.shutdown();
Paul Jensen3b759822014-05-13 11:44:01 -04002227 mNetworkAgentInfos.remove(msg.replyTo);
2228 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002229 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002230 // Remove the NetworkAgent, but don't mark the netId as
2231 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002232 mNetworkForNetId.remove(nai.network.netId);
2233 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002234 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002235 for (int i = 0; i < nai.networkRequests.size(); i++) {
2236 NetworkRequest request = nai.networkRequests.valueAt(i);
2237 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2238 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2239 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002240 sendUpdatedScoreToFactories(request, 0);
2241 }
2242 }
2243 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2244 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002245 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002246 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002247 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002248 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002249 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002250 if (nai.created) {
2251 // Tell netd to clean up the configuration for this network
2252 // (routing rules, DNS, etc).
2253 // This may be slow as it requires a lot of netd shelling out to ip and
2254 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2255 // after we've rematched networks with requests which should make a potential
2256 // fallback network the default or requested a new network from the
2257 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2258 // long time.
2259 try {
2260 mNetd.removeNetwork(nai.network.netId);
2261 } catch (Exception e) {
2262 loge("Exception removing network: " + e);
2263 }
2264 }
2265 synchronized (mNetworkForNetId) {
2266 mNetIdInUse.delete(nai.network.netId);
2267 }
2268 } else {
2269 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2270 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002271 }
2272 }
2273
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002274 // If this method proves to be too slow then we can maintain a separate
2275 // pendingIntent => NetworkRequestInfo map.
2276 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2277 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2278 Intent intent = pendingIntent.getIntent();
2279 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2280 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2281 if (existingPendingIntent != null &&
2282 existingPendingIntent.getIntent().filterEquals(intent)) {
2283 return entry.getValue();
2284 }
2285 }
2286 return null;
2287 }
2288
2289 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2290 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2291
2292 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2293 if (existingRequest != null) { // remove the existing request.
2294 if (DBG) log("Replacing " + existingRequest.request + " with "
2295 + nri.request + " because their intents matched.");
2296 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2297 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002298 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002299 }
2300
Erik Klineda4bfa82015-04-30 12:58:40 +09002301 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002302 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002303 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002304 if (!nri.isRequest) {
2305 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002306 if (nri.request.networkCapabilities.hasSignalStrength() &&
2307 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2308 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002309 }
2310 }
2311 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002312 rematchAllNetworksAndRequests(null, 0);
2313 if (nri.isRequest && mNetworkForRequestId.get(nri.request.requestId) == null) {
2314 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002315 }
2316 }
2317
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002318 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2319 int callingUid) {
2320 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2321 if (nri != null) {
2322 handleReleaseNetworkRequest(nri.request, callingUid);
2323 }
2324 }
2325
Paul Jensen99364842014-12-09 11:43:45 -05002326 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002327 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2328 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002329 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002330 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002331 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2332 // If this Network is already the highest scoring Network for a request, or if
2333 // there is hope for it to become one if it validated, then it is needed.
2334 if (nri.isRequest && nai.satisfies(nri.request) &&
2335 (nai.networkRequests.get(nri.request.requestId) != null ||
2336 // Note that this catches two important cases:
2337 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2338 // is currently satisfying the request. This is desirable when
2339 // cellular ends up validating but WiFi does not.
2340 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002341 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002342 // WiFi ends up validating and out scoring cellular.
2343 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2344 nai.getCurrentScoreAsValidated())) {
2345 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002346 }
2347 }
Paul Jensene0988542015-06-25 15:30:08 -04002348 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002349 }
2350
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002351 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2352 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002353 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002354 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002355 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2356 return;
2357 }
2358 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002359 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002360 mNetworkRequests.remove(request);
Erik Kline7523eb32015-07-09 18:24:03 +09002361 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002362 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002363 // Find all networks that are satisfying this request and remove the request
2364 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002365 // TODO - it's my understanding that for a request there is only a single
2366 // network satisfying it, so this loop is wasteful
2367 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002368 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2369 if (nai.networkRequests.get(nri.request.requestId) != null) {
2370 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002371 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002372 log(" Removing from current network " + nai.name() +
2373 ", leaving " + nai.networkRequests.size() +
2374 " requests.");
2375 }
Paul Jensen99364842014-12-09 11:43:45 -05002376 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002377 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002378 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002379 } else {
2380 // suspect there should only be one pass through here
2381 // but if any were kept do the check below
2382 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002383 }
2384 }
2385 }
2386
Robert Greenwalt51481852015-01-08 14:43:31 -08002387 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2388 if (nai != null) {
2389 mNetworkForRequestId.remove(nri.request.requestId);
2390 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002391 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002392 // that a network connected to serve it, even though the network was already
2393 // connected. Now that this request has gone away, we might have to pretend
2394 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002395 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002396 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2397 boolean doRemove = true;
2398 if (wasKept) {
2399 // check if any of the remaining requests for this network are for the
2400 // same legacy type - if so, don't remove the nai
2401 for (int i = 0; i < nai.networkRequests.size(); i++) {
2402 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2403 if (otherRequest.legacyType == nri.request.legacyType &&
2404 isRequest(otherRequest)) {
2405 if (DBG) log(" still have other legacy request - leaving");
2406 doRemove = false;
2407 }
2408 }
2409 }
2410
2411 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002412 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002413 }
2414 }
2415
Robert Greenwalta67be032014-05-16 15:49:14 -07002416 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002417 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2418 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002419 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002420 } else {
2421 // listens don't have a singular affectedNetwork. Check all networks to see
2422 // if this listen request applies and remove it.
2423 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2424 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002425 if (nri.request.networkCapabilities.hasSignalStrength() &&
2426 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2427 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002428 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002429 }
2430 }
2431 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2432 }
2433 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002434
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002435 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2436 enforceConnectivityInternalPermission();
2437 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2438 accept ? 1 : 0, always ? 1: 0, network));
2439 }
2440
Paul Jensen578a76e2016-01-14 14:54:39 -05002441 public void pushApfProgramToNetwork(NetworkAgentInfo nai, byte[] program) {
2442 enforceConnectivityInternalPermission();
2443 Message msg = mHandler.obtainMessage(EVENT_PUSH_APF_PROGRAM_TO_NETWORK, program);
2444 msg.replyTo = nai.messenger;
2445 mHandler.sendMessage(msg);
2446 }
2447
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002448 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2449 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2450 " accept=" + accept + " always=" + always);
2451
2452 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2453 if (nai == null) {
2454 // Nothing to do.
2455 return;
2456 }
2457
2458 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002459 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002460 return;
2461 }
2462
2463 if (!nai.networkMisc.explicitlySelected) {
2464 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2465 }
2466
2467 if (accept != nai.networkMisc.acceptUnvalidated) {
2468 int oldScore = nai.getCurrentScore();
2469 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002470 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002471 sendUpdatedScoreToFactories(nai);
2472 }
2473
2474 if (always) {
2475 nai.asyncChannel.sendMessage(
2476 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2477 }
2478
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002479 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002480 // Tell the NetworkAgent to not automatically reconnect to the network.
2481 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2482 // Teardown the nework.
2483 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002484 }
2485
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002486 }
2487
2488 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002489 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002490 mHandler.sendMessageDelayed(
2491 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2492 PROMPT_UNVALIDATED_DELAY_MS);
2493 }
2494
2495 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002496 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002497 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2498
2499 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2500 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002501 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002502 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002503 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2504 return;
2505 }
2506
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002507 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002508 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002509 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2510 intent.setClassName("com.android.settings",
2511 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002512
2513 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2514 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2515 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002516 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002517 }
2518
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002519 private class InternalHandler extends Handler {
2520 public InternalHandler(Looper looper) {
2521 super(looper);
2522 }
2523
2524 @Override
2525 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002526 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002527 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002528 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002529 String causedBy = null;
2530 synchronized (ConnectivityService.this) {
2531 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2532 mNetTransitionWakeLock.isHeld()) {
2533 mNetTransitionWakeLock.release();
2534 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002535 } else {
2536 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002537 }
2538 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002539 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2540 log("Failed to find a new network - expiring NetTransition Wakelock");
2541 } else {
2542 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2543 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002544 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002545 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002546 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002547 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002548 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002549 break;
2550 }
Jason Monkdecd2952013-10-10 14:02:51 -04002551 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002552 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002553 break;
2554 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002555 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002556 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2557 break;
2558 }
2559 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2560 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002561 break;
2562 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002563 case EVENT_REGISTER_NETWORK_AGENT: {
2564 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2565 break;
2566 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002567 case EVENT_REGISTER_NETWORK_REQUEST:
2568 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002569 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002570 break;
2571 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002572 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2573 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002574 handleRegisterNetworkRequestWithIntent(msg);
2575 break;
2576 }
2577 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2578 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2579 break;
2580 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002581 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002582 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002583 break;
2584 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002585 case EVENT_SET_ACCEPT_UNVALIDATED: {
2586 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2587 break;
2588 }
2589 case EVENT_PROMPT_UNVALIDATED: {
2590 handlePromptUnvalidated((Network) msg.obj);
2591 break;
2592 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002593 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2594 handleMobileDataAlwaysOn();
2595 break;
2596 }
Paul Jensen578a76e2016-01-14 14:54:39 -05002597 case EVENT_PUSH_APF_PROGRAM_TO_NETWORK: {
2598 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2599 if (nai == null) {
2600 loge("EVENT_PUSH_APF_PROGRAM_TO_NETWORK from unknown NetworkAgent");
2601 } else {
2602 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PUSH_APF_PROGRAM,
2603 (byte[]) msg.obj);
2604 }
2605 break;
2606 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002607 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2608 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2609 mKeepaliveTracker.handleStartKeepalive(msg);
2610 break;
2611 }
2612 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2613 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2614 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2615 int slot = msg.arg1;
2616 int reason = msg.arg2;
2617 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2618 break;
2619 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002620 case EVENT_SYSTEM_READY: {
2621 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2622 nai.networkMonitor.systemReady = true;
2623 }
2624 break;
2625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002626 }
2627 }
2628 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002629
2630 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002631 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002632 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002633 if (isTetheringSupported()) {
2634 return mTethering.tether(iface);
2635 } else {
2636 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2637 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002638 }
2639
2640 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002641 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002642 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002643
2644 if (isTetheringSupported()) {
2645 return mTethering.untether(iface);
2646 } else {
2647 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2648 }
2649 }
2650
2651 // javadoc from interface
2652 public int getLastTetherError(String iface) {
2653 enforceTetherAccessPermission();
2654
2655 if (isTetheringSupported()) {
2656 return mTethering.getLastTetherError(iface);
2657 } else {
2658 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2659 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002660 }
2661
2662 // TODO - proper iface API for selection by property, inspection, etc
2663 public String[] getTetherableUsbRegexs() {
2664 enforceTetherAccessPermission();
2665 if (isTetheringSupported()) {
2666 return mTethering.getTetherableUsbRegexs();
2667 } else {
2668 return new String[0];
2669 }
2670 }
2671
2672 public String[] getTetherableWifiRegexs() {
2673 enforceTetherAccessPermission();
2674 if (isTetheringSupported()) {
2675 return mTethering.getTetherableWifiRegexs();
2676 } else {
2677 return new String[0];
2678 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002679 }
2680
Danica Chang6fdd0c62010-08-11 14:54:43 -07002681 public String[] getTetherableBluetoothRegexs() {
2682 enforceTetherAccessPermission();
2683 if (isTetheringSupported()) {
2684 return mTethering.getTetherableBluetoothRegexs();
2685 } else {
2686 return new String[0];
2687 }
2688 }
2689
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002690 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002691 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002692 if (isTetheringSupported()) {
2693 return mTethering.setUsbTethering(enable);
2694 } else {
2695 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2696 }
2697 }
2698
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002699 // TODO - move iface listing, queries, etc to new module
2700 // javadoc from interface
2701 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002702 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002703 return mTethering.getTetherableIfaces();
2704 }
2705
2706 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002707 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002708 return mTethering.getTetheredIfaces();
2709 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002710
Robert Greenwalt5a735062010-03-02 17:25:02 -08002711 public String[] getTetheringErroredIfaces() {
2712 enforceTetherAccessPermission();
2713 return mTethering.getErroredIfaces();
2714 }
2715
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002716 public String[] getTetheredDhcpRanges() {
2717 enforceConnectivityInternalPermission();
2718 return mTethering.getTetheredDhcpRanges();
2719 }
2720
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002721 // if ro.tether.denied = true we default to no tethering
2722 // gservices could set the secure setting to 1 though to enable it on a build where it
2723 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002724 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002725 public boolean isTetheringSupported() {
2726 enforceTetherAccessPermission();
2727 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002728 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002729 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2730 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002731 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2732 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002733 mTethering.getTetherableWifiRegexs().length != 0 ||
2734 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2735 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002736 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002737
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002738 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002739 public void startTethering(int type, ResultReceiver receiver,
2740 boolean showProvisioningUi) {
2741 ConnectivityManager.enforceTetherChangePermission(mContext);
2742 if (!isTetheringSupported()) {
2743 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2744 return;
2745 }
2746 mTethering.startTethering(type, receiver, showProvisioningUi);
2747 }
2748
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002749 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002750 public void stopTethering(int type) {
2751 ConnectivityManager.enforceTetherChangePermission(mContext);
2752 mTethering.stopTethering(type);
2753 }
2754
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002755 // Called when we lose the default network and have no replacement yet.
2756 // This will automatically be cleared after X seconds or a new default network
2757 // becomes CONNECTED, whichever happens first. The timer is started by the
2758 // first caller and not restarted by subsequent callers.
2759 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002760 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002761 synchronized (this) {
2762 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002763 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002764 mNetTransitionWakeLock.acquire();
2765 mNetTransitionWakeLockCausedBy = forWhom;
2766 }
2767 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002768 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002769 mNetTransitionWakeLockTimeout);
2770 return;
2771 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002772
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002773 // 100 percent is full good, 0 is full bad.
2774 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002775 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002776 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002777 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002778 }
2779
Paul Jensenbfd17b72015-04-07 12:43:13 -04002780 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002781 enforceAccessPermission();
2782 enforceInternetPermission();
2783
Paul Jensenbfd17b72015-04-07 12:43:13 -04002784 NetworkAgentInfo nai;
2785 if (network == null) {
2786 nai = getDefaultNetwork();
2787 } else {
2788 nai = getNetworkAgentInfoForNetwork(network);
2789 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002790 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2791 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2792 return;
2793 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002794 // Revalidate if the app report does not match our current validated state.
2795 if (hasConnectivity == nai.lastValidated) return;
2796 final int uid = Binder.getCallingUid();
2797 if (DBG) {
2798 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2799 ") by " + uid);
2800 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002801 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002802 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2803 // which isn't meant to work on uncreated networks.
2804 if (!nai.created) return;
2805
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002806 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002807
2808 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2809 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002810 }
2811
Paul Jensencee9b512015-05-06 07:32:40 -04002812 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002813 // this information is already available as a world read/writable jvm property
2814 // so this API change wouldn't have a benifit. It also breaks the passing
2815 // of proxy info to all the JVMs.
2816 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002817 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002818 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002819 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2820 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002821 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002822 }
2823
Paul Jensencee9b512015-05-06 07:32:40 -04002824 public ProxyInfo getProxyForNetwork(Network network) {
2825 if (network == null) return getDefaultProxy();
2826 final ProxyInfo globalProxy = getGlobalProxy();
2827 if (globalProxy != null) return globalProxy;
2828 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2829 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2830 // caller may not have.
2831 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2832 if (nai == null) return null;
2833 synchronized (nai) {
2834 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2835 if (proxyInfo == null) return null;
2836 return new ProxyInfo(proxyInfo);
2837 }
2838 }
2839
Paul Jensene0bef712014-12-10 15:12:18 -05002840 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2841 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2842 // proxy is null then there is no proxy in place).
2843 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2844 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2845 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2846 proxy = null;
2847 }
2848 return proxy;
2849 }
2850
2851 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2852 // better for determining if a new proxy broadcast is necessary:
2853 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2854 // avoid unnecessary broadcasts.
2855 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2856 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2857 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2858 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2859 // all set.
2860 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2861 a = canonicalizeProxyInfo(a);
2862 b = canonicalizeProxyInfo(b);
2863 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2864 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2865 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2866 }
2867
Jason Monk207900c2014-04-25 15:00:09 -04002868 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002869 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002870
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002871 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002872 if (proxyProperties == mGlobalProxy) return;
2873 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2874 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2875
2876 String host = "";
2877 int port = 0;
2878 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002879 String pacFileUrl = "";
2880 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002881 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002882 if (!proxyProperties.isValid()) {
2883 if (DBG)
2884 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2885 return;
2886 }
Jason Monk207900c2014-04-25 15:00:09 -04002887 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002888 host = mGlobalProxy.getHost();
2889 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002890 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002891 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002892 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002893 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002894 } else {
2895 mGlobalProxy = null;
2896 }
2897 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002898 final long token = Binder.clearCallingIdentity();
2899 try {
2900 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2901 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2902 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2903 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002904 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002905 } finally {
2906 Binder.restoreCallingIdentity(token);
2907 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002908
Jason Monkcf0f97a2014-10-02 15:39:38 -04002909 if (mGlobalProxy == null) {
2910 proxyProperties = mDefaultProxy;
2911 }
2912 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002913 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002914 }
2915
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002916 private void loadGlobalProxy() {
2917 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002918 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2919 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2920 String exclList = Settings.Global.getString(res,
2921 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002922 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2923 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002924 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002925 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002926 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002927 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002928 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002929 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002930 if (!proxyProperties.isValid()) {
2931 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2932 return;
2933 }
2934
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002935 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002936 mGlobalProxy = proxyProperties;
2937 }
2938 }
2939 }
2940
Jason Monk207900c2014-04-25 15:00:09 -04002941 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002942 // this information is already available as a world read/writable jvm property
2943 // so this API change wouldn't have a benifit. It also breaks the passing
2944 // of proxy info to all the JVMs.
2945 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002946 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002947 return mGlobalProxy;
2948 }
2949 }
2950
Jason Monk207900c2014-04-25 15:00:09 -04002951 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002952 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002953 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002954 proxy = null;
2955 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002956 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002957 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002958 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002959 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002960 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2961 return;
2962 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002963
2964 // This call could be coming from the PacManager, containing the port of the local
2965 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2966 // global (to get the correct local port), and send a broadcast.
2967 // TODO: Switch PacManager to have its own message to send back rather than
2968 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002969 if ((mGlobalProxy != null) && (proxy != null)
2970 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002971 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2972 mGlobalProxy = proxy;
2973 sendProxyBroadcast(mGlobalProxy);
2974 return;
2975 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002976 mDefaultProxy = proxy;
2977
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002978 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002979 if (!mDefaultProxyDisabled) {
2980 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002981 }
2982 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002983 }
2984
Paul Jensene0bef712014-12-10 15:12:18 -05002985 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2986 // This method gets called when any network changes proxy, but the broadcast only ever contains
2987 // the default proxy (even if it hasn't changed).
2988 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2989 // world where an app might be bound to a non-default network.
2990 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2991 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2992 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2993
2994 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2995 sendProxyBroadcast(getDefaultProxy());
2996 }
2997 }
2998
Robert Greenwalt434203a2010-10-11 16:00:27 -07002999 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003000 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3001 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003002 if (!TextUtils.isEmpty(proxy)) {
3003 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003004 if (data.length == 0) {
3005 return;
3006 }
3007
Robert Greenwalt434203a2010-10-11 16:00:27 -07003008 String proxyHost = data[0];
3009 int proxyPort = 8080;
3010 if (data.length > 1) {
3011 try {
3012 proxyPort = Integer.parseInt(data[1]);
3013 } catch (NumberFormatException e) {
3014 return;
3015 }
3016 }
Jason Monk207900c2014-04-25 15:00:09 -04003017 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003018 setGlobalProxy(p);
3019 }
3020 }
3021
Jason Monk207900c2014-04-25 15:00:09 -04003022 private void sendProxyBroadcast(ProxyInfo proxy) {
3023 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003024 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003025 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003026 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003027 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3028 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003029 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003030 final long ident = Binder.clearCallingIdentity();
3031 try {
3032 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3033 } finally {
3034 Binder.restoreCallingIdentity(ident);
3035 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003036 }
3037
3038 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003039 final private HashMap<Uri, Integer> mUriEventMap;
3040 final private Context mContext;
3041 final private Handler mHandler;
3042
3043 SettingsObserver(Context context, Handler handler) {
3044 super(null);
3045 mUriEventMap = new HashMap<Uri, Integer>();
3046 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003047 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003048 }
3049
Erik Klineda4bfa82015-04-30 12:58:40 +09003050 void observe(Uri uri, int what) {
3051 mUriEventMap.put(uri, what);
3052 final ContentResolver resolver = mContext.getContentResolver();
3053 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003054 }
3055
3056 @Override
3057 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003058 Slog.wtf(TAG, "Should never be reached.");
3059 }
3060
3061 @Override
3062 public void onChange(boolean selfChange, Uri uri) {
3063 final Integer what = mUriEventMap.get(uri);
3064 if (what != null) {
3065 mHandler.obtainMessage(what.intValue()).sendToTarget();
3066 } else {
3067 loge("No matching event to send for URI=" + uri);
3068 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003069 }
3070 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003071
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003072 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003073 Slog.d(TAG, s);
3074 }
3075
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003076 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003077 Slog.e(TAG, s);
3078 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003079
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003080 private static <T> T checkNotNull(T value, String message) {
3081 if (value == null) {
3082 throw new NullPointerException(message);
3083 }
3084 return value;
3085 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003086
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003087 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003088 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003089 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3090 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3091 *
3092 * @param oldPackage Package name of the application which currently controls VPN, which will
3093 * be replaced. If there is no such application, this should should either be
3094 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3095 * @param newPackage Package name of the application which should gain control of VPN, or
3096 * {@code null} to disable.
3097 * @param userId User for whom to prepare the new VPN.
3098 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003099 * @hide
3100 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003101 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003102 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3103 int userId) {
3104 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003105 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003106
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003107 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003108 Vpn vpn = mVpns.get(userId);
3109 if (vpn != null) {
3110 return vpn.prepare(oldPackage, newPackage);
3111 } else {
3112 return false;
3113 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003114 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003115 }
3116
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003117 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003118 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3119 * This method is used by system-privileged apps.
3120 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3121 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3122 *
3123 * @param packageName The package for which authorization state should change.
3124 * @param userId User for whom {@code packageName} is installed.
3125 * @param authorized {@code true} if this app should be able to start a VPN connection without
3126 * explicit user approval, {@code false} if not.
3127 *
Jeff Davidson05542602014-08-11 14:07:27 -07003128 * @hide
3129 */
3130 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003131 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3132 enforceCrossUserPermission(userId);
3133
Jeff Davidson05542602014-08-11 14:07:27 -07003134 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003135 Vpn vpn = mVpns.get(userId);
3136 if (vpn != null) {
3137 vpn.setPackageAuthorization(packageName, authorized);
3138 }
Jeff Davidson05542602014-08-11 14:07:27 -07003139 }
3140 }
3141
3142 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003143 * Configure a TUN interface and return its file descriptor. Parameters
3144 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003145 * and not available in ConnectivityManager. Permissions are checked in
3146 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003147 * @hide
3148 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003149 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003150 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003151 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003152 int user = UserHandle.getUserId(Binder.getCallingUid());
3153 synchronized(mVpns) {
3154 return mVpns.get(user).establish(config);
3155 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003156 }
3157
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003158 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003159 * Start legacy VPN, controlling native daemons as needed. Creates a
3160 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003161 */
3162 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003163 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003164 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003165 final LinkProperties egress = getActiveLinkProperties();
3166 if (egress == null) {
3167 throw new IllegalStateException("Missing active network connection");
3168 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003169 int user = UserHandle.getUserId(Binder.getCallingUid());
3170 synchronized(mVpns) {
3171 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3172 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003173 }
3174
3175 /**
3176 * Return the information of the ongoing legacy VPN. This method is used
3177 * by VpnSettings and not available in ConnectivityManager. Permissions
3178 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003179 */
3180 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003181 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3182 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003183 if (mLockdownEnabled) {
3184 return null;
3185 }
3186
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003187 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003188 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003189 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003190 }
3191
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003192 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003193 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3194 * and not available in ConnectivityManager.
3195 */
3196 @Override
3197 public VpnInfo[] getAllVpnInfo() {
3198 enforceConnectivityInternalPermission();
3199 if (mLockdownEnabled) {
3200 return new VpnInfo[0];
3201 }
3202
3203 synchronized(mVpns) {
3204 List<VpnInfo> infoList = new ArrayList<>();
3205 for (int i = 0; i < mVpns.size(); i++) {
3206 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3207 if (info != null) {
3208 infoList.add(info);
3209 }
3210 }
3211 return infoList.toArray(new VpnInfo[infoList.size()]);
3212 }
3213 }
3214
3215 /**
3216 * @return VPN information for accounting, or null if we can't retrieve all required
3217 * information, e.g primary underlying iface.
3218 */
3219 @Nullable
3220 private VpnInfo createVpnInfo(Vpn vpn) {
3221 VpnInfo info = vpn.getVpnInfo();
3222 if (info == null) {
3223 return null;
3224 }
3225 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3226 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3227 // the underlyingNetworks list.
3228 if (underlyingNetworks == null) {
3229 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3230 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3231 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3232 }
3233 } else if (underlyingNetworks.length > 0) {
3234 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3235 if (linkProperties != null) {
3236 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3237 }
3238 }
3239 return info.primaryUnderlyingIface == null ? null : info;
3240 }
3241
3242 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003243 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3244 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003245 * Permissions are checked in Vpn class.
3246 * @hide
3247 */
3248 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003249 public VpnConfig getVpnConfig(int userId) {
3250 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003251 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003252 Vpn vpn = mVpns.get(userId);
3253 if (vpn != null) {
3254 return vpn.getVpnConfig();
3255 } else {
3256 return null;
3257 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003258 }
3259 }
3260
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003261 @Override
3262 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003263 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3264 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3265 return false;
3266 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003267
3268 // Tear down existing lockdown if profile was removed
3269 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3270 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003271 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3272 final VpnProfile profile = VpnProfile.decode(
3273 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003274 if (profile == null) {
3275 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3276 setLockdownTracker(null);
3277 return true;
3278 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003279 int user = UserHandle.getUserId(Binder.getCallingUid());
3280 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003281 Vpn vpn = mVpns.get(user);
3282 if (vpn == null) {
3283 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3284 return false;
3285 }
3286 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003287 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003288 } else {
3289 setLockdownTracker(null);
3290 }
3291
3292 return true;
3293 }
3294
3295 /**
3296 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3297 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3298 */
3299 private void setLockdownTracker(LockdownVpnTracker tracker) {
3300 // Shutdown any existing tracker
3301 final LockdownVpnTracker existing = mLockdownTracker;
3302 mLockdownTracker = null;
3303 if (existing != null) {
3304 existing.shutdown();
3305 }
3306
3307 try {
3308 if (tracker != null) {
3309 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003310 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003311 mLockdownTracker = tracker;
3312 mLockdownTracker.init();
3313 } else {
3314 mNetd.setFirewallEnabled(false);
3315 }
3316 } catch (RemoteException e) {
3317 // ignored; NMS lives inside system_server
3318 }
3319 }
3320
3321 private void throwIfLockdownEnabled() {
3322 if (mLockdownEnabled) {
3323 throw new IllegalStateException("Unavailable in lockdown mode");
3324 }
3325 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003326
Robin Lee244ce8e2016-01-05 18:03:46 +00003327 /**
3328 * Sets up or tears down the always-on VPN for user {@param user} as appropriate.
3329 *
3330 * @return {@code false} in case of errors; {@code true} otherwise.
3331 */
3332 private boolean updateAlwaysOnVpn(int user) {
3333 final String lockdownPackage = getAlwaysOnVpnPackage(user);
3334 if (lockdownPackage == null) {
3335 return true;
3336 }
3337
3338 // Create an intent to start the VPN service declared in the app's manifest.
3339 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
3340 serviceIntent.setPackage(lockdownPackage);
3341
3342 try {
3343 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(user)) != null;
3344 } catch (RuntimeException e) {
3345 return false;
3346 }
3347 }
3348
3349 @Override
3350 public boolean setAlwaysOnVpnPackage(int userId, String packageName) {
3351 enforceConnectivityInternalPermission();
3352 enforceCrossUserPermission(userId);
3353
3354 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3355 if (LockdownVpnTracker.isEnabled()) {
3356 return false;
3357 }
3358
3359 // If the current VPN package is the same as the new one, this is a no-op
3360 final String oldPackage = getAlwaysOnVpnPackage(userId);
3361 if (TextUtils.equals(oldPackage, packageName)) {
3362 return true;
3363 }
3364
3365 synchronized (mVpns) {
3366 Vpn vpn = mVpns.get(userId);
3367 if (vpn == null) {
3368 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3369 return false;
3370 }
3371 if (!vpn.setAlwaysOnPackage(packageName)) {
3372 return false;
3373 }
3374 if (!updateAlwaysOnVpn(userId)) {
3375 vpn.setAlwaysOnPackage(null);
3376 return false;
3377 }
3378 }
3379 return true;
3380 }
3381
3382 @Override
3383 public String getAlwaysOnVpnPackage(int userId) {
3384 enforceConnectivityInternalPermission();
3385 enforceCrossUserPermission(userId);
3386
3387 synchronized (mVpns) {
3388 Vpn vpn = mVpns.get(userId);
3389 if (vpn == null) {
3390 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3391 return null;
3392 }
3393 return vpn.getAlwaysOnPackage();
3394 }
3395 }
3396
Wink Savilleab9321d2013-06-29 21:10:57 -07003397 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003398 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003399 // TODO: Remove? Any reason to trigger a provisioning check?
3400 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003401 }
3402
3403 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003404 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003405
Paul Jensen89e0f092014-09-15 15:59:36 -04003406 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003407 if (DBG) {
3408 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003409 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003410 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003411 Intent intent = new Intent(action);
3412 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003413 // Concatenate the range of types onto the range of NetIDs.
3414 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003415 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003416 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003417 }
3418
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003419 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003420 * Show or hide network provisioning notifications.
3421 *
3422 * We use notifications for two purposes: to notify that a network requires sign in
3423 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3424 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3425 * particular network we can display the notification type that was most recently requested.
3426 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3427 * might first display NO_INTERNET, and then when the captive portal check completes, display
3428 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003429 *
3430 * @param id an identifier that uniquely identifies this notification. This must match
3431 * between show and hide calls. We use the NetID value but for legacy callers
3432 * we concatenate the range of types with the range of NetIDs.
3433 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003434 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003435 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3436 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003437 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003438 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3439 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003440 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003441 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003442
3443 Resources r = Resources.getSystem();
3444 NotificationManager notificationManager = (NotificationManager) mContext
3445 .getSystemService(Context.NOTIFICATION_SERVICE);
3446
3447 if (visible) {
3448 CharSequence title;
3449 CharSequence details;
3450 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003451 if (notifyType == NotificationType.NO_INTERNET &&
3452 networkType == ConnectivityManager.TYPE_WIFI) {
3453 title = r.getString(R.string.wifi_no_internet, 0);
3454 details = r.getString(R.string.wifi_no_internet_detailed);
3455 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3456 } else if (notifyType == NotificationType.SIGN_IN) {
3457 switch (networkType) {
3458 case ConnectivityManager.TYPE_WIFI:
3459 title = r.getString(R.string.wifi_available_sign_in, 0);
3460 details = r.getString(R.string.network_available_sign_in_detailed,
3461 extraInfo);
3462 icon = R.drawable.stat_notify_wifi_in_range;
3463 break;
3464 case ConnectivityManager.TYPE_MOBILE:
3465 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3466 title = r.getString(R.string.network_available_sign_in, 0);
3467 // TODO: Change this to pull from NetworkInfo once a printable
3468 // name has been added to it
3469 details = mTelephonyManager.getNetworkOperatorName();
3470 icon = R.drawable.stat_notify_rssi_in_range;
3471 break;
3472 default:
3473 title = r.getString(R.string.network_available_sign_in, 0);
3474 details = r.getString(R.string.network_available_sign_in_detailed,
3475 extraInfo);
3476 icon = R.drawable.stat_notify_rssi_in_range;
3477 break;
3478 }
3479 } else {
3480 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3481 + getNetworkTypeName(networkType));
3482 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003483 }
3484
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003485 Notification notification = new Notification.Builder(mContext)
3486 .setWhen(0)
3487 .setSmallIcon(icon)
3488 .setAutoCancel(true)
3489 .setTicker(title)
3490 .setColor(mContext.getColor(
3491 com.android.internal.R.color.system_notification_accent_color))
3492 .setContentTitle(title)
3493 .setContentText(details)
3494 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003495 .setLocalOnly(true)
3496 .setPriority(highPriority ?
3497 Notification.PRIORITY_HIGH :
3498 Notification.PRIORITY_DEFAULT)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003499 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003500 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003501 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003502
Wink Saville948282b2013-08-29 08:55:16 -07003503 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003504 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003505 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003506 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003507 npe.printStackTrace();
3508 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003509 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003510 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003511 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003512 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003513 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003514 npe.printStackTrace();
3515 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003516 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003517 }
3518
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003519 /** Location to an updatable file listing carrier provisioning urls.
3520 * An example:
3521 *
3522 * <?xml version="1.0" encoding="utf-8"?>
3523 * <provisioningUrls>
3524 * <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 -07003525 * </provisioningUrls>
3526 */
3527 private static final String PROVISIONING_URL_PATH =
3528 "/data/misc/radio/provisioning_urls.xml";
3529 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003530
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003531 /** XML tag for root element. */
3532 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3533 /** XML tag for individual url */
3534 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003535 /** XML attribute for mcc */
3536 private static final String ATTR_MCC = "mcc";
3537 /** XML attribute for mnc */
3538 private static final String ATTR_MNC = "mnc";
3539
Paul Jensen434dde82015-06-11 09:43:30 -04003540 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003541 FileReader fileReader = null;
3542 XmlPullParser parser = null;
3543 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003544
3545 try {
3546 fileReader = new FileReader(mProvisioningUrlFile);
3547 parser = Xml.newPullParser();
3548 parser.setInput(fileReader);
3549 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3550
3551 while (true) {
3552 XmlUtils.nextElement(parser);
3553
3554 String element = parser.getName();
3555 if (element == null) break;
3556
Paul Jensen434dde82015-06-11 09:43:30 -04003557 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003558 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3559 try {
3560 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3561 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3562 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3563 parser.next();
3564 if (parser.getEventType() == XmlPullParser.TEXT) {
3565 return parser.getText();
3566 }
3567 }
3568 }
3569 } catch (NumberFormatException e) {
3570 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3571 }
3572 }
3573 }
3574 return null;
3575 } catch (FileNotFoundException e) {
3576 loge("Carrier Provisioning Urls file not found");
3577 } catch (XmlPullParserException e) {
3578 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3579 } catch (IOException e) {
3580 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3581 } finally {
3582 if (fileReader != null) {
3583 try {
3584 fileReader.close();
3585 } catch (IOException e) {}
3586 }
3587 }
3588 return null;
3589 }
3590
Wink Saville42d4f082013-07-20 20:31:59 -07003591 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003592 public String getMobileProvisioningUrl() {
3593 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003594 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003595 if (TextUtils.isEmpty(url)) {
3596 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003597 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003598 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003599 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003600 }
Wink Saville8cf35602013-07-10 23:00:07 -07003601 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003602 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003603 String phoneNumber = mTelephonyManager.getLine1Number();
3604 if (TextUtils.isEmpty(phoneNumber)) {
3605 phoneNumber = "0000000000";
3606 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003607 url = String.format(url,
3608 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3609 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003610 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003611 }
3612
Wink Savilleab9321d2013-06-29 21:10:57 -07003613 return url;
3614 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003615
Wink Saville948282b2013-08-29 08:55:16 -07003616 @Override
3617 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003618 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003619 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003620 final long ident = Binder.clearCallingIdentity();
3621 try {
3622 setProvNotificationVisible(visible, networkType, action);
3623 } finally {
3624 Binder.restoreCallingIdentity(ident);
3625 }
Wink Saville948282b2013-08-29 08:55:16 -07003626 }
Wink Saville7788c612013-08-29 14:57:08 -07003627
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003628 @Override
3629 public void setAirplaneMode(boolean enable) {
3630 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003631 final long ident = Binder.clearCallingIdentity();
3632 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003633 final ContentResolver cr = mContext.getContentResolver();
3634 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3635 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3636 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003637 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003638 } finally {
3639 Binder.restoreCallingIdentity(ident);
3640 }
3641 }
3642
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003643 private void onUserStart(int userId) {
3644 synchronized(mVpns) {
3645 Vpn userVpn = mVpns.get(userId);
3646 if (userVpn != null) {
3647 loge("Starting user already has a VPN");
3648 return;
3649 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003650 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003651 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003652 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003653 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3654 updateLockdownVpn();
3655 } else {
3656 updateAlwaysOnVpn(userId);
3657 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003658 }
3659
3660 private void onUserStop(int userId) {
3661 synchronized(mVpns) {
3662 Vpn userVpn = mVpns.get(userId);
3663 if (userVpn == null) {
3664 loge("Stopping user has no VPN");
3665 return;
3666 }
3667 mVpns.delete(userId);
3668 }
3669 }
3670
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003671 private void onUserAdded(int userId) {
3672 synchronized(mVpns) {
3673 final int vpnsSize = mVpns.size();
3674 for (int i = 0; i < vpnsSize; i++) {
3675 Vpn vpn = mVpns.valueAt(i);
3676 vpn.onUserAdded(userId);
3677 }
3678 }
3679 }
3680
3681 private void onUserRemoved(int userId) {
3682 synchronized(mVpns) {
3683 final int vpnsSize = mVpns.size();
3684 for (int i = 0; i < vpnsSize; i++) {
3685 Vpn vpn = mVpns.valueAt(i);
3686 vpn.onUserRemoved(userId);
3687 }
3688 }
3689 }
3690
Robin Lee89e7a692016-02-29 14:38:17 +00003691 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003692 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3693 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3694 updateLockdownVpn();
3695 } else {
3696 updateAlwaysOnVpn(userId);
3697 }
3698 }
3699
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003700 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3701 @Override
3702 public void onReceive(Context context, Intent intent) {
3703 final String action = intent.getAction();
3704 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3705 if (userId == UserHandle.USER_NULL) return;
3706
3707 if (Intent.ACTION_USER_STARTING.equals(action)) {
3708 onUserStart(userId);
3709 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3710 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003711 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3712 onUserAdded(userId);
3713 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3714 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003715 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3716 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003717 }
3718 }
3719 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003720
Robert Greenwalta67be032014-05-16 15:49:14 -07003721 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3722 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003723 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3724 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003725
Robert Greenwalta67be032014-05-16 15:49:14 -07003726 private static class NetworkFactoryInfo {
3727 public final String name;
3728 public final Messenger messenger;
3729 public final AsyncChannel asyncChannel;
3730
3731 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3732 this.name = name;
3733 this.messenger = messenger;
3734 this.asyncChannel = asyncChannel;
3735 }
3736 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003737
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003738 /**
3739 * Tracks info about the requester.
3740 * Also used to notice when the calling process dies so we can self-expire
3741 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003742 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3743 static final boolean REQUEST = true;
3744 static final boolean LISTEN = false;
3745
3746 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003747 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003748 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003749 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003750 final int mPid;
3751 final int mUid;
3752 final Messenger messenger;
3753 final boolean isRequest;
3754
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003755 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3756 request = r;
3757 mPendingIntent = pi;
3758 messenger = null;
3759 mBinder = null;
3760 mPid = getCallingPid();
3761 mUid = getCallingUid();
3762 this.isRequest = isRequest;
3763 }
3764
Robert Greenwalt9258c642014-03-26 16:47:06 -07003765 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3766 super();
3767 messenger = m;
3768 request = r;
3769 mBinder = binder;
3770 mPid = getCallingPid();
3771 mUid = getCallingUid();
3772 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003773 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003774
3775 try {
3776 mBinder.linkToDeath(this, 0);
3777 } catch (RemoteException e) {
3778 binderDied();
3779 }
3780 }
3781
3782 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003783 if (mBinder != null) {
3784 mBinder.unlinkToDeath(this, 0);
3785 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003786 }
3787
3788 public void binderDied() {
3789 log("ConnectivityService NetworkRequestInfo binderDied(" +
3790 request + ", " + mBinder + ")");
3791 releaseNetworkRequest(request);
3792 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003793
3794 public String toString() {
Erik Kline7523eb32015-07-09 18:24:03 +09003795 return (isRequest ? "Request" : "Listen") +
3796 " from uid/pid:" + mUid + "/" + mPid +
3797 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003798 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003799 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003800 }
3801
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003802 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3803 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3804 if (badCapability != null) {
3805 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003806 }
3807 }
3808
Erik Kline9d598e12015-07-13 16:37:51 +09003809 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003810 final SortedSet<Integer> thresholds = new TreeSet();
3811 synchronized (nai) {
3812 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3813 if (nri.request.networkCapabilities.hasSignalStrength() &&
3814 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3815 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3816 }
3817 }
3818 }
Erik Kline9d598e12015-07-13 16:37:51 +09003819 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003820 }
3821
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003822 private void updateSignalStrengthThresholds(
3823 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3824 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003825 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003826 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3827
3828 // TODO: Switch to VDBG.
3829 if (DBG) {
3830 String detail;
3831 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3832 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3833 } else {
3834 detail = reason;
3835 }
3836 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3837 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3838 }
3839
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003840 nai.asyncChannel.sendMessage(
3841 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003842 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003843 }
3844
Robert Greenwalt9258c642014-03-26 16:47:06 -07003845 @Override
3846 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003847 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Erik Klinea2d29402016-03-16 15:31:39 +09003848 // If the requested networkCapabilities is null, take them instead from
3849 // the default network request. This allows callers to keep track of
3850 // the system default network.
3851 if (networkCapabilities == null) {
3852 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
3853 enforceAccessPermission();
3854 } else {
3855 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3856 enforceNetworkRequestPermissions(networkCapabilities);
3857 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003858 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003859 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003860
Robert Greenwalt6078b502014-06-11 16:05:07 -07003861 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003862 throw new IllegalArgumentException("Bad timeout specified");
3863 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003864
Etan Cohenddb9ef02015-11-18 10:56:15 -08003865 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
3866 .equals(networkCapabilities.getNetworkSpecifier())) {
3867 throw new IllegalArgumentException("Invalid network specifier - must not be '"
3868 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
3869 }
3870
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003871 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3872 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003873 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3874 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003875 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003876
3877 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003878 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003879 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003880 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003881 }
3882 return networkRequest;
3883 }
3884
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003885 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003886 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003887 enforceConnectivityInternalPermission();
3888 } else {
3889 enforceChangePermission();
3890 }
3891 }
3892
fenglub15e72b2015-03-20 11:29:56 -07003893 @Override
fengludb571472015-04-21 17:12:05 -07003894 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003895 enforceAccessPermission();
3896 NetworkAgentInfo nai = null;
3897 if (network == null) {
3898 return false;
3899 }
3900 synchronized (mNetworkForNetId) {
3901 nai = mNetworkForNetId.get(network.netId);
3902 }
3903 if (nai != null) {
3904 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3905 return true;
3906 }
3907 return false;
3908 }
3909
3910
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003911 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3912 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003913 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003914 final int uidRules;
3915 final int uid = Binder.getCallingUid();
3916 synchronized(mRulesLock) {
3917 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3918 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003919 if (uidRules != RULE_ALLOW_ALL) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003920 // we could silently fail or we can filter the available nets to only give
3921 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003922 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003923 }
3924 }
3925 }
3926
Robert Greenwalt9258c642014-03-26 16:47:06 -07003927 @Override
3928 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3929 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003930 checkNotNull(operation, "PendingIntent cannot be null.");
3931 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3932 enforceNetworkRequestPermissions(networkCapabilities);
3933 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003934 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003935
3936 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3937 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003938 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3939 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003940 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003941 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3942 nri));
3943 return networkRequest;
3944 }
3945
Jeremy Joslin79294842014-12-03 17:15:28 -08003946 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3947 mHandler.sendMessageDelayed(
3948 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3949 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3950 }
3951
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003952 @Override
3953 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003954 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003955 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3956 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003957 }
3958
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003959 // In order to implement the compatibility measure for pre-M apps that call
3960 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3961 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3962 // This ensures it has permission to do so.
3963 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3964 if (nc == null) {
3965 return false;
3966 }
3967 int[] transportTypes = nc.getTransportTypes();
3968 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3969 return false;
3970 }
3971 try {
3972 mContext.enforceCallingOrSelfPermission(
3973 android.Manifest.permission.ACCESS_WIFI_STATE,
3974 "ConnectivityService");
3975 } catch (SecurityException e) {
3976 return false;
3977 }
3978 return true;
3979 }
3980
Robert Greenwalt9258c642014-03-26 16:47:06 -07003981 @Override
3982 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3983 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003984 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3985 enforceAccessPermission();
3986 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003987
Erik Kline7523eb32015-07-09 18:24:03 +09003988 NetworkRequest networkRequest = new NetworkRequest(
3989 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003990 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3991 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003992 if (DBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003993
3994 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3995 return networkRequest;
3996 }
3997
3998 @Override
3999 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4000 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004001 checkNotNull(operation, "PendingIntent cannot be null.");
4002 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4003 enforceAccessPermission();
4004 }
4005
Erik Kline7523eb32015-07-09 18:24:03 +09004006 NetworkRequest networkRequest = new NetworkRequest(
4007 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04004008 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
4009 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09004010 if (DBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004011
4012 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004013 }
4014
4015 @Override
4016 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04004017 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4018 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004019 }
4020
4021 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004022 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004023 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004024 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4025 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004026 }
4027
Robert Greenwalta67be032014-05-16 15:49:14 -07004028 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004029 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004030 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4031 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4032 }
4033
4034 @Override
4035 public void unregisterNetworkFactory(Messenger messenger) {
4036 enforceConnectivityInternalPermission();
4037 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4038 }
4039
4040 private void handleUnregisterNetworkFactory(Messenger messenger) {
4041 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4042 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004043 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004044 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004045 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004046 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004047 }
4048
Robert Greenwalt7b816022014-04-18 15:25:25 -07004049 /**
4050 * NetworkAgentInfo supporting a request by requestId.
4051 * These have already been vetted (their Capabilities satisfy the request)
4052 * and the are the highest scored network available.
4053 * the are keyed off the Requests requestId.
4054 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004055 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004056 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4057 new SparseArray<NetworkAgentInfo>();
4058
Paul Jensen31a94f42015-02-13 14:18:39 -05004059 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4060 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004061 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4062 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004063 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4064 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4065 // there may not be a strict 1:1 correlation between the two.
4066 @GuardedBy("mNetworkForNetId")
4067 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004068
Robert Greenwalt7b816022014-04-18 15:25:25 -07004069 // NetworkAgentInfo keyed off its connecting messenger
4070 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004071 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004072 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4073 new HashMap<Messenger, NetworkAgentInfo>();
4074
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004075 @GuardedBy("mBlockedAppUids")
4076 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4077
Paul Jensen2c311d62014-11-17 12:34:51 -05004078 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004079 private final NetworkRequest mDefaultRequest;
4080
Erik Klineda4bfa82015-04-30 12:58:40 +09004081 // Request used to optionally keep mobile data active even when higher
4082 // priority networks like Wi-Fi are active.
4083 private final NetworkRequest mDefaultMobileDataRequest;
4084
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004085 private NetworkAgentInfo getDefaultNetwork() {
4086 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4087 }
4088
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004089 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004090 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004091 }
4092
Paul Jensen31a94f42015-02-13 14:18:39 -05004093 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004094 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004095 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004096 enforceConnectivityInternalPermission();
4097
Paul Jensen2c311d62014-11-17 12:34:51 -05004098 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4099 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004100 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004101 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4102 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004103 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004104 synchronized (this) {
4105 nai.networkMonitor.systemReady = mSystemReady;
4106 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07004107 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004108 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004109 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004110 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004111 }
4112
4113 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4114 if (VDBG) log("Got NetworkAgent Messenger");
4115 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004116 synchronized (mNetworkForNetId) {
4117 mNetworkForNetId.put(na.network.netId, na);
4118 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004119 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4120 NetworkInfo networkInfo = na.networkInfo;
4121 na.networkInfo = null;
4122 updateNetworkInfo(na, networkInfo);
4123 }
4124
4125 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4126 LinkProperties newLp = networkAgent.linkProperties;
4127 int netId = networkAgent.network.netId;
4128
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004129 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4130 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004131 if (networkAgent.clatd != null) {
4132 networkAgent.clatd.fixupLinkProperties(oldLp);
4133 }
Paul Jensen578a76e2016-01-14 14:54:39 -05004134 if (networkAgent.apfFilter != null) {
4135 networkAgent.apfFilter.updateFilter();
4136 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004137
Paul Jensen992f2522014-04-28 10:33:11 -04004138 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004139 updateMtu(newLp, oldLp);
4140 // TODO - figure out what to do for clat
4141// for (LinkProperties lp : newLp.getStackedLinks()) {
4142// updateMtu(lp, null);
4143// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004144 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004145
Lorenzo Colitti93155b32015-05-14 22:12:36 +09004146 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
4147 // In L, we used it only when the network had Internet access but provided no DNS servers.
4148 // For now, just disable it, and if disabling it doesn't break things, remove it.
4149 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
4150 // NET_CAPABILITY_INTERNET);
4151 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004152 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004153 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
4154
Paul Jensen3b759822014-05-13 11:44:01 -04004155 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004156 if (isDefaultNetwork(networkAgent)) {
4157 handleApplyDefaultProxy(newLp.getHttpProxy());
4158 } else {
4159 updateProxy(newLp, oldLp, networkAgent);
4160 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004161 // TODO - move this check to cover the whole function
4162 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004163 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004164 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4165 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004166
4167 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004168 }
4169
Lorenzo Colitti95439462014-10-09 13:44:48 +09004170 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4171 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4172 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004173
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004174 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004175 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4176 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004177 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004178 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004179 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004180 }
Paul Jensen992f2522014-04-28 10:33:11 -04004181
4182 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4183 CompareResult<String> interfaceDiff = new CompareResult<String>();
4184 if (oldLp != null) {
4185 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4186 } else if (newLp != null) {
4187 interfaceDiff.added = newLp.getAllInterfaceNames();
4188 }
4189 for (String iface : interfaceDiff.added) {
4190 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004191 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004192 mNetd.addInterfaceToNetwork(iface, netId);
4193 } catch (Exception e) {
4194 loge("Exception adding interface: " + e);
4195 }
4196 }
4197 for (String iface : interfaceDiff.removed) {
4198 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004199 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004200 mNetd.removeInterfaceFromNetwork(iface, netId);
4201 } catch (Exception e) {
4202 loge("Exception removing interface: " + e);
4203 }
4204 }
4205 }
4206
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004207 /**
4208 * Have netd update routes from oldLp to newLp.
4209 * @return true if routes changed between oldLp and newLp
4210 */
4211 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004212 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4213 if (oldLp != null) {
4214 routeDiff = oldLp.compareAllRoutes(newLp);
4215 } else if (newLp != null) {
4216 routeDiff.added = newLp.getAllRoutes();
4217 }
4218
4219 // add routes before removing old in case it helps with continuous connectivity
4220
4221 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4222 for (RouteInfo route : routeDiff.added) {
4223 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004224 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004225 try {
4226 mNetd.addRoute(netId, route);
4227 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004228 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4229 loge("Exception in addRoute for non-gateway: " + e);
4230 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004231 }
4232 }
4233 for (RouteInfo route : routeDiff.added) {
4234 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004235 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004236 try {
4237 mNetd.addRoute(netId, route);
4238 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004239 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4240 loge("Exception in addRoute for gateway: " + e);
4241 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004242 }
4243 }
4244
4245 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004246 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004247 try {
4248 mNetd.removeRoute(netId, route);
4249 } catch (Exception e) {
4250 loge("Exception in removeRoute: " + e);
4251 }
4252 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004253 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004254 }
Erik Kline41368502015-06-17 13:19:54 +09004255
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004256 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
4257 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004258 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Klineb36a3132015-06-26 19:21:34 +09004259 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004260 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004261 dnses = new ArrayList();
4262 dnses.add(mDefaultDns);
4263 if (DBG) {
4264 loge("no dns provided for netId " + netId + ", so using defaults");
4265 }
4266 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004267 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004268 try {
4269 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4270 newLp.getDomains());
4271 } catch (Exception e) {
4272 loge("Exception in setDnsServersForNetwork: " + e);
4273 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04004274 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004275 if (defaultNai != null && defaultNai.network.netId == netId) {
4276 setDefaultDnsSystemProperties(dnses);
4277 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07004278 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004279 } else if (flush) {
4280 try {
4281 mNetd.flushNetworkDnsCache(netId);
4282 } catch (Exception e) {
4283 loge("Exception in flushNetworkDnsCache: " + e);
4284 }
4285 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004286 }
4287 }
4288
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004289 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4290 int last = 0;
4291 for (InetAddress dns : dnses) {
4292 ++last;
4293 String key = "net.dns" + last;
4294 String value = dns.getHostAddress();
4295 SystemProperties.set(key, value);
4296 }
4297 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4298 String key = "net.dns" + i;
4299 SystemProperties.set(key, "");
4300 }
4301 mNumDnsEntries = last;
4302 }
4303
Paul Jensen3d194ea2015-06-16 14:27:36 -04004304 /**
4305 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4306 * augmented with any stateful capabilities implied from {@code networkAgent}
4307 * (e.g., validated status and captive portal status).
4308 *
Paul Jensene0988542015-06-25 15:30:08 -04004309 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004310 * @param networkCapabilities the new network capabilities.
4311 */
Paul Jensene0988542015-06-25 15:30:08 -04004312 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004313 // Don't modify caller's NetworkCapabilities.
4314 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004315 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004316 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4317 } else {
4318 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4319 }
Paul Jensene0988542015-06-25 15:30:08 -04004320 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004321 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4322 } else {
4323 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4324 }
Paul Jensene0988542015-06-25 15:30:08 -04004325 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4326 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004327 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4328 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4329 try {
4330 mNetd.setNetworkPermission(nai.network.netId,
4331 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4332 null : NetworkManagementService.PERMISSION_SYSTEM);
4333 } catch (RemoteException e) {
4334 loge("Exception in setNetworkPermission: " + e);
4335 }
4336 }
Paul Jensene0988542015-06-25 15:30:08 -04004337 synchronized (nai) {
4338 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004339 }
Paul Jensene0988542015-06-25 15:30:08 -04004340 rematchAllNetworksAndRequests(nai, oldScore);
4341 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004342 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004343 }
4344
Paul Jensenc8b9a742014-09-30 15:37:41 -04004345 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4346 for (int i = 0; i < nai.networkRequests.size(); i++) {
4347 NetworkRequest nr = nai.networkRequests.valueAt(i);
4348 // Don't send listening requests to factories. b/17393458
4349 if (!isRequest(nr)) continue;
4350 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4351 }
4352 }
4353
Robert Greenwalt7b816022014-04-18 15:25:25 -07004354 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4355 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004356 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004357 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4358 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004359 }
4360 }
4361
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004362 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4363 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004364 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004365 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004366 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4367 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004368 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004369 sendIntent(nri.mPendingIntent, intent);
4370 }
4371 // else not handled
4372 }
4373
4374 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4375 mPendingIntentWakeLock.acquire();
4376 try {
4377 if (DBG) log("Sending " + pendingIntent);
4378 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4379 } catch (PendingIntent.CanceledException e) {
4380 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4381 mPendingIntentWakeLock.release();
4382 releasePendingNetworkRequest(pendingIntent);
4383 }
4384 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4385 }
4386
4387 @Override
4388 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4389 String resultData, Bundle resultExtras) {
4390 if (DBG) log("Finished sending " + pendingIntent);
4391 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004392 // Release with a delay so the receiving client has an opportunity to put in its
4393 // own request.
4394 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004395 }
4396
Robert Greenwalt9258c642014-03-26 16:47:06 -07004397 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004398 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004399 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004400 Bundle bundle = new Bundle();
4401 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4402 new NetworkRequest(nri.request));
4403 Message msg = Message.obtain();
4404 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4405 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4406 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4407 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004408 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004409 case ConnectivityManager.CALLBACK_LOSING: {
4410 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4411 break;
4412 }
4413 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4414 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4415 new NetworkCapabilities(networkAgent.networkCapabilities));
4416 break;
4417 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004418 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004419 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4420 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004421 break;
4422 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004423 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004424 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004425 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004426 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004427 if (VDBG) {
4428 log("sending notification " + notifyTypeToName(notificationType) +
4429 " for " + nri.request);
4430 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004431 nri.messenger.send(msg);
4432 } catch (RemoteException e) {
4433 // may occur naturally in the race of binder death.
4434 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4435 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004436 }
4437
Paul Jensenc8b9a742014-09-30 15:37:41 -04004438 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4439 for (int i = 0; i < nai.networkRequests.size(); i++) {
4440 NetworkRequest nr = nai.networkRequests.valueAt(i);
4441 // Ignore listening requests.
4442 if (!isRequest(nr)) continue;
4443 loge("Dead network still had at least " + nr);
4444 break;
4445 }
4446 nai.asyncChannel.disconnect();
4447 }
4448
Robert Greenwalt7b816022014-04-18 15:25:25 -07004449 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4450 if (oldNetwork == null) {
4451 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4452 return;
4453 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004454 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4455 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004456 }
4457
Paul Jensen27b02b72014-07-14 12:03:33 -04004458 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004459 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004460 setupDataActivityTracking(newNetwork);
4461 try {
4462 mNetd.setDefaultNetId(newNetwork.network.netId);
4463 } catch (Exception e) {
4464 loge("Exception setting default network :" + e);
4465 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004466 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004467 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004468 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004469 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004470 }
4471
Paul Jensen2161a8e2014-09-11 11:00:39 -04004472 // Handles a network appearing or improving its score.
4473 //
4474 // - Evaluates all current NetworkRequests that can be
4475 // satisfied by newNetwork, and reassigns to newNetwork
4476 // any such requests for which newNetwork is the best.
4477 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004478 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004479 // needed. A network is needed if it is the best network for
4480 // one or more NetworkRequests, or if it is a VPN.
4481 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004482 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004483 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004484 //
4485 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4486 // networks that have no chance (i.e. even if validated)
4487 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004488 //
4489 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4490 // it does not remove NetworkRequests that other Networks could better satisfy.
4491 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4492 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4493 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004494 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004495 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004496 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4497 // performed to tear down unvalidated networks that have no chance (i.e. even if
4498 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004499 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004500 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004501 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004502 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004503 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004504 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004505 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004506 // Find and migrate to this Network any NetworkRequests for
4507 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004508 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004509 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004510 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004511 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004512 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4513 final boolean satisfies = newNetwork.satisfies(nri.request);
4514 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004515 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004516 log("Network " + newNetwork.name() + " was already satisfying" +
4517 " request " + nri.request.requestId + ". No change.");
4518 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004519 keep = true;
4520 continue;
4521 }
4522
4523 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004524 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004525 if (satisfies) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004526 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004527 // This is not a request, it's a callback listener.
4528 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004529 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004530 continue;
4531 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004532
Robert Greenwalt7b816022014-04-18 15:25:25 -07004533 // next check if it's better than any current network we're using for
4534 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004535 if (VDBG) {
4536 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004537 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4538 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004539 }
4540 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004541 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004542 if (DBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004543 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004544 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004545 currentNetwork.networkRequests.remove(nri.request.requestId);
4546 currentNetwork.networkLingered.add(nri.request);
4547 affectedNetworks.add(currentNetwork);
4548 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004549 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004550 }
Paul Jensen573a0352015-01-08 10:49:34 -05004551 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004552 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004553 if (!newNetwork.addRequest(nri.request)) {
4554 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4555 }
4556 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004557 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004558 // Tell NetworkFactories about the new score, so they can stop
4559 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004560 // TODO - this could get expensive if we have alot of requests for this
4561 // network. Think about if there is a way to reduce this. Push
4562 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004563 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004564 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004565 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004566 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004567 }
4568 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004569 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4570 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4571 // mark it as no longer satisfying "nri". Because networks are processed by
4572 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4573 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4574 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4575 // This means this code doesn't have to handle the case where "currentNetwork" no
4576 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4577 if (DBG) {
4578 log("Network " + newNetwork.name() + " stopped satisfying" +
4579 " request " + nri.request.requestId);
4580 }
4581 newNetwork.networkRequests.remove(nri.request.requestId);
4582 if (currentNetwork == newNetwork) {
4583 mNetworkForRequestId.remove(nri.request.requestId);
4584 sendUpdatedScoreToFactories(nri.request, 0);
4585 } else {
4586 if (nri.isRequest == true) {
4587 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4588 newNetwork.name() +
4589 " without updating mNetworkForRequestId or factories!");
4590 }
4591 }
4592 // TODO: technically, sending CALLBACK_LOST here is
4593 // incorrect if nri is a request (not a listen) and there
4594 // is a replacement network currently connected that can
4595 // satisfy it. However, the only capability that can both
4596 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4597 // so this code is only incorrect for a network that loses
4598 // the TRUSTED capability, which is a rare case.
4599 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004600 }
4601 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004602 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004603 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004604 if (nai.lingering) {
4605 // Already lingered. Nothing to do. This can only happen if "nai" is in
4606 // "affectedNetworks" twice. The reasoning being that to get added to
4607 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4608 // (i.e. not lingered) so it could have only been lingered by this loop.
4609 // unneeded(nai) will be false and we'll call unlinger() below which would
4610 // be bad, so handle it here.
4611 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004612 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004613 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004614 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004615 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004616 }
4617 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004618 if (isNewDefault) {
4619 // Notify system services that this network is up.
4620 makeDefault(newNetwork);
4621 synchronized (ConnectivityService.this) {
4622 // have a new default network, release the transition wakelock in
4623 // a second if it's held. The second pause is to allow apps
4624 // to reconnect over the new network
4625 if (mNetTransitionWakeLock.isHeld()) {
4626 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4627 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4628 mNetTransitionWakeLockSerialNumber, 0),
4629 1000);
4630 }
4631 }
4632 }
4633
4634 // do this after the default net is switched, but
4635 // before LegacyTypeTracker sends legacy broadcasts
4636 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4637
4638 if (isNewDefault) {
4639 // Maintain the illusion: since the legacy API only
4640 // understands one network at a time, we must pretend
4641 // that the current default network disconnected before
4642 // the new one connected.
4643 if (oldDefaultNetwork != null) {
4644 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4645 oldDefaultNetwork, true);
4646 }
4647 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4648 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4649 notifyLockdownVpn(newNetwork);
4650 }
4651
Robert Greenwalt7b816022014-04-18 15:25:25 -07004652 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004653 // Notify battery stats service about this network, both the normal
4654 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004655 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004656 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004657 final IBatteryStats bs = BatteryStatsService.getService();
4658 final int type = newNetwork.networkInfo.getType();
4659
4660 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4661 bs.noteNetworkInterfaceType(baseIface, type);
4662 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4663 final String stackedIface = stacked.getInterfaceName();
4664 bs.noteNetworkInterfaceType(stackedIface, type);
4665 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4666 }
4667 } catch (RemoteException ignored) {
4668 }
4669
Robert Greenwalt152ed372014-12-17 17:19:53 -08004670 // This has to happen after the notifyNetworkCallbacks as that tickles each
4671 // ConnectivityManager instance so that legacy requests correctly bind dns
4672 // requests to this network. The legacy users are listening for this bcast
4673 // and will generally do a dns request so they can ensureRouteToHost and if
4674 // they do that before the callbacks happen they'll use the default network.
4675 //
4676 // TODO: Is there still a race here? We send the broadcast
4677 // after sending the callback, but if the app can receive the
4678 // broadcast before the callback, it might still break.
4679 //
4680 // This *does* introduce a race where if the user uses the new api
4681 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4682 // they may get old info. Reverse this after the old startUsing api is removed.
4683 // This is on top of the multiple intent sequencing referenced in the todo above.
4684 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4685 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4686 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4687 // legacy type tracker filters out repeat adds
4688 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4689 }
4690 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004691
4692 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4693 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4694 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4695 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4696 if (newNetwork.isVPN()) {
4697 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4698 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004699 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004700 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4701 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004702 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004703 if (DBG) log("Reaping " + nai.name());
4704 teardownUnneededNetwork(nai);
4705 }
4706 }
4707 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004708 }
4709
Paul Jensen1c7ba022015-06-16 14:27:36 -04004710 /**
4711 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4712 * being disconnected.
4713 * @param changed If only one Network's score or capabilities have been modified since the last
4714 * time this function was called, pass this Network in this argument, otherwise pass
4715 * null.
4716 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4717 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4718 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4719 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4720 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004721 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004722 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004723 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4724 // to avoid the slowness. It is not simply enough to process just "changed", for
4725 // example in the case where "changed"'s score decreases and another network should begin
4726 // satifying a NetworkRequest that "changed" currently satisfies.
4727
4728 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4729 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4730 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004731 if (changed != null && oldScore < changed.getCurrentScore()) {
4732 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004733 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004734 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4735 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4736 // Rematch higher scoring networks first to prevent requests first matching a lower
4737 // scoring network and then a higher scoring network, which could produce multiple
4738 // callbacks and inadvertently unlinger networks.
4739 Arrays.sort(nais);
4740 for (NetworkAgentInfo nai : nais) {
4741 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004742 // Only reap the last time through the loop. Reaping before all rematching
4743 // is complete could incorrectly teardown a network that hasn't yet been
4744 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004745 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004746 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004747 }
4748 }
4749 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004750
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004751 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004752 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004753 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004754 // For now only update icons for default connection.
4755 // TODO: Update WiFi and cellular icons separately. b/17237507
4756 if (!isDefaultNetwork(nai)) return;
4757
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004758 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004759 // Don't repeat publish.
4760 if (newInetCondition == mDefaultInetConditionPublished) return;
4761
4762 mDefaultInetConditionPublished = newInetCondition;
4763 sendInetConditionBroadcast(nai.networkInfo);
4764 }
4765
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004766 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4767 if (mLockdownTracker != null) {
4768 if (nai != null && nai.isVPN()) {
4769 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4770 } else {
4771 mLockdownTracker.onNetworkInfoChanged();
4772 }
4773 }
4774 }
4775
Robert Greenwalt7b816022014-04-18 15:25:25 -07004776 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4777 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004778 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004779 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004780 synchronized (networkAgent) {
4781 oldInfo = networkAgent.networkInfo;
4782 networkAgent.networkInfo = newInfo;
4783 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004784 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004785
4786 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004787 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4788 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4789 notifyIfacesChangedForNetworkStats();
4790 } else if (VDBG) log("ignoring duplicate network state non-change");
4791 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004792 return;
4793 }
4794 if (DBG) {
4795 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4796 (oldInfo == null ? "null" : oldInfo.getState()) +
4797 " to " + state);
4798 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004799
Paul Jenseneec75412014-08-04 12:21:19 -04004800 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004801 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004802 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004803 if (networkAgent.isVPN()) {
4804 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004805 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4806 (networkAgent.networkMisc == null ||
4807 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004808 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004809 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4810 networkAgent.networkCapabilities.hasCapability(
4811 NET_CAPABILITY_NOT_RESTRICTED) ?
4812 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004813 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004814 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004815 loge("Error creating network " + networkAgent.network.netId + ": "
4816 + e.getMessage());
4817 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004818 }
Paul Jenseneec75412014-08-04 12:21:19 -04004819 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004820 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004821 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004822
Paul Jensenca8f16a2014-05-09 12:47:55 -04004823 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004824 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004825
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004826 if (networkAgent.isVPN()) {
4827 // Temporarily disable the default proxy (not global).
4828 synchronized (mProxyLock) {
4829 if (!mDefaultProxyDisabled) {
4830 mDefaultProxyDisabled = true;
4831 if (mGlobalProxy == null && mDefaultProxy != null) {
4832 sendProxyBroadcast(null);
4833 }
4834 }
4835 }
4836 // TODO: support proxy per network.
4837 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004838
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004839 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4840 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4841 // capabilities, so it only needs to be done once on initial connect, not every time the
4842 // network's capabilities change. Note that we do this before rematching the network,
4843 // so we could decide to tear it down immediately afterwards. That's fine though - on
4844 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4845 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004846 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004847
Paul Jensen2161a8e2014-09-11 11:00:39 -04004848 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004849 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004850
4851 // This has to happen after matching the requests, because callbacks are just requests.
4852 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004853 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004854 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004855 if (networkAgent.isVPN()) {
4856 synchronized (mProxyLock) {
4857 if (mDefaultProxyDisabled) {
4858 mDefaultProxyDisabled = false;
4859 if (mGlobalProxy == null && mDefaultProxy != null) {
4860 sendProxyBroadcast(mDefaultProxy);
4861 }
4862 }
4863 }
4864 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004865 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4866 state == NetworkInfo.State.SUSPENDED) {
4867 // going into or coming out of SUSPEND: rescore and notify
4868 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004869 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004870 }
4871 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4872 ConnectivityManager.CALLBACK_SUSPENDED :
4873 ConnectivityManager.CALLBACK_RESUMED));
4874 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004875 }
4876 }
4877
Robert Greenwaltac96c522014-06-03 16:43:57 -07004878 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4879 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004880 if (score < 0) {
4881 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4882 "). Bumping score to min of 0");
4883 score = 0;
4884 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004885
Paul Jensen2161a8e2014-09-11 11:00:39 -04004886 final int oldScore = nai.getCurrentScore();
4887 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004888
Paul Jensen85cf78e2015-06-25 13:25:07 -04004889 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004890
Paul Jensenc8b9a742014-09-30 15:37:41 -04004891 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004892 }
4893
Robert Greenwalt9258c642014-03-26 16:47:06 -07004894 // notify only this one new request of the current state
4895 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4896 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4897 // TODO - read state from monitor to decide what to send.
4898// if (nai.networkMonitor.isLingering()) {
4899// notifyType = NetworkCallbacks.LOSING;
4900// } else if (nai.networkMonitor.isEvaluating()) {
4901// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4902// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004903 if (nri.mPendingIntent == null) {
4904 callCallbackForRequest(nri, nai, notifyType);
4905 } else {
4906 sendPendingIntentForRequest(nri, nai, notifyType);
4907 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004908 }
4909
Robert Greenwalt8d482522015-06-24 13:23:42 -07004910 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004911 // The NetworkInfo we actually send out has no bearing on the real
4912 // state of affairs. For example, if the default connection is mobile,
4913 // and a request for HIPRI has just gone away, we need to pretend that
4914 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4915 // the state to DISCONNECTED, even though the network is of type MOBILE
4916 // and is still connected.
4917 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4918 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004919 if (state != DetailedState.DISCONNECTED) {
4920 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004921 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004922 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004923 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004924 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4925 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4926 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4927 if (info.isFailover()) {
4928 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4929 nai.networkInfo.setFailover(false);
4930 }
4931 if (info.getReason() != null) {
4932 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4933 }
4934 if (info.getExtraInfo() != null) {
4935 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4936 }
4937 NetworkAgentInfo newDefaultAgent = null;
4938 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004939 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004940 if (newDefaultAgent != null) {
4941 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4942 newDefaultAgent.networkInfo);
4943 } else {
4944 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4945 }
4946 }
4947 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4948 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004949 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004950 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004951 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004952 }
4953 }
4954 }
4955
Robert Greenwalt7b816022014-04-18 15:25:25 -07004956 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004957 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004958 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004959 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4960 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4961 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004962 if (nri.mPendingIntent == null) {
4963 callCallbackForRequest(nri, networkAgent, notifyType);
4964 } else {
4965 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4966 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004967 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004968 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004969
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004970 private String notifyTypeToName(int notifyType) {
4971 switch (notifyType) {
4972 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4973 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4974 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4975 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4976 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4977 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4978 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4979 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4980 }
4981 return "UNKNOWN";
4982 }
4983
Jeff Sharkey69736342014-12-08 14:50:12 -08004984 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004985 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
4986 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08004987 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004988 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08004989 try {
4990 mStatsService.forceUpdateIfaces();
4991 } catch (Exception ignored) {
4992 }
4993 }
4994
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004995 @Override
4996 public boolean addVpnAddress(String address, int prefixLength) {
4997 throwIfLockdownEnabled();
4998 int user = UserHandle.getUserId(Binder.getCallingUid());
4999 synchronized (mVpns) {
5000 return mVpns.get(user).addAddress(address, prefixLength);
5001 }
5002 }
5003
5004 @Override
5005 public boolean removeVpnAddress(String address, int prefixLength) {
5006 throwIfLockdownEnabled();
5007 int user = UserHandle.getUserId(Binder.getCallingUid());
5008 synchronized (mVpns) {
5009 return mVpns.get(user).removeAddress(address, prefixLength);
5010 }
5011 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005012
5013 @Override
5014 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5015 throwIfLockdownEnabled();
5016 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005017 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005018 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005019 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005020 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005021 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005022 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005023 }
5024 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005025 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005026
5027 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005028 public String getCaptivePortalServerUrl() {
5029 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5030 }
5031
5032 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005033 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5034 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5035 enforceKeepalivePermission();
5036 mKeepaliveTracker.startNattKeepalive(
5037 getNetworkAgentInfoForNetwork(network),
5038 intervalSeconds, messenger, binder,
5039 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5040 }
5041
5042 @Override
5043 public void stopKeepalive(Network network, int slot) {
5044 mHandler.sendMessage(mHandler.obtainMessage(
5045 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5046 }
5047
5048 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005049 public void factoryReset() {
5050 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005051
5052 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5053 return;
5054 }
5055
Robin Lee3b3dd942015-05-12 18:14:58 +01005056 final int userId = UserHandle.getCallingUserId();
5057
Stuart Scottf1fb3972015-04-02 18:00:02 -07005058 // Turn airplane mode off
5059 setAirplaneMode(false);
5060
Stuart Scotte3e314d2015-04-20 14:07:45 -07005061 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5062 // Untether
5063 for (String tether : getTetheredIfaces()) {
5064 untether(tether);
5065 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005066 }
5067
Stuart Scotte3e314d2015-04-20 14:07:45 -07005068 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
5069 // Turn VPN off
5070 VpnConfig vpnConfig = getVpnConfig(userId);
5071 if (vpnConfig != null) {
5072 if (vpnConfig.legacy) {
5073 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5074 } else {
5075 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5076 // in the future without user intervention.
5077 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005078
Stuart Scotte3e314d2015-04-20 14:07:45 -07005079 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
5080 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005081 }
5082 }
5083 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005084
5085 @VisibleForTesting
5086 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5087 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5088 return new NetworkMonitor(context, handler, nai, defaultRequest);
5089 }
5090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005091}