blob: 82a36b4958a6f71f508128cb69b40746a3f4db60 [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;
Pierre Imai55618be2016-02-19 15:25:54 +090074import android.net.metrics.ConnectivityServiceChangeEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080076import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070077import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040078import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070080import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070081import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070082import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.Looper;
84import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070085import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070086import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070087import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070088import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070089import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080090import android.os.ResultReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070092import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040093import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070095import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070096import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070097import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070098import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070099import android.util.LocalLog;
100import android.util.LocalLog.ReadOnlyLocalLog;
101import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800102import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700103import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500104import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700105import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700106import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
Wink Savilleab9321d2013-06-29 21:10:57 -0700108import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400109import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400110import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700111import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700112import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700113import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700114import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800115import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700116import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700117import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700118import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700119import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700120import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400121import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900122import com.android.server.connectivity.KeepaliveTracker;
Erik Kline379747a2015-06-05 17:47:34 +0900123import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900124import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700125import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400126import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400127import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700128import com.android.server.connectivity.PermissionMonitor;
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
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900357 /** Handler thread used for both of the handlers below. */
358 @VisibleForTesting
359 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700360 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700361 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700362 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700363 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700364
Mike Lockwood0f79b542009-08-14 14:18:49 -0400365 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800366 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400367
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700368 private PowerManager.WakeLock mNetTransitionWakeLock;
369 private String mNetTransitionWakeLockCausedBy = "";
370 private int mNetTransitionWakeLockSerialNumber;
371 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800372 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700373
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700374 // used in DBG mode to track inet condition reports
375 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
376 private ArrayList mInetLog;
377
Robert Greenwalt434203a2010-10-11 16:00:27 -0700378 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400379 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700380 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700381 private boolean mDefaultProxyDisabled = false;
382
Robert Greenwalt434203a2010-10-11 16:00:27 -0700383 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400384 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700385
Jason Monk602b2322013-07-03 17:04:33 -0400386 private PacManager mPacManager = null;
387
Erik Klineda4bfa82015-04-30 12:58:40 +0900388 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700389
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400390 private UserManager mUserManager;
391
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700392 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700393 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700394
Robert Greenwalt50393202011-06-21 17:26:14 -0700395 // the set of network types that can only be enabled by system/sig apps
396 List mProtectedNetworks;
397
John Spurlockbf991a82013-06-24 14:20:23 -0400398 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700399
Wink Savilleab9321d2013-06-29 21:10:57 -0700400 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400401
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900402 private KeepaliveTracker mKeepaliveTracker;
403
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700404 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
405 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700406 private final static int MAX_NET_ID = 65535;
407 private int mNextNetId = MIN_NET_ID;
408
Robert Greenwalt34524f02014-05-18 16:22:10 -0700409 // sequence number of NetworkRequests
410 private int mNextNetworkRequestId = 1;
411
Erik Kline7523eb32015-07-09 18:24:03 +0900412 // NetworkRequest activity String log entries.
413 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
414 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
415
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700416 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
417 private static final int MAX_VALIDATION_LOGS = 10;
418 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
419 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
420
421 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
422 synchronized(mValidationLogs) {
423 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
424 mValidationLogs.removeLast();
425 }
426 mValidationLogs.addFirst(new Pair(network, log));
427 }
428 }
429
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700430 /**
431 * Implements support for the legacy "one network per network type" model.
432 *
433 * We used to have a static array of NetworkStateTrackers, one for each
434 * network type, but that doesn't work any more now that we can have,
435 * for example, more that one wifi network. This class stores all the
436 * NetworkAgentInfo objects that support a given type, but the legacy
437 * API will only see the first one.
438 *
439 * It serves two main purposes:
440 *
441 * 1. Provide information about "the network for a given type" (since this
442 * API only supports one).
443 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
444 * the first network for a given type changes, or if the default network
445 * changes.
446 */
447 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900448
Joe Onorato12acbd72016-02-01 17:49:31 -0800449 private static final boolean DBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900450 private static final boolean VDBG = false;
451 private static final String TAG = "CSLegacyTypeTracker";
452
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700453 /**
454 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
455 * Each list holds references to all NetworkAgentInfos that are used to
456 * satisfy requests for that network type.
457 *
458 * This array is built out at startup such that an unsupported network
459 * doesn't get an ArrayList instance, making this a tristate:
460 * unsupported, supported but not active and active.
461 *
462 * The actual lists are populated when we scan the network types that
463 * are supported on this device.
464 */
465 private ArrayList<NetworkAgentInfo> mTypeLists[];
466
467 public LegacyTypeTracker() {
468 mTypeLists = (ArrayList<NetworkAgentInfo>[])
469 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
470 }
471
472 public void addSupportedType(int type) {
473 if (mTypeLists[type] != null) {
474 throw new IllegalStateException(
475 "legacy list for type " + type + "already initialized");
476 }
477 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
478 }
479
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700480 public boolean isTypeSupported(int type) {
481 return isNetworkTypeValid(type) && mTypeLists[type] != null;
482 }
483
484 public NetworkAgentInfo getNetworkForType(int type) {
485 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
486 return mTypeLists[type].get(0);
487 } else {
488 return null;
489 }
490 }
491
Robert Greenwalt8d482522015-06-24 13:23:42 -0700492 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900493 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900494 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700495 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900496 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900497 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900498 }
499 }
500
501 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700502 public void add(int type, NetworkAgentInfo nai) {
503 if (!isTypeSupported(type)) {
504 return; // Invalid network type.
505 }
506 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
507
508 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
509 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700510 return;
511 }
512
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900513 list.add(nai);
514
515 // 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 +0900516 final boolean isDefaultNetwork = isDefaultNetwork(nai);
517 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700518 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
519 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700520 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700521 }
522
Lorenzo Colittia793a672014-07-31 23:20:17 +0900523 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900524 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900525 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
526 if (list == null || list.isEmpty()) {
527 return;
528 }
529
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900530 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900531
532 if (!list.remove(nai)) {
533 return;
534 }
535
Robert Greenwalt8d482522015-06-24 13:23:42 -0700536 final DetailedState state = DetailedState.DISCONNECTED;
537
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900538 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700539 maybeLogBroadcast(nai, state, type, wasDefault);
540 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900541 }
542
543 if (!list.isEmpty() && wasFirstNetwork) {
544 if (DBG) log("Other network available for type " + type +
545 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900546 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700547 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
548 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900549 }
550 }
551
552 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900553 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
554 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700555 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900556 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700557 }
558 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700559
Robert Greenwalt8d482522015-06-24 13:23:42 -0700560 // send out another legacy broadcast - currently only used for suspend/unsuspend
561 // toggle
562 public void update(NetworkAgentInfo nai) {
563 final boolean isDefault = isDefaultNetwork(nai);
564 final DetailedState state = nai.networkInfo.getDetailedState();
565 for (int type = 0; type < mTypeLists.length; type++) {
566 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700567 final boolean contains = (list != null && list.contains(nai));
Robert Greenwalt8d482522015-06-24 13:23:42 -0700568 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700569 if (isFirst || (contains && isDefault)) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700570 maybeLogBroadcast(nai, state, type, isDefault);
571 sendLegacyNetworkBroadcast(nai, state, type);
572 }
573 }
574 }
575
Lorenzo Colittia793a672014-07-31 23:20:17 +0900576 private String naiToString(NetworkAgentInfo nai) {
577 String name = (nai != null) ? nai.name() : "null";
578 String state = (nai.networkInfo != null) ?
579 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
580 "???/???";
581 return name + " " + state;
582 }
583
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700584 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900585 pw.println("mLegacyTypeTracker:");
586 pw.increaseIndent();
587 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700588 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900589 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700590 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900591 pw.println();
592 pw.println("Current state:");
593 pw.increaseIndent();
594 for (int type = 0; type < mTypeLists.length; type++) {
595 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
596 for (NetworkAgentInfo nai : mTypeLists[type]) {
597 pw.println(type + " " + naiToString(nai));
598 }
599 }
600 pw.decreaseIndent();
601 pw.decreaseIndent();
602 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700603 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900604
605 // This class needs its own log method because it has a different TAG.
606 private void log(String s) {
607 Slog.d(TAG, s);
608 }
609
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700610 }
611 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
612
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900613 @VisibleForTesting
614 protected HandlerThread createHandlerThread() {
615 return new HandlerThread("ConnectivityServiceThread");
616 }
617
Jeff Sharkey899223b2012-08-04 15:24:58 -0700618 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700619 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800620 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800621
Erik Klineda4bfa82015-04-30 12:58:40 +0900622 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900623 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
Erik Kline371c7b72016-03-22 17:04:20 +0900624 new Binder(), NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +0900625 mNetworkRequests.put(mDefaultRequest, defaultNRI);
626 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900627
628 mDefaultMobileDataRequest = createInternetRequestForTransport(
629 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700630
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900631 mHandlerThread = createHandlerThread();
632 mHandlerThread.start();
633 mHandler = new InternalHandler(mHandlerThread.getLooper());
634 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700635
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800636 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800637 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
638 String id = Settings.Secure.getString(context.getContentResolver(),
639 Settings.Secure.ANDROID_ID);
640 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700641 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800642 SystemProperties.set("net.hostname", name);
643 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800644 }
645
Jeremy Joslin79294842014-12-03 17:15:28 -0800646 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
647 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
648
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700649 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700650 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800651 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700652 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700653 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700654 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700655
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700656 try {
657 mPolicyManager.registerListener(mPolicyListener);
658 } catch (RemoteException e) {
659 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700660 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700661 }
662
663 final PowerManager powerManager = (PowerManager) context.getSystemService(
664 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700665 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
666 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
667 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800668 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700669
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700670 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700671
Wink Saville51f456f2013-04-23 14:26:51 -0700672 // TODO: What is the "correct" way to do determine if this is a wifi only device?
673 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
674 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700675 String[] naStrings = context.getResources().getStringArray(
676 com.android.internal.R.array.networkAttributes);
677 for (String naString : naStrings) {
678 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700679 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700680 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700681 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800682 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700683 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700684 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700685 }
Wink Saville51f456f2013-04-23 14:26:51 -0700686 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
687 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
688 n.type);
689 continue;
690 }
Wink Saville975c8482011-04-07 14:23:45 -0700691 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800692 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700693 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700694 continue;
695 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700696 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700697
Wink Saville975c8482011-04-07 14:23:45 -0700698 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700699 mNetworksDefined++;
700 } catch(Exception e) {
701 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700702 }
703 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700704
705 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
706 if (mNetConfigs[TYPE_VPN] == null) {
707 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
708 // don't need to add TYPE_VPN to mNetConfigs.
709 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
710 mNetworksDefined++; // used only in the log() statement below.
711 }
712
Wink Saville5e56bc52013-07-29 15:00:57 -0700713 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700714
Robert Greenwalt50393202011-06-21 17:26:14 -0700715 mProtectedNetworks = new ArrayList<Integer>();
716 int[] protectedNetworks = context.getResources().getIntArray(
717 com.android.internal.R.array.config_protectedNetworks);
718 for (int p : protectedNetworks) {
719 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
720 mProtectedNetworks.add(p);
721 } else {
722 if (DBG) loge("Ignoring protectedNetwork " + p);
723 }
724 }
725
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700726 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
727 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700728
Jeremy Kleinfa8712b2016-01-26 11:10:55 -0800729 mTethering = new Tethering(mContext, mNetd, statsService);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800730
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700731 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
732
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700733 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700734 IntentFilter intentFilter = new IntentFilter();
735 intentFilter.addAction(Intent.ACTION_USER_STARTING);
736 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700737 intentFilter.addAction(Intent.ACTION_USER_ADDED);
738 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000739 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700740 mContext.registerReceiverAsUser(
741 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900742
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700743 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700744 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700745 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700746 } catch (RemoteException e) {
747 loge("Error registering observer :" + e);
748 }
749
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700750 if (DBG) {
751 mInetLog = new ArrayList();
752 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700753
Erik Klineda4bfa82015-04-30 12:58:40 +0900754 mSettingsObserver = new SettingsObserver(mContext, mHandler);
755 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800756
John Spurlockbf991a82013-06-24 14:20:23 -0400757 mDataConnectionStats = new DataConnectionStats(mContext);
758 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400759
Jason Monkdecd2952013-10-10 14:02:51 -0400760 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700761
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400762 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900763
764 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700766
Erik Klineda4bfa82015-04-30 12:58:40 +0900767 private NetworkRequest createInternetRequestForTransport(int transportType) {
768 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900769 netCap.addCapability(NET_CAPABILITY_INTERNET);
770 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900771 if (transportType > -1) {
772 netCap.addTransportType(transportType);
773 }
774 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
775 }
776
777 private void handleMobileDataAlwaysOn() {
778 final boolean enable = (Settings.Global.getInt(
779 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
780 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
781 if (enable == isEnabled) {
782 return; // Nothing to do.
783 }
784
785 if (enable) {
786 handleRegisterNetworkRequest(new NetworkRequestInfo(
Erik Kline371c7b72016-03-22 17:04:20 +0900787 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestType.REQUEST));
Erik Klineda4bfa82015-04-30 12:58:40 +0900788 } else {
789 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
790 }
791 }
792
793 private void registerSettingsCallbacks() {
794 // Watch for global HTTP proxy changes.
795 mSettingsObserver.observe(
796 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
797 EVENT_APPLY_GLOBAL_HTTP_PROXY);
798
799 // Watch for whether or not to keep mobile data always on.
800 mSettingsObserver.observe(
801 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
802 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
803 }
804
Robert Greenwalt34524f02014-05-18 16:22:10 -0700805 private synchronized int nextNetworkRequestId() {
806 return mNextNetworkRequestId++;
807 }
808
Paul Jensen67b0b072015-06-10 11:22:17 -0400809 @VisibleForTesting
810 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400811 synchronized (mNetworkForNetId) {
812 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
813 int netId = mNextNetId;
814 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
815 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500816 if (!mNetIdInUse.get(netId)) {
817 mNetIdInUse.put(netId, true);
818 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400819 }
820 }
821 }
822 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700823 }
824
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800825 private NetworkState getFilteredNetworkState(int networkType, int uid) {
826 NetworkInfo info = null;
827 LinkProperties lp = null;
828 NetworkCapabilities nc = null;
829 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800830 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800831
832 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
833 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
834 if (nai != null) {
835 synchronized (nai) {
836 info = new NetworkInfo(nai.networkInfo);
837 lp = new LinkProperties(nai.linkProperties);
838 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400839 // Network objects are outwardly immutable so there is no point to duplicating.
840 // Duplicating also precludes sharing socket factories and connection pools.
841 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800842 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800843 }
844 info.setType(networkType);
845 } else {
846 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
847 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
848 info.setIsAvailable(true);
849 lp = new LinkProperties();
850 nc = new NetworkCapabilities();
851 network = null;
852 }
853 info = getFilteredNetworkInfo(info, lp, uid);
854 }
855
Jeff Sharkey32566012014-12-02 18:30:14 -0800856 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400857 }
858
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800859 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
860 if (network == null) {
861 return null;
862 }
863 synchronized (mNetworkForNetId) {
864 return mNetworkForNetId.get(network.netId);
865 }
866 };
867
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900868 private Network[] getVpnUnderlyingNetworks(int uid) {
869 if (!mLockdownEnabled) {
870 int user = UserHandle.getUserId(uid);
871 synchronized (mVpns) {
872 Vpn vpn = mVpns.get(user);
873 if (vpn != null && vpn.appliesToUid(uid)) {
874 return vpn.getUnderlyingNetworks();
875 }
876 }
877 }
878 return null;
879 }
880
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800881 private NetworkState getUnfilteredActiveNetworkState(int uid) {
882 NetworkInfo info = null;
883 LinkProperties lp = null;
884 NetworkCapabilities nc = null;
885 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800886 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800887
Paul Jensen85cf78e2015-06-25 13:25:07 -0400888 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800889
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900890 final Network[] networks = getVpnUnderlyingNetworks(uid);
891 if (networks != null) {
892 // getUnderlyingNetworks() returns:
893 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
894 // empty array => the VPN explicitly said "no default network".
895 // non-empty array => the VPN specified one or more default networks; we use the
896 // first one.
897 if (networks.length > 0) {
898 nai = getNetworkAgentInfoForNetwork(networks[0]);
899 } else {
900 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800901 }
902 }
903
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800904 if (nai != null) {
905 synchronized (nai) {
906 info = new NetworkInfo(nai.networkInfo);
907 lp = new LinkProperties(nai.linkProperties);
908 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400909 // Network objects are outwardly immutable so there is no point to duplicating.
910 // Duplicating also precludes sharing socket factories and connection pools.
911 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800912 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800913 }
914 }
915
Jeff Sharkey32566012014-12-02 18:30:14 -0800916 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400917 }
918
919 /**
920 * Check if UID should be blocked from using the network with the given LinkProperties.
921 */
922 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700923 final boolean networkCostly;
924 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700925
Robert Greenwalt12e67352014-05-13 21:41:06 -0700926 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700927 synchronized (mRulesLock) {
928 networkCostly = mMeteredIfaces.contains(iface);
929 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700930 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700931
Jeff Sharkeydc988062015-09-14 10:09:47 -0700932 if (uidRules == RULE_REJECT_ALL) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700933 return true;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700934 } else if ((uidRules == RULE_REJECT_METERED) && networkCostly) {
935 return true;
936 } else {
937 return false;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700938 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700939 }
940
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900941 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
942 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) return;
943 boolean removed = false;
944 boolean added = false;
945 synchronized (mBlockedAppUids) {
946 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
947 added = true;
948 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
949 removed = true;
950 }
951 }
952 if (added) log("Returning blocked NetworkInfo to uid=" + uid);
953 else if (removed) log("Returning unblocked NetworkInfo to uid=" + uid);
954 }
955
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700956 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700957 * Return a filtered {@link NetworkInfo}, potentially marked
958 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800959 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700960 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800961 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
962 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400963 // network is blocked; clone and override state
964 info = new NetworkInfo(info);
965 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700966 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800967 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700968 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900969 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700970 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700971 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700972 }
973
974 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 * Return NetworkInfo for the active (i.e., connected) network interface.
976 * It is assumed that at most one network is active at a time. If more
977 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700978 * @return the info for the active network, or {@code null} if none is
979 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700981 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700983 enforceAccessPermission();
984 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800985 NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900986 NetworkInfo ni = getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
987 maybeLogBlockedNetworkInfo(ni, uid);
988 return ni;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 }
990
Paul Jensen31a94f42015-02-13 14:18:39 -0500991 @Override
992 public Network getActiveNetwork() {
993 enforceAccessPermission();
994 final int uid = Binder.getCallingUid();
995 final int user = UserHandle.getUserId(uid);
996 int vpnNetId = NETID_UNSET;
997 synchronized (mVpns) {
998 final Vpn vpn = mVpns.get(user);
999 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1000 }
1001 NetworkAgentInfo nai;
1002 if (vpnNetId != NETID_UNSET) {
1003 synchronized (mNetworkForNetId) {
1004 nai = mNetworkForNetId.get(vpnNetId);
1005 }
1006 if (nai != null) return nai.network;
1007 }
1008 nai = getDefaultNetwork();
1009 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
1010 return nai != null ? nai.network : null;
1011 }
1012
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001013 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1014 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001015 final int uid = Binder.getCallingUid();
1016 NetworkState state = getUnfilteredActiveNetworkState(uid);
1017 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001018 }
1019
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001020 @Override
1021 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1022 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001023 NetworkState state = getUnfilteredActiveNetworkState(uid);
1024 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001025 }
1026
1027 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 public NetworkInfo getNetworkInfo(int networkType) {
1029 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001030 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001031 if (getVpnUnderlyingNetworks(uid) != null) {
1032 // A VPN is active, so we may need to return one of its underlying networks. This
1033 // information is not available in LegacyTypeTracker, so we have to get it from
1034 // getUnfilteredActiveNetworkState.
1035 NetworkState state = getUnfilteredActiveNetworkState(uid);
1036 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1037 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1038 }
1039 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001040 NetworkState state = getFilteredNetworkState(networkType, uid);
1041 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 }
1043
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001044 @Override
1045 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1046 enforceAccessPermission();
1047 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001048 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001049 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1050 if (nai != null) {
1051 synchronized (nai) {
1052 info = new NetworkInfo(nai.networkInfo);
1053 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001054 }
1055 }
1056 return info;
1057 }
1058
1059 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 public NetworkInfo[] getAllNetworkInfo() {
1061 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001062 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001063 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1064 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001065 NetworkInfo info = getNetworkInfo(networkType);
1066 if (info != null) {
1067 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001070 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 }
1072
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001073 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001074 public Network getNetworkForType(int networkType) {
1075 enforceAccessPermission();
1076 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001077 NetworkState state = getFilteredNetworkState(networkType, uid);
1078 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1079 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001080 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001081 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001082 }
1083
1084 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001085 public Network[] getAllNetworks() {
1086 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001087 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001088 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001089 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001090 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001091 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001092 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001093 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001094 }
1095
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001096 @Override
1097 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1098 // The basic principle is: if an app's traffic could possibly go over a
1099 // network, without the app doing anything multinetwork-specific,
1100 // (hence, by "default"), then include that network's capabilities in
1101 // the array.
1102 //
1103 // In the normal case, app traffic only goes over the system's default
1104 // network connection, so that's the only network returned.
1105 //
1106 // With a VPN in force, some app traffic may go into the VPN, and thus
1107 // over whatever underlying networks the VPN specifies, while other app
1108 // traffic may go over the system default network (e.g.: a split-tunnel
1109 // VPN, or an app disallowed by the VPN), so the set of networks
1110 // returned includes the VPN's underlying networks and the system
1111 // default.
1112 enforceAccessPermission();
1113
1114 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1115
1116 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001117 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001118 if (nc != null) {
1119 result.put(nai.network, nc);
1120 }
1121
1122 if (!mLockdownEnabled) {
1123 synchronized (mVpns) {
1124 Vpn vpn = mVpns.get(userId);
1125 if (vpn != null) {
1126 Network[] networks = vpn.getUnderlyingNetworks();
1127 if (networks != null) {
1128 for (Network network : networks) {
1129 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001130 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001131 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001132 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001133 }
1134 }
1135 }
1136 }
1137 }
1138 }
1139
1140 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1141 out = result.values().toArray(out);
1142 return out;
1143 }
1144
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001145 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001146 public boolean isNetworkSupported(int networkType) {
1147 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001148 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001149 }
1150
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001151 /**
1152 * Return LinkProperties for the active (i.e., connected) default
1153 * network interface. It is assumed that at most one default network
1154 * is active at a time. If more than one is active, it is indeterminate
1155 * which will be returned.
1156 * @return the ip properties for the active network, or {@code null} if
1157 * none is active
1158 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001159 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001160 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001161 enforceAccessPermission();
1162 final int uid = Binder.getCallingUid();
1163 NetworkState state = getUnfilteredActiveNetworkState(uid);
1164 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001165 }
1166
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001167 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001168 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001169 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001170 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1171 if (nai != null) {
1172 synchronized (nai) {
1173 return new LinkProperties(nai.linkProperties);
1174 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001175 }
1176 return null;
1177 }
1178
Robert Greenwalt12e67352014-05-13 21:41:06 -07001179 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001180 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001181 public LinkProperties getLinkProperties(Network network) {
1182 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001183 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001184 if (nai != null) {
1185 synchronized (nai) {
1186 return new LinkProperties(nai.linkProperties);
1187 }
1188 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001189 return null;
1190 }
1191
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001192 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001193 if (nai != null) {
1194 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001195 if (nai.networkCapabilities != null) {
1196 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001197 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001198 }
1199 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001200 return null;
1201 }
1202
1203 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001204 public NetworkCapabilities getNetworkCapabilities(Network network) {
1205 enforceAccessPermission();
1206 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1207 }
1208
1209 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001210 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001211 // Require internal since we're handing out IMSI details
1212 enforceConnectivityInternalPermission();
1213
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001214 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001215 for (Network network : getAllNetworks()) {
1216 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1217 if (nai != null) {
1218 synchronized (nai) {
1219 final String subscriberId = (nai.networkMisc != null)
1220 ? nai.networkMisc.subscriberId : null;
1221 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1222 nai.networkCapabilities, network, subscriberId, null));
1223 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001224 }
1225 }
1226 return result.toArray(new NetworkState[result.size()]);
1227 }
1228
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001229 @Override
1230 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1231 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001232 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001233 final long token = Binder.clearCallingIdentity();
1234 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001235 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1236 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001237 try {
1238 return mPolicyManager.getNetworkQuotaInfo(state);
1239 } catch (RemoteException e) {
1240 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001241 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001242 return null;
1243 } finally {
1244 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001245 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001246 }
1247
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001248 @Override
1249 public boolean isActiveNetworkMetered() {
1250 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001251 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001252 final long token = Binder.clearCallingIdentity();
1253 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001254 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001255 } finally {
1256 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001257 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001258 }
1259
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001260 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1261 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1262 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001263 try {
1264 return mPolicyManager.isNetworkMetered(state);
1265 } catch (RemoteException e) {
1266 }
1267 }
1268 return false;
1269 }
1270
Jeff Sharkey216c1812012-08-05 14:29:23 -07001271 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1272 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001273 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001274 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001275 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001276 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001277 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001278
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001279 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 * Ensure that a network route exists to deliver traffic to the specified
1281 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001282 * @param networkType the type of the network over which traffic to the
1283 * specified host is to be routed
1284 * @param hostAddress the IP address of the host to which the route is
1285 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 * @return {@code true} on success, {@code false} on failure
1287 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001288 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001290 if (mProtectedNetworks.contains(networkType)) {
1291 enforceConnectivityInternalPermission();
1292 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001293
Chad Brubakerc0234532014-02-14 13:24:29 -08001294 InetAddress addr;
1295 try {
1296 addr = InetAddress.getByAddress(hostAddress);
1297 } catch (UnknownHostException e) {
1298 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1299 return false;
1300 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001303 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 return false;
1305 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001306
1307 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1308 if (nai == null) {
1309 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1310 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1311 } else {
1312 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1313 }
1314 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001315 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001316
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001317 DetailedState netState;
1318 synchronized (nai) {
1319 netState = nai.networkInfo.getDetailedState();
1320 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001321
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001322 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001323 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001324 log("requestRouteToHostAddress on down network "
1325 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001326 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001327 }
1328 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001330
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001331 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001332 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001333 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001334 LinkProperties lp;
1335 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001336 synchronized (nai) {
1337 lp = nai.linkProperties;
1338 netId = nai.network.netId;
1339 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001340 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001341 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1342 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001343 } finally {
1344 Binder.restoreCallingIdentity(token);
1345 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001346 }
1347
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001348 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001349 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001350 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001351 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001352 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001353 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001354 if (bestRoute.getGateway().equals(addr)) {
1355 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001356 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001357 } else {
1358 // if we will connect to this through another route, add a direct route
1359 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001360 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001361 }
1362 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001363 if (DBG) log("Adding legacy route " + bestRoute +
1364 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001365 try {
1366 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1367 } catch (Exception e) {
1368 // never crash - catch them all
1369 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001370 return false;
1371 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001372 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 }
1374
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001375 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1376 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001377 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001378 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001379 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001380 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001381 }
1382
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001383 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001384 // skip update when we've already applied rules
1385 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1386 if (oldRules == uidRules) return;
1387
1388 mUidRules.put(uid, uidRules);
1389 }
1390
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001391 // TODO: notify UID when it has requested targeted updates
1392 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001393
1394 @Override
1395 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001396 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001397 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001398 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001399 }
1400
1401 synchronized (mRulesLock) {
1402 mMeteredIfaces.clear();
1403 for (String iface : meteredIfaces) {
1404 mMeteredIfaces.add(iface);
1405 }
1406 }
1407 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001408
1409 @Override
1410 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1411 // caller is NPMS, since we only register with them
1412 if (LOGD_RULES) {
1413 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1414 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001415 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001416 };
1417
Robin Lee3b3dd942015-05-12 18:14:58 +01001418 /**
1419 * Require that the caller is either in the same user or has appropriate permission to interact
1420 * across users.
1421 *
1422 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1423 */
1424 private void enforceCrossUserPermission(int userId) {
1425 if (userId == UserHandle.getCallingUserId()) {
1426 // Not a cross-user call.
1427 return;
1428 }
1429 mContext.enforceCallingOrSelfPermission(
1430 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1431 "ConnectivityService");
1432 }
1433
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001434 private void enforceInternetPermission() {
1435 mContext.enforceCallingOrSelfPermission(
1436 android.Manifest.permission.INTERNET,
1437 "ConnectivityService");
1438 }
1439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001441 mContext.enforceCallingOrSelfPermission(
1442 android.Manifest.permission.ACCESS_NETWORK_STATE,
1443 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 }
1445
1446 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001447 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 }
1449
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001450 private void enforceTetherAccessPermission() {
1451 mContext.enforceCallingOrSelfPermission(
1452 android.Manifest.permission.ACCESS_NETWORK_STATE,
1453 "ConnectivityService");
1454 }
1455
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001456 private void enforceConnectivityInternalPermission() {
1457 mContext.enforceCallingOrSelfPermission(
1458 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1459 "ConnectivityService");
1460 }
1461
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001462 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001463 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001464 }
1465
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001466 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001467 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001468 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001469 }
1470
1471 private void sendInetConditionBroadcast(NetworkInfo info) {
1472 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1473 }
1474
Wink Saville628b0852011-08-04 15:01:58 -07001475 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001476 if (mLockdownTracker != null) {
1477 info = mLockdownTracker.augmentNetworkInfo(info);
1478 }
1479
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001480 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001481 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001482 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 if (info.isFailover()) {
1484 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1485 info.setFailover(false);
1486 }
1487 if (info.getReason() != null) {
1488 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1489 }
1490 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001491 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1492 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001494 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001495 return intent;
1496 }
1497
1498 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1499 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1500 }
1501
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001502 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001503 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1504 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1505 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001506 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001507 final long ident = Binder.clearCallingIdentity();
1508 try {
1509 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1510 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1511 } finally {
1512 Binder.restoreCallingIdentity(ident);
1513 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001514 }
1515
Mike Lockwood0f79b542009-08-14 14:18:49 -04001516 private void sendStickyBroadcast(Intent intent) {
1517 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001518 if (!mSystemReady) {
1519 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001520 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001521 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001522 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001523 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001524 }
1525
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001526 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001527 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001528 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001529 final NetworkInfo ni = intent.getParcelableExtra(
1530 ConnectivityManager.EXTRA_NETWORK_INFO);
1531 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1532 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1533 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001534 } else {
1535 BroadcastOptions opts = BroadcastOptions.makeBasic();
1536 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1537 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001538 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001539 final IBatteryStats bs = BatteryStatsService.getService();
1540 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001541 bs.noteConnectivityChanged(intent.getIntExtra(
1542 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1543 ni != null ? ni.getState().toString() : "?");
1544 } catch (RemoteException e) {
1545 }
1546 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001547 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001548 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001549 } finally {
1550 Binder.restoreCallingIdentity(ident);
1551 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001552 }
1553 }
1554
1555 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001556 loadGlobalProxy();
1557
Mike Lockwood0f79b542009-08-14 14:18:49 -04001558 synchronized(this) {
1559 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001560 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001561 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001562 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001563 }
1564 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001565 // load the global proxy at startup
1566 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001567
Robin Lee244ce8e2016-01-05 18:03:46 +00001568 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1569 // for user to unlock device too.
1570 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001571
Erik Klineda4bfa82015-04-30 12:58:40 +09001572 // Configure whether mobile data is always on.
1573 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1574
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001575 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001576
1577 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 }
1579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001581 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001582 *
1583 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001584 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001585 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001586 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1587 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001588
1589 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001590 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001591
Robert Greenwalt7b816022014-04-18 15:25:25 -07001592 if (networkAgent.networkCapabilities.hasTransport(
1593 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001594 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1595 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001596 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001597 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001598 } else if (networkAgent.networkCapabilities.hasTransport(
1599 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001600 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1601 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001602 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001603 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001604 } else {
1605 // do not track any other networks
1606 timeout = 0;
1607 }
1608
Robert Greenwalt7b816022014-04-18 15:25:25 -07001609 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001610 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001611 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001612 } catch (Exception e) {
1613 // You shall not crash!
1614 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001615 }
1616 }
1617 }
1618
1619 /**
1620 * Remove data activity tracking when network disconnects.
1621 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001622 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1623 final String iface = networkAgent.linkProperties.getInterfaceName();
1624 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001625
Robert Greenwalt7b816022014-04-18 15:25:25 -07001626 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1627 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001628 try {
1629 // the call fails silently if no idletimer setup for this interface
1630 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001631 } catch (Exception e) {
1632 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001633 }
1634 }
1635 }
1636
1637 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001638 * Reads the network specific MTU size from reources.
1639 * and set it on it's iface.
1640 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001641 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1642 final String iface = newLp.getInterfaceName();
1643 final int mtu = newLp.getMtu();
1644 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1645 if (VDBG) log("identical MTU - not setting");
1646 return;
1647 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001648
Robert Greenwalt43074032014-08-15 17:53:05 -07001649 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001650 loge("Unexpected mtu value: " + mtu + ", " + iface);
1651 return;
1652 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001653
w1997615afd812014-08-05 15:18:11 -07001654 // Cannot set MTU without interface name
1655 if (TextUtils.isEmpty(iface)) {
1656 loge("Setting MTU size with null iface.");
1657 return;
1658 }
1659
Robert Greenwalt7b816022014-04-18 15:25:25 -07001660 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001661 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001662 mNetd.setMtu(iface, mtu);
1663 } catch (Exception e) {
1664 Slog.e(TAG, "exception in setMtu()" + e);
1665 }
1666 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001667
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001668 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001669 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1670
1671 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001672 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001673 protected int getDefaultTcpRwnd() {
1674 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1675 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001676
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001677 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1678 if (isDefaultNetwork(nai) == false) {
1679 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001680 }
1681
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001682 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1683 String[] values = null;
1684 if (tcpBufferSizes != null) {
1685 values = tcpBufferSizes.split(",");
1686 }
1687
1688 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001689 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001690 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1691 values = tcpBufferSizes.split(",");
1692 }
1693
1694 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1695
1696 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001697 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001698
1699 final String prefix = "/sys/kernel/ipv4/tcp_";
1700 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1701 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1702 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1703 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1704 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1705 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1706 mCurrentTcpBufferSizes = tcpBufferSizes;
1707 } catch (IOException e) {
1708 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001709 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001710
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001711 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001712 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001713 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1714 if (rwndValue != 0) {
1715 SystemProperties.set(sysctlKey, rwndValue.toString());
1716 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001717 }
1718
Mattias Falk8b47b362011-08-23 14:15:13 +02001719 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001720 /*
1721 * Tell the VMs to toss their DNS caches
1722 */
1723 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1724 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001725 /*
1726 * Connectivity events can happen before boot has completed ...
1727 */
1728 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001729 final long ident = Binder.clearCallingIdentity();
1730 try {
1731 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1732 } finally {
1733 Binder.restoreCallingIdentity(ident);
1734 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001735 }
1736
Robert Greenwalt562cc542014-05-15 18:07:26 -07001737 @Override
1738 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001739 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1740 NETWORK_RESTORE_DELAY_PROP_NAME);
1741 if(restoreDefaultNetworkDelayStr != null &&
1742 restoreDefaultNetworkDelayStr.length() != 0) {
1743 try {
1744 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1745 } catch (NumberFormatException e) {
1746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001748 // if the system property isn't set, use the value for the apn type
1749 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1750
1751 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1752 (mNetConfigs[networkType] != null)) {
1753 ret = mNetConfigs[networkType].restoreTime;
1754 }
1755 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 }
1757
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001758 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001759 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001760 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001761 }
1762 return false;
1763 }
1764
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001765 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1766 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1767 final long DIAG_TIME_MS = 5000;
1768 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1769 // Start gathering diagnostic information.
1770 netDiags.add(new NetworkDiagnostics(
1771 nai.network,
1772 new LinkProperties(nai.linkProperties), // Must be a copy.
1773 DIAG_TIME_MS));
1774 }
1775
1776 for (NetworkDiagnostics netDiag : netDiags) {
1777 pw.println();
1778 netDiag.waitForMeasurements();
1779 netDiag.dump(pw);
1780 }
1781 }
1782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001784 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1785 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001786 if (mContext.checkCallingOrSelfPermission(
1787 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001789 pw.println("Permission Denial: can't dump ConnectivityService " +
1790 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1791 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 return;
1793 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001794
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001795 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001796 dumpNetworkDiagnostics(pw);
1797 return;
1798 }
Erik Kline379747a2015-06-05 17:47:34 +09001799
Lorenzo Colittie3805462015-06-03 11:18:24 +09001800 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001801 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001802 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001803 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001804 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001805 pw.println();
1806
Paul Jensen85cf78e2015-06-25 13:25:07 -04001807 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001808 pw.print("Active default network: ");
1809 if (defaultNai == null) {
1810 pw.println("none");
1811 } else {
1812 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001814 pw.println();
1815
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001816 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001817 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001818 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1819 pw.println(nai.toString());
1820 pw.increaseIndent();
1821 pw.println("Requests:");
1822 pw.increaseIndent();
1823 for (int i = 0; i < nai.networkRequests.size(); i++) {
1824 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001825 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001826 pw.decreaseIndent();
1827 pw.println("Lingered:");
1828 pw.increaseIndent();
1829 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1830 pw.decreaseIndent();
1831 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001832 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001833 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001834 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001835
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001836 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001837 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001838 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1839 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001840 }
1841 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001842 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001843
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001844 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001845
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001846 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001847 pw.print("mNetTransitionWakeLock: currently " +
1848 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1849 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1850 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1851 } else {
1852 pw.println(", last requested never");
1853 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001854 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001855
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001856 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001857 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001858
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001859 pw.println();
1860 mKeepaliveTracker.dump(pw);
1861
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001862 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001863
Lorenzo Colittie3805462015-06-03 11:18:24 +09001864 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001865 pw.println();
1866 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001867 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001868 for(int i = 0; i < mInetLog.size(); i++) {
1869 pw.println(mInetLog.get(i));
1870 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001871 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001872 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001873
1874 if (argsContain(args, "--short") == false) {
1875 pw.println();
1876 synchronized (mValidationLogs) {
1877 pw.println("mValidationLogs (most recent first):");
1878 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1879 pw.println(p.first);
1880 pw.increaseIndent();
1881 p.second.dump(fd, pw, args);
1882 pw.decreaseIndent();
1883 }
1884 }
Erik Kline7523eb32015-07-09 18:24:03 +09001885
1886 pw.println();
1887 pw.println("mNetworkRequestInfoLogs (most recent first):");
1888 pw.increaseIndent();
1889 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1890 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
1893
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001894 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001895 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001896 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001897 if (officialNai != null && officialNai.equals(nai)) return true;
1898 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001899 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001900 " - " + nai);
1901 }
1902 return false;
1903 }
1904
Paul Jensenc8b9a742014-09-30 15:37:41 -04001905 private boolean isRequest(NetworkRequest request) {
Erik Kline371c7b72016-03-22 17:04:20 +09001906 return mNetworkRequests.get(request).isRequest();
Paul Jensenc8b9a742014-09-30 15:37:41 -04001907 }
1908
Robert Greenwalt42acef32009-08-12 16:08:25 -07001909 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001910 private class NetworkStateTrackerHandler extends Handler {
1911 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001912 super(looper);
1913 }
1914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 @Override
1916 public void handleMessage(Message msg) {
1917 NetworkInfo info;
1918 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001919 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001920 handleAsyncChannelHalfConnect(msg);
1921 break;
1922 }
1923 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1924 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1925 if (nai != null) nai.asyncChannel.disconnect();
1926 break;
1927 }
1928 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1929 handleAsyncChannelDisconnected(msg);
1930 break;
1931 }
1932 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1933 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1934 if (nai == null) {
1935 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1936 } else {
Paul Jensen1c7ba022015-06-16 14:27:36 -04001937 final NetworkCapabilities networkCapabilities =
1938 (NetworkCapabilities)msg.obj;
1939 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1940 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001941 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Paul Jensen1c7ba022015-06-16 14:27:36 -04001942 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09001943 if (nai.created && !nai.networkCapabilities.equalImmutableCapabilities(
1944 networkCapabilities)) {
1945 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
1946 + nai.networkCapabilities + " -> " + networkCapabilities);
1947 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04001948 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001949 }
1950 break;
1951 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001952 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1953 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1954 if (nai == null) {
1955 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1956 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001957 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001958 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001959 "; created=" + nai.created);
1960 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001961 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001962 synchronized (nai) {
1963 nai.linkProperties = (LinkProperties)msg.obj;
1964 }
Paul Jenseneec75412014-08-04 12:21:19 -04001965 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001966 }
1967 break;
1968 }
1969 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1970 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1971 if (nai == null) {
1972 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1973 break;
1974 }
1975 info = (NetworkInfo) msg.obj;
1976 updateNetworkInfo(nai, info);
1977 break;
1978 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001979 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1980 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1981 if (nai == null) {
1982 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1983 break;
1984 }
1985 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001986 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001987 break;
1988 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001989 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1990 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1991 if (nai == null) {
1992 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1993 break;
1994 }
1995 try {
1996 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001997 } catch (Exception e) {
1998 // Never crash!
1999 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002000 }
2001 break;
2002 }
2003 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
2004 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2005 if (nai == null) {
2006 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
2007 break;
2008 }
2009 try {
2010 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002011 } catch (Exception e) {
2012 // Never crash!
2013 loge("Exception in removeVpnUidRanges: " + e);
2014 }
2015 break;
2016 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002017 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
2018 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2019 if (nai == null) {
2020 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
2021 break;
2022 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002023 if (nai.created && !nai.networkMisc.explicitlySelected) {
2024 loge("ERROR: created network explicitly selected.");
2025 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002026 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002027 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002028 break;
2029 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002030 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
2031 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2032 if (nai == null) {
2033 loge("EVENT_PACKET_KEEPALIVE from unknown NetworkAgent");
2034 break;
2035 }
2036 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2037 break;
2038 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04002039 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002040 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002041 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
2042 final boolean valid =
2043 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002044 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
2045 if (valid != nai.lastValidated) {
2046 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002047 nai.lastValidated = valid;
2048 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002049 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002050 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2051 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002052 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002053 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002054 // Let the NetworkAgent know the state of its network
2055 nai.asyncChannel.sendMessage(
2056 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2057 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2058 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002059 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002060 break;
2061 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002062 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002063 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002064 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2065 handleLingerComplete(nai);
2066 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002067 break;
2068 }
Paul Jensen869868be2014-05-15 10:33:05 -04002069 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002070 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002071 final boolean visible = (msg.arg1 != 0);
2072 final NetworkAgentInfo nai;
2073 synchronized (mNetworkForNetId) {
2074 nai = mNetworkForNetId.get(netId);
2075 }
2076 // If captive portal status has changed, update capabilities.
2077 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2078 nai.lastCaptivePortalDetected = visible;
2079 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002080 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002081 }
2082 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002083 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002084 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002085 if (nai == null) {
2086 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2087 break;
2088 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002089 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002090 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2091 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002092 }
Paul Jensen869868be2014-05-15 10:33:05 -04002093 break;
2094 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002095 }
2096 }
2097 }
2098
Paul Jensen85cf78e2015-06-25 13:25:07 -04002099 private void linger(NetworkAgentInfo nai) {
2100 nai.lingering = true;
2101 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2102 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2103 }
2104
Paul Jensen0cc17322014-11-25 15:26:53 -05002105 // Cancel any lingering so the linger timeout doesn't teardown a network.
2106 // This should be called when a network begins satisfying a NetworkRequest.
2107 // Note: depending on what state the NetworkMonitor is in (e.g.,
2108 // if it's awaiting captive portal login, or if validation failed), this
2109 // may trigger a re-evaluation of the network.
2110 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002111 nai.networkLingered.clear();
2112 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002113 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002114 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002115 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2116 }
2117
Robert Greenwalt7b816022014-04-18 15:25:25 -07002118 private void handleAsyncChannelHalfConnect(Message msg) {
2119 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002120 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002121 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2122 if (VDBG) log("NetworkFactory connected");
2123 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002124 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Erik Kline371c7b72016-03-22 17:04:20 +09002125 if (!nri.isRequest()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002126 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002127 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002128 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002129 }
2130 } else {
2131 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002132 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002133 }
2134 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2135 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2136 if (VDBG) log("NetworkAgent connected");
2137 // A network agent has requested a connection. Establish the connection.
2138 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2139 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2140 } else {
2141 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002142 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002143 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002144 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002145 synchronized (mNetworkForNetId) {
2146 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002147 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002148 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002149 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002150 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002151 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002152 }
2153 }
2154 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002155
Robert Greenwalt7b816022014-04-18 15:25:25 -07002156 private void handleAsyncChannelDisconnected(Message msg) {
2157 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2158 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002159 if (DBG) {
2160 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2161 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002162 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002163 // TODO - if we move the logic to the network agent (have them disconnect
2164 // because they lost all their requests or because their score isn't good)
2165 // then they would disconnect organically, report their new state and then
2166 // disconnect the channel.
2167 if (nai.networkInfo.isConnected()) {
2168 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2169 null, null);
2170 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002171 final boolean wasDefault = isDefaultNetwork(nai);
2172 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002173 mDefaultInetConditionPublished = 0;
2174 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002175 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002176 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2177 // by other networks that are already connected. Perhaps that can be done by
2178 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2179 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002180 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002181 mKeepaliveTracker.handleStopAllKeepalives(nai,
2182 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002183 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002184 mNetworkAgentInfos.remove(msg.replyTo);
2185 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002186 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002187 // Remove the NetworkAgent, but don't mark the netId as
2188 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002189 mNetworkForNetId.remove(nai.network.netId);
2190 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002191 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002192 for (int i = 0; i < nai.networkRequests.size(); i++) {
2193 NetworkRequest request = nai.networkRequests.valueAt(i);
2194 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2195 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2196 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002197 sendUpdatedScoreToFactories(request, 0);
2198 }
2199 }
2200 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2201 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002202 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002203 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002204 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002205 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002206 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002207 if (nai.created) {
2208 // Tell netd to clean up the configuration for this network
2209 // (routing rules, DNS, etc).
2210 // This may be slow as it requires a lot of netd shelling out to ip and
2211 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2212 // after we've rematched networks with requests which should make a potential
2213 // fallback network the default or requested a new network from the
2214 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2215 // long time.
2216 try {
2217 mNetd.removeNetwork(nai.network.netId);
2218 } catch (Exception e) {
2219 loge("Exception removing network: " + e);
2220 }
2221 }
2222 synchronized (mNetworkForNetId) {
2223 mNetIdInUse.delete(nai.network.netId);
2224 }
2225 } else {
2226 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2227 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002228 }
2229 }
2230
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002231 // If this method proves to be too slow then we can maintain a separate
2232 // pendingIntent => NetworkRequestInfo map.
2233 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2234 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2235 Intent intent = pendingIntent.getIntent();
2236 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2237 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2238 if (existingPendingIntent != null &&
2239 existingPendingIntent.getIntent().filterEquals(intent)) {
2240 return entry.getValue();
2241 }
2242 }
2243 return null;
2244 }
2245
2246 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2247 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2248
2249 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2250 if (existingRequest != null) { // remove the existing request.
2251 if (DBG) log("Replacing " + existingRequest.request + " with "
2252 + nri.request + " because their intents matched.");
2253 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2254 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002255 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002256 }
2257
Erik Klineda4bfa82015-04-30 12:58:40 +09002258 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002259 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002260 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002261 if (!nri.isRequest()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002262 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002263 if (nri.request.networkCapabilities.hasSignalStrength() &&
2264 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2265 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002266 }
2267 }
2268 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002269 rematchAllNetworksAndRequests(null, 0);
Erik Kline371c7b72016-03-22 17:04:20 +09002270 if (nri.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002271 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002272 }
2273 }
2274
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002275 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2276 int callingUid) {
2277 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2278 if (nri != null) {
2279 handleReleaseNetworkRequest(nri.request, callingUid);
2280 }
2281 }
2282
Paul Jensen99364842014-12-09 11:43:45 -05002283 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002284 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2285 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002286 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002287 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002288 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2289 // If this Network is already the highest scoring Network for a request, or if
2290 // there is hope for it to become one if it validated, then it is needed.
Erik Kline371c7b72016-03-22 17:04:20 +09002291 if (nri.isRequest() && nai.satisfies(nri.request) &&
Paul Jensene0988542015-06-25 15:30:08 -04002292 (nai.networkRequests.get(nri.request.requestId) != null ||
2293 // Note that this catches two important cases:
2294 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2295 // is currently satisfying the request. This is desirable when
2296 // cellular ends up validating but WiFi does not.
2297 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002298 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002299 // WiFi ends up validating and out scoring cellular.
2300 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2301 nai.getCurrentScoreAsValidated())) {
2302 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002303 }
2304 }
Paul Jensene0988542015-06-25 15:30:08 -04002305 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002306 }
2307
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002308 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2309 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002310 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002311 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002312 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2313 return;
2314 }
2315 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002316 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002317 mNetworkRequests.remove(request);
Erik Kline7523eb32015-07-09 18:24:03 +09002318 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002319 if (nri.isRequest()) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002320 // Find all networks that are satisfying this request and remove the request
2321 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002322 // TODO - it's my understanding that for a request there is only a single
2323 // network satisfying it, so this loop is wasteful
2324 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002325 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2326 if (nai.networkRequests.get(nri.request.requestId) != null) {
2327 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002328 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002329 log(" Removing from current network " + nai.name() +
2330 ", leaving " + nai.networkRequests.size() +
2331 " requests.");
2332 }
Paul Jensen99364842014-12-09 11:43:45 -05002333 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002334 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002335 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002336 } else {
2337 // suspect there should only be one pass through here
2338 // but if any were kept do the check below
2339 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002340 }
2341 }
2342 }
2343
Robert Greenwalt51481852015-01-08 14:43:31 -08002344 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2345 if (nai != null) {
2346 mNetworkForRequestId.remove(nri.request.requestId);
2347 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002348 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002349 // that a network connected to serve it, even though the network was already
2350 // connected. Now that this request has gone away, we might have to pretend
2351 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002352 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002353 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2354 boolean doRemove = true;
2355 if (wasKept) {
2356 // check if any of the remaining requests for this network are for the
2357 // same legacy type - if so, don't remove the nai
2358 for (int i = 0; i < nai.networkRequests.size(); i++) {
2359 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2360 if (otherRequest.legacyType == nri.request.legacyType &&
2361 isRequest(otherRequest)) {
2362 if (DBG) log(" still have other legacy request - leaving");
2363 doRemove = false;
2364 }
2365 }
2366 }
2367
2368 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002369 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002370 }
2371 }
2372
Robert Greenwalta67be032014-05-16 15:49:14 -07002373 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002374 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2375 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002376 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002377 } else {
2378 // listens don't have a singular affectedNetwork. Check all networks to see
2379 // if this listen request applies and remove it.
2380 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2381 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002382 if (nri.request.networkCapabilities.hasSignalStrength() &&
2383 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2384 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002385 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002386 }
2387 }
2388 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2389 }
2390 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002391
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002392 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2393 enforceConnectivityInternalPermission();
2394 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2395 accept ? 1 : 0, always ? 1: 0, network));
2396 }
2397
2398 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2399 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2400 " accept=" + accept + " always=" + always);
2401
2402 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2403 if (nai == null) {
2404 // Nothing to do.
2405 return;
2406 }
2407
2408 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002409 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002410 return;
2411 }
2412
2413 if (!nai.networkMisc.explicitlySelected) {
2414 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2415 }
2416
2417 if (accept != nai.networkMisc.acceptUnvalidated) {
2418 int oldScore = nai.getCurrentScore();
2419 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002420 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002421 sendUpdatedScoreToFactories(nai);
2422 }
2423
2424 if (always) {
2425 nai.asyncChannel.sendMessage(
2426 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2427 }
2428
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002429 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002430 // Tell the NetworkAgent to not automatically reconnect to the network.
2431 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2432 // Teardown the nework.
2433 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002434 }
2435
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002436 }
2437
2438 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002439 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002440 mHandler.sendMessageDelayed(
2441 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2442 PROMPT_UNVALIDATED_DELAY_MS);
2443 }
2444
2445 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002446 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002447 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2448
2449 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2450 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002451 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002452 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002453 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2454 return;
2455 }
2456
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002457 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002458 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002459 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2460 intent.setClassName("com.android.settings",
2461 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002462
2463 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2464 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2465 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002466 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002467 }
2468
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002469 private class InternalHandler extends Handler {
2470 public InternalHandler(Looper looper) {
2471 super(looper);
2472 }
2473
2474 @Override
2475 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002476 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002477 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002478 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002479 String causedBy = null;
2480 synchronized (ConnectivityService.this) {
2481 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2482 mNetTransitionWakeLock.isHeld()) {
2483 mNetTransitionWakeLock.release();
2484 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002485 } else {
2486 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002487 }
2488 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002489 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2490 log("Failed to find a new network - expiring NetTransition Wakelock");
2491 } else {
2492 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2493 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002494 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002495 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002496 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002497 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002498 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002499 break;
2500 }
Jason Monkdecd2952013-10-10 14:02:51 -04002501 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002502 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002503 break;
2504 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002505 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002506 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2507 break;
2508 }
2509 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2510 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002511 break;
2512 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002513 case EVENT_REGISTER_NETWORK_AGENT: {
2514 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2515 break;
2516 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002517 case EVENT_REGISTER_NETWORK_REQUEST:
2518 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002519 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002520 break;
2521 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002522 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2523 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002524 handleRegisterNetworkRequestWithIntent(msg);
2525 break;
2526 }
2527 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2528 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2529 break;
2530 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002531 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002532 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002533 break;
2534 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002535 case EVENT_SET_ACCEPT_UNVALIDATED: {
2536 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2537 break;
2538 }
2539 case EVENT_PROMPT_UNVALIDATED: {
2540 handlePromptUnvalidated((Network) msg.obj);
2541 break;
2542 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002543 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2544 handleMobileDataAlwaysOn();
2545 break;
2546 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002547 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2548 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2549 mKeepaliveTracker.handleStartKeepalive(msg);
2550 break;
2551 }
2552 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2553 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2554 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2555 int slot = msg.arg1;
2556 int reason = msg.arg2;
2557 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2558 break;
2559 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002560 case EVENT_SYSTEM_READY: {
2561 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2562 nai.networkMonitor.systemReady = true;
2563 }
2564 break;
2565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 }
2567 }
2568 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002569
2570 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002571 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002572 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002573 if (isTetheringSupported()) {
2574 return mTethering.tether(iface);
2575 } else {
2576 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2577 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002578 }
2579
2580 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002581 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002582 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002583
2584 if (isTetheringSupported()) {
2585 return mTethering.untether(iface);
2586 } else {
2587 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2588 }
2589 }
2590
2591 // javadoc from interface
2592 public int getLastTetherError(String iface) {
2593 enforceTetherAccessPermission();
2594
2595 if (isTetheringSupported()) {
2596 return mTethering.getLastTetherError(iface);
2597 } else {
2598 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2599 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002600 }
2601
2602 // TODO - proper iface API for selection by property, inspection, etc
2603 public String[] getTetherableUsbRegexs() {
2604 enforceTetherAccessPermission();
2605 if (isTetheringSupported()) {
2606 return mTethering.getTetherableUsbRegexs();
2607 } else {
2608 return new String[0];
2609 }
2610 }
2611
2612 public String[] getTetherableWifiRegexs() {
2613 enforceTetherAccessPermission();
2614 if (isTetheringSupported()) {
2615 return mTethering.getTetherableWifiRegexs();
2616 } else {
2617 return new String[0];
2618 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002619 }
2620
Danica Chang6fdd0c62010-08-11 14:54:43 -07002621 public String[] getTetherableBluetoothRegexs() {
2622 enforceTetherAccessPermission();
2623 if (isTetheringSupported()) {
2624 return mTethering.getTetherableBluetoothRegexs();
2625 } else {
2626 return new String[0];
2627 }
2628 }
2629
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002630 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002631 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002632 if (isTetheringSupported()) {
2633 return mTethering.setUsbTethering(enable);
2634 } else {
2635 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2636 }
2637 }
2638
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002639 // TODO - move iface listing, queries, etc to new module
2640 // javadoc from interface
2641 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002642 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002643 return mTethering.getTetherableIfaces();
2644 }
2645
2646 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002647 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002648 return mTethering.getTetheredIfaces();
2649 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002650
Robert Greenwalt5a735062010-03-02 17:25:02 -08002651 public String[] getTetheringErroredIfaces() {
2652 enforceTetherAccessPermission();
2653 return mTethering.getErroredIfaces();
2654 }
2655
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002656 public String[] getTetheredDhcpRanges() {
2657 enforceConnectivityInternalPermission();
2658 return mTethering.getTetheredDhcpRanges();
2659 }
2660
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002661 // if ro.tether.denied = true we default to no tethering
2662 // gservices could set the secure setting to 1 though to enable it on a build where it
2663 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002664 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002665 public boolean isTetheringSupported() {
2666 enforceTetherAccessPermission();
2667 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002668 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002669 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2670 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002671 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2672 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002673 mTethering.getTetherableWifiRegexs().length != 0 ||
2674 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2675 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002676 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002677
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002678 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002679 public void startTethering(int type, ResultReceiver receiver,
2680 boolean showProvisioningUi) {
2681 ConnectivityManager.enforceTetherChangePermission(mContext);
2682 if (!isTetheringSupported()) {
2683 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2684 return;
2685 }
2686 mTethering.startTethering(type, receiver, showProvisioningUi);
2687 }
2688
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002689 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002690 public void stopTethering(int type) {
2691 ConnectivityManager.enforceTetherChangePermission(mContext);
2692 mTethering.stopTethering(type);
2693 }
2694
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002695 // Called when we lose the default network and have no replacement yet.
2696 // This will automatically be cleared after X seconds or a new default network
2697 // becomes CONNECTED, whichever happens first. The timer is started by the
2698 // first caller and not restarted by subsequent callers.
2699 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002700 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002701 synchronized (this) {
2702 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002703 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002704 mNetTransitionWakeLock.acquire();
2705 mNetTransitionWakeLockCausedBy = forWhom;
2706 }
2707 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002708 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002709 mNetTransitionWakeLockTimeout);
2710 return;
2711 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002712
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002713 // 100 percent is full good, 0 is full bad.
2714 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002715 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002716 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002717 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002718 }
2719
Paul Jensenbfd17b72015-04-07 12:43:13 -04002720 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002721 enforceAccessPermission();
2722 enforceInternetPermission();
2723
Paul Jensenbfd17b72015-04-07 12:43:13 -04002724 NetworkAgentInfo nai;
2725 if (network == null) {
2726 nai = getDefaultNetwork();
2727 } else {
2728 nai = getNetworkAgentInfoForNetwork(network);
2729 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002730 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2731 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2732 return;
2733 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002734 // Revalidate if the app report does not match our current validated state.
2735 if (hasConnectivity == nai.lastValidated) return;
2736 final int uid = Binder.getCallingUid();
2737 if (DBG) {
2738 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2739 ") by " + uid);
2740 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002741 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002742 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2743 // which isn't meant to work on uncreated networks.
2744 if (!nai.created) return;
2745
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002746 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002747
2748 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2749 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002750 }
2751
Paul Jensencee9b512015-05-06 07:32:40 -04002752 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002753 // this information is already available as a world read/writable jvm property
2754 // so this API change wouldn't have a benifit. It also breaks the passing
2755 // of proxy info to all the JVMs.
2756 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002757 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002758 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002759 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2760 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002761 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002762 }
2763
Paul Jensencee9b512015-05-06 07:32:40 -04002764 public ProxyInfo getProxyForNetwork(Network network) {
2765 if (network == null) return getDefaultProxy();
2766 final ProxyInfo globalProxy = getGlobalProxy();
2767 if (globalProxy != null) return globalProxy;
2768 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2769 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2770 // caller may not have.
2771 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2772 if (nai == null) return null;
2773 synchronized (nai) {
2774 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2775 if (proxyInfo == null) return null;
2776 return new ProxyInfo(proxyInfo);
2777 }
2778 }
2779
Paul Jensene0bef712014-12-10 15:12:18 -05002780 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2781 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2782 // proxy is null then there is no proxy in place).
2783 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2784 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2785 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2786 proxy = null;
2787 }
2788 return proxy;
2789 }
2790
2791 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2792 // better for determining if a new proxy broadcast is necessary:
2793 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2794 // avoid unnecessary broadcasts.
2795 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2796 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2797 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2798 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2799 // all set.
2800 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2801 a = canonicalizeProxyInfo(a);
2802 b = canonicalizeProxyInfo(b);
2803 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2804 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2805 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2806 }
2807
Jason Monk207900c2014-04-25 15:00:09 -04002808 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002809 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002810
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002811 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002812 if (proxyProperties == mGlobalProxy) return;
2813 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2814 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2815
2816 String host = "";
2817 int port = 0;
2818 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002819 String pacFileUrl = "";
2820 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002821 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002822 if (!proxyProperties.isValid()) {
2823 if (DBG)
2824 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2825 return;
2826 }
Jason Monk207900c2014-04-25 15:00:09 -04002827 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002828 host = mGlobalProxy.getHost();
2829 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002830 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002831 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002832 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002833 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002834 } else {
2835 mGlobalProxy = null;
2836 }
2837 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002838 final long token = Binder.clearCallingIdentity();
2839 try {
2840 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2841 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2842 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2843 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002844 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002845 } finally {
2846 Binder.restoreCallingIdentity(token);
2847 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002848
Jason Monkcf0f97a2014-10-02 15:39:38 -04002849 if (mGlobalProxy == null) {
2850 proxyProperties = mDefaultProxy;
2851 }
2852 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002853 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002854 }
2855
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002856 private void loadGlobalProxy() {
2857 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002858 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2859 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2860 String exclList = Settings.Global.getString(res,
2861 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002862 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2863 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002864 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002865 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002866 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002867 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002868 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002869 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002870 if (!proxyProperties.isValid()) {
2871 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2872 return;
2873 }
2874
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002875 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002876 mGlobalProxy = proxyProperties;
2877 }
2878 }
2879 }
2880
Jason Monk207900c2014-04-25 15:00:09 -04002881 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002882 // this information is already available as a world read/writable jvm property
2883 // so this API change wouldn't have a benifit. It also breaks the passing
2884 // of proxy info to all the JVMs.
2885 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002886 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002887 return mGlobalProxy;
2888 }
2889 }
2890
Jason Monk207900c2014-04-25 15:00:09 -04002891 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002892 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002893 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002894 proxy = null;
2895 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002896 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002897 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002898 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002899 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002900 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2901 return;
2902 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002903
2904 // This call could be coming from the PacManager, containing the port of the local
2905 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2906 // global (to get the correct local port), and send a broadcast.
2907 // TODO: Switch PacManager to have its own message to send back rather than
2908 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002909 if ((mGlobalProxy != null) && (proxy != null)
2910 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002911 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2912 mGlobalProxy = proxy;
2913 sendProxyBroadcast(mGlobalProxy);
2914 return;
2915 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002916 mDefaultProxy = proxy;
2917
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002918 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002919 if (!mDefaultProxyDisabled) {
2920 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002921 }
2922 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002923 }
2924
Paul Jensene0bef712014-12-10 15:12:18 -05002925 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2926 // This method gets called when any network changes proxy, but the broadcast only ever contains
2927 // the default proxy (even if it hasn't changed).
2928 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2929 // world where an app might be bound to a non-default network.
2930 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2931 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2932 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2933
2934 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2935 sendProxyBroadcast(getDefaultProxy());
2936 }
2937 }
2938
Robert Greenwalt434203a2010-10-11 16:00:27 -07002939 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002940 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2941 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002942 if (!TextUtils.isEmpty(proxy)) {
2943 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002944 if (data.length == 0) {
2945 return;
2946 }
2947
Robert Greenwalt434203a2010-10-11 16:00:27 -07002948 String proxyHost = data[0];
2949 int proxyPort = 8080;
2950 if (data.length > 1) {
2951 try {
2952 proxyPort = Integer.parseInt(data[1]);
2953 } catch (NumberFormatException e) {
2954 return;
2955 }
2956 }
Jason Monk207900c2014-04-25 15:00:09 -04002957 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002958 setGlobalProxy(p);
2959 }
2960 }
2961
Jason Monk207900c2014-04-25 15:00:09 -04002962 private void sendProxyBroadcast(ProxyInfo proxy) {
2963 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002964 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002965 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002966 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002967 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2968 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002969 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002970 final long ident = Binder.clearCallingIdentity();
2971 try {
2972 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2973 } finally {
2974 Binder.restoreCallingIdentity(ident);
2975 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002976 }
2977
2978 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002979 final private HashMap<Uri, Integer> mUriEventMap;
2980 final private Context mContext;
2981 final private Handler mHandler;
2982
2983 SettingsObserver(Context context, Handler handler) {
2984 super(null);
2985 mUriEventMap = new HashMap<Uri, Integer>();
2986 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002987 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002988 }
2989
Erik Klineda4bfa82015-04-30 12:58:40 +09002990 void observe(Uri uri, int what) {
2991 mUriEventMap.put(uri, what);
2992 final ContentResolver resolver = mContext.getContentResolver();
2993 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002994 }
2995
2996 @Override
2997 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002998 Slog.wtf(TAG, "Should never be reached.");
2999 }
3000
3001 @Override
3002 public void onChange(boolean selfChange, Uri uri) {
3003 final Integer what = mUriEventMap.get(uri);
3004 if (what != null) {
3005 mHandler.obtainMessage(what.intValue()).sendToTarget();
3006 } else {
3007 loge("No matching event to send for URI=" + uri);
3008 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003009 }
3010 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003011
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003012 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003013 Slog.d(TAG, s);
3014 }
3015
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003016 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003017 Slog.e(TAG, s);
3018 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003019
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003020 private static <T> T checkNotNull(T value, String message) {
3021 if (value == null) {
3022 throw new NullPointerException(message);
3023 }
3024 return value;
3025 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003026
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003027 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003028 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003029 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3030 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3031 *
3032 * @param oldPackage Package name of the application which currently controls VPN, which will
3033 * be replaced. If there is no such application, this should should either be
3034 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3035 * @param newPackage Package name of the application which should gain control of VPN, or
3036 * {@code null} to disable.
3037 * @param userId User for whom to prepare the new VPN.
3038 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003039 * @hide
3040 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003041 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003042 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3043 int userId) {
3044 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003045 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003046
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003047 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003048 Vpn vpn = mVpns.get(userId);
3049 if (vpn != null) {
3050 return vpn.prepare(oldPackage, newPackage);
3051 } else {
3052 return false;
3053 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003054 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003055 }
3056
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003057 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003058 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3059 * This method is used by system-privileged apps.
3060 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3061 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3062 *
3063 * @param packageName The package for which authorization state should change.
3064 * @param userId User for whom {@code packageName} is installed.
3065 * @param authorized {@code true} if this app should be able to start a VPN connection without
3066 * explicit user approval, {@code false} if not.
3067 *
Jeff Davidson05542602014-08-11 14:07:27 -07003068 * @hide
3069 */
3070 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003071 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3072 enforceCrossUserPermission(userId);
3073
Jeff Davidson05542602014-08-11 14:07:27 -07003074 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003075 Vpn vpn = mVpns.get(userId);
3076 if (vpn != null) {
3077 vpn.setPackageAuthorization(packageName, authorized);
3078 }
Jeff Davidson05542602014-08-11 14:07:27 -07003079 }
3080 }
3081
3082 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003083 * Configure a TUN interface and return its file descriptor. Parameters
3084 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003085 * and not available in ConnectivityManager. Permissions are checked in
3086 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003087 * @hide
3088 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003089 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003090 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003091 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003092 int user = UserHandle.getUserId(Binder.getCallingUid());
3093 synchronized(mVpns) {
3094 return mVpns.get(user).establish(config);
3095 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003096 }
3097
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003098 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003099 * Start legacy VPN, controlling native daemons as needed. Creates a
3100 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003101 */
3102 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003103 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003104 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003105 final LinkProperties egress = getActiveLinkProperties();
3106 if (egress == null) {
3107 throw new IllegalStateException("Missing active network connection");
3108 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003109 int user = UserHandle.getUserId(Binder.getCallingUid());
3110 synchronized(mVpns) {
3111 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3112 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003113 }
3114
3115 /**
3116 * Return the information of the ongoing legacy VPN. This method is used
3117 * by VpnSettings and not available in ConnectivityManager. Permissions
3118 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003119 */
3120 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003121 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3122 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003123 if (mLockdownEnabled) {
3124 return null;
3125 }
3126
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003127 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003128 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003129 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003130 }
3131
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003132 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003133 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3134 * and not available in ConnectivityManager.
3135 */
3136 @Override
3137 public VpnInfo[] getAllVpnInfo() {
3138 enforceConnectivityInternalPermission();
3139 if (mLockdownEnabled) {
3140 return new VpnInfo[0];
3141 }
3142
3143 synchronized(mVpns) {
3144 List<VpnInfo> infoList = new ArrayList<>();
3145 for (int i = 0; i < mVpns.size(); i++) {
3146 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3147 if (info != null) {
3148 infoList.add(info);
3149 }
3150 }
3151 return infoList.toArray(new VpnInfo[infoList.size()]);
3152 }
3153 }
3154
3155 /**
3156 * @return VPN information for accounting, or null if we can't retrieve all required
3157 * information, e.g primary underlying iface.
3158 */
3159 @Nullable
3160 private VpnInfo createVpnInfo(Vpn vpn) {
3161 VpnInfo info = vpn.getVpnInfo();
3162 if (info == null) {
3163 return null;
3164 }
3165 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3166 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3167 // the underlyingNetworks list.
3168 if (underlyingNetworks == null) {
3169 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3170 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3171 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3172 }
3173 } else if (underlyingNetworks.length > 0) {
3174 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3175 if (linkProperties != null) {
3176 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3177 }
3178 }
3179 return info.primaryUnderlyingIface == null ? null : info;
3180 }
3181
3182 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003183 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3184 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003185 * Permissions are checked in Vpn class.
3186 * @hide
3187 */
3188 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003189 public VpnConfig getVpnConfig(int userId) {
3190 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003191 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003192 Vpn vpn = mVpns.get(userId);
3193 if (vpn != null) {
3194 return vpn.getVpnConfig();
3195 } else {
3196 return null;
3197 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003198 }
3199 }
3200
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003201 @Override
3202 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003203 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3204 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3205 return false;
3206 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003207
3208 // Tear down existing lockdown if profile was removed
3209 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3210 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003211 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3212 final VpnProfile profile = VpnProfile.decode(
3213 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003214 if (profile == null) {
3215 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3216 setLockdownTracker(null);
3217 return true;
3218 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003219 int user = UserHandle.getUserId(Binder.getCallingUid());
3220 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003221 Vpn vpn = mVpns.get(user);
3222 if (vpn == null) {
3223 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3224 return false;
3225 }
3226 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003227 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003228 } else {
3229 setLockdownTracker(null);
3230 }
3231
3232 return true;
3233 }
3234
3235 /**
3236 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3237 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3238 */
3239 private void setLockdownTracker(LockdownVpnTracker tracker) {
3240 // Shutdown any existing tracker
3241 final LockdownVpnTracker existing = mLockdownTracker;
3242 mLockdownTracker = null;
3243 if (existing != null) {
3244 existing.shutdown();
3245 }
3246
3247 try {
3248 if (tracker != null) {
3249 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003250 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003251 mLockdownTracker = tracker;
3252 mLockdownTracker.init();
3253 } else {
3254 mNetd.setFirewallEnabled(false);
3255 }
3256 } catch (RemoteException e) {
3257 // ignored; NMS lives inside system_server
3258 }
3259 }
3260
3261 private void throwIfLockdownEnabled() {
3262 if (mLockdownEnabled) {
3263 throw new IllegalStateException("Unavailable in lockdown mode");
3264 }
3265 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003266
Robin Lee244ce8e2016-01-05 18:03:46 +00003267 /**
3268 * Sets up or tears down the always-on VPN for user {@param user} as appropriate.
3269 *
3270 * @return {@code false} in case of errors; {@code true} otherwise.
3271 */
3272 private boolean updateAlwaysOnVpn(int user) {
3273 final String lockdownPackage = getAlwaysOnVpnPackage(user);
3274 if (lockdownPackage == null) {
3275 return true;
3276 }
3277
3278 // Create an intent to start the VPN service declared in the app's manifest.
3279 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
3280 serviceIntent.setPackage(lockdownPackage);
3281
3282 try {
3283 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(user)) != null;
3284 } catch (RuntimeException e) {
3285 return false;
3286 }
3287 }
3288
3289 @Override
3290 public boolean setAlwaysOnVpnPackage(int userId, String packageName) {
3291 enforceConnectivityInternalPermission();
3292 enforceCrossUserPermission(userId);
3293
3294 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3295 if (LockdownVpnTracker.isEnabled()) {
3296 return false;
3297 }
3298
3299 // If the current VPN package is the same as the new one, this is a no-op
3300 final String oldPackage = getAlwaysOnVpnPackage(userId);
3301 if (TextUtils.equals(oldPackage, packageName)) {
3302 return true;
3303 }
3304
3305 synchronized (mVpns) {
3306 Vpn vpn = mVpns.get(userId);
3307 if (vpn == null) {
3308 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3309 return false;
3310 }
3311 if (!vpn.setAlwaysOnPackage(packageName)) {
3312 return false;
3313 }
3314 if (!updateAlwaysOnVpn(userId)) {
3315 vpn.setAlwaysOnPackage(null);
3316 return false;
3317 }
3318 }
3319 return true;
3320 }
3321
3322 @Override
3323 public String getAlwaysOnVpnPackage(int userId) {
3324 enforceConnectivityInternalPermission();
3325 enforceCrossUserPermission(userId);
3326
3327 synchronized (mVpns) {
3328 Vpn vpn = mVpns.get(userId);
3329 if (vpn == null) {
3330 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3331 return null;
3332 }
3333 return vpn.getAlwaysOnPackage();
3334 }
3335 }
3336
Wink Savilleab9321d2013-06-29 21:10:57 -07003337 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003338 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003339 // TODO: Remove? Any reason to trigger a provisioning check?
3340 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003341 }
3342
3343 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003344 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003345
Paul Jensen89e0f092014-09-15 15:59:36 -04003346 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003347 if (DBG) {
3348 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003349 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003350 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003351 Intent intent = new Intent(action);
3352 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003353 // Concatenate the range of types onto the range of NetIDs.
3354 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003355 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003356 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003357 }
3358
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003359 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003360 * Show or hide network provisioning notifications.
3361 *
3362 * We use notifications for two purposes: to notify that a network requires sign in
3363 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3364 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3365 * particular network we can display the notification type that was most recently requested.
3366 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3367 * might first display NO_INTERNET, and then when the captive portal check completes, display
3368 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003369 *
3370 * @param id an identifier that uniquely identifies this notification. This must match
3371 * between show and hide calls. We use the NetID value but for legacy callers
3372 * we concatenate the range of types with the range of NetIDs.
3373 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003374 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003375 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3376 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003377 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003378 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3379 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003380 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003381 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003382
3383 Resources r = Resources.getSystem();
3384 NotificationManager notificationManager = (NotificationManager) mContext
3385 .getSystemService(Context.NOTIFICATION_SERVICE);
3386
3387 if (visible) {
3388 CharSequence title;
3389 CharSequence details;
3390 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003391 if (notifyType == NotificationType.NO_INTERNET &&
3392 networkType == ConnectivityManager.TYPE_WIFI) {
3393 title = r.getString(R.string.wifi_no_internet, 0);
3394 details = r.getString(R.string.wifi_no_internet_detailed);
3395 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3396 } else if (notifyType == NotificationType.SIGN_IN) {
3397 switch (networkType) {
3398 case ConnectivityManager.TYPE_WIFI:
3399 title = r.getString(R.string.wifi_available_sign_in, 0);
3400 details = r.getString(R.string.network_available_sign_in_detailed,
3401 extraInfo);
3402 icon = R.drawable.stat_notify_wifi_in_range;
3403 break;
3404 case ConnectivityManager.TYPE_MOBILE:
3405 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3406 title = r.getString(R.string.network_available_sign_in, 0);
3407 // TODO: Change this to pull from NetworkInfo once a printable
3408 // name has been added to it
3409 details = mTelephonyManager.getNetworkOperatorName();
3410 icon = R.drawable.stat_notify_rssi_in_range;
3411 break;
3412 default:
3413 title = r.getString(R.string.network_available_sign_in, 0);
3414 details = r.getString(R.string.network_available_sign_in_detailed,
3415 extraInfo);
3416 icon = R.drawable.stat_notify_rssi_in_range;
3417 break;
3418 }
3419 } else {
3420 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3421 + getNetworkTypeName(networkType));
3422 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003423 }
3424
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003425 Notification notification = new Notification.Builder(mContext)
3426 .setWhen(0)
3427 .setSmallIcon(icon)
3428 .setAutoCancel(true)
3429 .setTicker(title)
3430 .setColor(mContext.getColor(
3431 com.android.internal.R.color.system_notification_accent_color))
3432 .setContentTitle(title)
3433 .setContentText(details)
3434 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003435 .setLocalOnly(true)
3436 .setPriority(highPriority ?
3437 Notification.PRIORITY_HIGH :
3438 Notification.PRIORITY_DEFAULT)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003439 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003440 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003441 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003442
Wink Saville948282b2013-08-29 08:55:16 -07003443 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003444 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003445 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003446 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003447 npe.printStackTrace();
3448 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003449 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003450 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003451 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003452 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003453 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003454 npe.printStackTrace();
3455 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003456 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003457 }
3458
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003459 /** Location to an updatable file listing carrier provisioning urls.
3460 * An example:
3461 *
3462 * <?xml version="1.0" encoding="utf-8"?>
3463 * <provisioningUrls>
3464 * <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 -07003465 * </provisioningUrls>
3466 */
3467 private static final String PROVISIONING_URL_PATH =
3468 "/data/misc/radio/provisioning_urls.xml";
3469 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003470
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003471 /** XML tag for root element. */
3472 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3473 /** XML tag for individual url */
3474 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003475 /** XML attribute for mcc */
3476 private static final String ATTR_MCC = "mcc";
3477 /** XML attribute for mnc */
3478 private static final String ATTR_MNC = "mnc";
3479
Paul Jensen434dde82015-06-11 09:43:30 -04003480 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003481 FileReader fileReader = null;
3482 XmlPullParser parser = null;
3483 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003484
3485 try {
3486 fileReader = new FileReader(mProvisioningUrlFile);
3487 parser = Xml.newPullParser();
3488 parser.setInput(fileReader);
3489 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3490
3491 while (true) {
3492 XmlUtils.nextElement(parser);
3493
3494 String element = parser.getName();
3495 if (element == null) break;
3496
Paul Jensen434dde82015-06-11 09:43:30 -04003497 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003498 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3499 try {
3500 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3501 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3502 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3503 parser.next();
3504 if (parser.getEventType() == XmlPullParser.TEXT) {
3505 return parser.getText();
3506 }
3507 }
3508 }
3509 } catch (NumberFormatException e) {
3510 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3511 }
3512 }
3513 }
3514 return null;
3515 } catch (FileNotFoundException e) {
3516 loge("Carrier Provisioning Urls file not found");
3517 } catch (XmlPullParserException e) {
3518 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3519 } catch (IOException e) {
3520 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3521 } finally {
3522 if (fileReader != null) {
3523 try {
3524 fileReader.close();
3525 } catch (IOException e) {}
3526 }
3527 }
3528 return null;
3529 }
3530
Wink Saville42d4f082013-07-20 20:31:59 -07003531 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003532 public String getMobileProvisioningUrl() {
3533 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003534 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003535 if (TextUtils.isEmpty(url)) {
3536 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003537 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003538 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003539 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003540 }
Wink Saville8cf35602013-07-10 23:00:07 -07003541 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003542 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003543 String phoneNumber = mTelephonyManager.getLine1Number();
3544 if (TextUtils.isEmpty(phoneNumber)) {
3545 phoneNumber = "0000000000";
3546 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003547 url = String.format(url,
3548 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3549 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003550 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003551 }
3552
Wink Savilleab9321d2013-06-29 21:10:57 -07003553 return url;
3554 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003555
Wink Saville948282b2013-08-29 08:55:16 -07003556 @Override
3557 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003558 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003559 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003560 final long ident = Binder.clearCallingIdentity();
3561 try {
3562 setProvNotificationVisible(visible, networkType, action);
3563 } finally {
3564 Binder.restoreCallingIdentity(ident);
3565 }
Wink Saville948282b2013-08-29 08:55:16 -07003566 }
Wink Saville7788c612013-08-29 14:57:08 -07003567
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003568 @Override
3569 public void setAirplaneMode(boolean enable) {
3570 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003571 final long ident = Binder.clearCallingIdentity();
3572 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003573 final ContentResolver cr = mContext.getContentResolver();
3574 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3575 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3576 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003577 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003578 } finally {
3579 Binder.restoreCallingIdentity(ident);
3580 }
3581 }
3582
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003583 private void onUserStart(int userId) {
3584 synchronized(mVpns) {
3585 Vpn userVpn = mVpns.get(userId);
3586 if (userVpn != null) {
3587 loge("Starting user already has a VPN");
3588 return;
3589 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003590 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003591 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003592 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003593 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3594 updateLockdownVpn();
3595 } else {
3596 updateAlwaysOnVpn(userId);
3597 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003598 }
3599
3600 private void onUserStop(int userId) {
3601 synchronized(mVpns) {
3602 Vpn userVpn = mVpns.get(userId);
3603 if (userVpn == null) {
3604 loge("Stopping user has no VPN");
3605 return;
3606 }
3607 mVpns.delete(userId);
3608 }
3609 }
3610
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003611 private void onUserAdded(int userId) {
3612 synchronized(mVpns) {
3613 final int vpnsSize = mVpns.size();
3614 for (int i = 0; i < vpnsSize; i++) {
3615 Vpn vpn = mVpns.valueAt(i);
3616 vpn.onUserAdded(userId);
3617 }
3618 }
3619 }
3620
3621 private void onUserRemoved(int userId) {
3622 synchronized(mVpns) {
3623 final int vpnsSize = mVpns.size();
3624 for (int i = 0; i < vpnsSize; i++) {
3625 Vpn vpn = mVpns.valueAt(i);
3626 vpn.onUserRemoved(userId);
3627 }
3628 }
3629 }
3630
Robin Lee89e7a692016-02-29 14:38:17 +00003631 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003632 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3633 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3634 updateLockdownVpn();
3635 } else {
3636 updateAlwaysOnVpn(userId);
3637 }
3638 }
3639
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003640 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3641 @Override
3642 public void onReceive(Context context, Intent intent) {
3643 final String action = intent.getAction();
3644 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3645 if (userId == UserHandle.USER_NULL) return;
3646
3647 if (Intent.ACTION_USER_STARTING.equals(action)) {
3648 onUserStart(userId);
3649 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3650 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003651 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3652 onUserAdded(userId);
3653 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3654 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003655 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3656 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003657 }
3658 }
3659 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003660
Robert Greenwalta67be032014-05-16 15:49:14 -07003661 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3662 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003663 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3664 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003665
Robert Greenwalta67be032014-05-16 15:49:14 -07003666 private static class NetworkFactoryInfo {
3667 public final String name;
3668 public final Messenger messenger;
3669 public final AsyncChannel asyncChannel;
3670
3671 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3672 this.name = name;
3673 this.messenger = messenger;
3674 this.asyncChannel = asyncChannel;
3675 }
3676 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003677
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003678 /**
Erik Kline371c7b72016-03-22 17:04:20 +09003679 * A NetworkRequest as registered by an application can be one of three
3680 * types:
3681 *
3682 * - "listen", for which the framework will issue callbacks about any
3683 * and all networks that match the specified NetworkCapabilities,
3684 *
3685 * - "request", capable of causing a specific network to be created
3686 * first (e.g. a telephony DUN request), the framework will issue
3687 * callbacks about the single, highest scoring current network
3688 * (if any) that matches the specified NetworkCapabilities, or
3689 *
3690 * - "track the default network", a hybrid of the two designed such
3691 * that the framework will issue callbacks for the single, highest
3692 * scoring current network (if any) that matches the capabilities of
3693 * the default Internet request (mDefaultRequest), but which cannot
3694 * cause the framework to either create or retain the existence of
3695 * any specific network.
3696 *
3697 */
3698 private static enum NetworkRequestType {
3699 LISTEN,
3700 TRACK_DEFAULT,
3701 REQUEST
3702 };
3703
3704 /**
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003705 * Tracks info about the requester.
3706 * Also used to notice when the calling process dies so we can self-expire
3707 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003708 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003709 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003710 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003711 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003712 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003713 final int mPid;
3714 final int mUid;
3715 final Messenger messenger;
Erik Kline371c7b72016-03-22 17:04:20 +09003716 private final NetworkRequestType mType;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003717
Erik Kline371c7b72016-03-22 17:04:20 +09003718 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, NetworkRequestType type) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003719 request = r;
3720 mPendingIntent = pi;
3721 messenger = null;
3722 mBinder = null;
3723 mPid = getCallingPid();
3724 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003725 mType = type;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003726 }
3727
Erik Kline371c7b72016-03-22 17:04:20 +09003728 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, NetworkRequestType type) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003729 super();
3730 messenger = m;
3731 request = r;
3732 mBinder = binder;
3733 mPid = getCallingPid();
3734 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003735 mType = type;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003736 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003737
3738 try {
3739 mBinder.linkToDeath(this, 0);
3740 } catch (RemoteException e) {
3741 binderDied();
3742 }
3743 }
3744
Erik Kline371c7b72016-03-22 17:04:20 +09003745 private String typeString() {
3746 switch (mType) {
3747 case LISTEN: return "Listen";
3748 case REQUEST: return "Request";
3749 case TRACK_DEFAULT: return "Track default";
3750 default:
3751 return "unknown type";
3752 }
3753 }
3754
Robert Greenwalt9258c642014-03-26 16:47:06 -07003755 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003756 if (mBinder != null) {
3757 mBinder.unlinkToDeath(this, 0);
3758 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003759 }
3760
3761 public void binderDied() {
3762 log("ConnectivityService NetworkRequestInfo binderDied(" +
3763 request + ", " + mBinder + ")");
3764 releaseNetworkRequest(request);
3765 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003766
Erik Kline371c7b72016-03-22 17:04:20 +09003767 /**
3768 * Returns true iff. the contained NetworkRequest is one that:
3769 *
3770 * - should be associated with at most one satisfying network
3771 * at a time;
3772 *
3773 * - should cause a network to be kept up if it is the only network
3774 * which can satisfy the NetworkReqeust.
3775 *
3776 * For full detail of how isRequest() is used for pairing Networks with
3777 * NetworkRequests read rematchNetworkAndRequests().
3778 *
3779 * TODO: Rename to something more properly descriptive.
3780 */
3781 public boolean isRequest() {
3782 return (mType == NetworkRequestType.TRACK_DEFAULT) ||
3783 (mType == NetworkRequestType.REQUEST);
3784 }
3785
Robert Greenwalta67be032014-05-16 15:49:14 -07003786 public String toString() {
Erik Kline371c7b72016-03-22 17:04:20 +09003787 return typeString() +
Erik Kline7523eb32015-07-09 18:24:03 +09003788 " from uid/pid:" + mUid + "/" + mPid +
3789 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003790 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003791 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003792 }
3793
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003794 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3795 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3796 if (badCapability != null) {
3797 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003798 }
3799 }
3800
Erik Kline9d598e12015-07-13 16:37:51 +09003801 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003802 final SortedSet<Integer> thresholds = new TreeSet();
3803 synchronized (nai) {
3804 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3805 if (nri.request.networkCapabilities.hasSignalStrength() &&
3806 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3807 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3808 }
3809 }
3810 }
Erik Kline9d598e12015-07-13 16:37:51 +09003811 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003812 }
3813
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003814 private void updateSignalStrengthThresholds(
3815 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3816 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003817 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003818 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3819
3820 // TODO: Switch to VDBG.
3821 if (DBG) {
3822 String detail;
3823 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3824 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3825 } else {
3826 detail = reason;
3827 }
3828 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3829 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3830 }
3831
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003832 nai.asyncChannel.sendMessage(
3833 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003834 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003835 }
3836
Robert Greenwalt9258c642014-03-26 16:47:06 -07003837 @Override
3838 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003839 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Erik Kline371c7b72016-03-22 17:04:20 +09003840 final NetworkRequestType type = (networkCapabilities == null)
3841 ? NetworkRequestType.TRACK_DEFAULT
3842 : NetworkRequestType.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09003843 // If the requested networkCapabilities is null, take them instead from
3844 // the default network request. This allows callers to keep track of
3845 // the system default network.
Erik Kline371c7b72016-03-22 17:04:20 +09003846 if (type == NetworkRequestType.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09003847 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
3848 enforceAccessPermission();
3849 } else {
3850 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3851 enforceNetworkRequestPermissions(networkCapabilities);
3852 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003853 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003854 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003855
Robert Greenwalt6078b502014-06-11 16:05:07 -07003856 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003857 throw new IllegalArgumentException("Bad timeout specified");
3858 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003859
Etan Cohenddb9ef02015-11-18 10:56:15 -08003860 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
3861 .equals(networkCapabilities.getNetworkSpecifier())) {
3862 throw new IllegalArgumentException("Invalid network specifier - must not be '"
3863 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
3864 }
3865
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003866 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3867 nextNetworkRequestId());
Erik Kline371c7b72016-03-22 17:04:20 +09003868 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, type);
Erik Kline7523eb32015-07-09 18:24:03 +09003869 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003870
3871 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003872 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003873 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003874 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003875 }
3876 return networkRequest;
3877 }
3878
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003879 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003880 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003881 enforceConnectivityInternalPermission();
3882 } else {
3883 enforceChangePermission();
3884 }
3885 }
3886
fenglub15e72b2015-03-20 11:29:56 -07003887 @Override
fengludb571472015-04-21 17:12:05 -07003888 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003889 enforceAccessPermission();
3890 NetworkAgentInfo nai = null;
3891 if (network == null) {
3892 return false;
3893 }
3894 synchronized (mNetworkForNetId) {
3895 nai = mNetworkForNetId.get(network.netId);
3896 }
3897 if (nai != null) {
3898 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3899 return true;
3900 }
3901 return false;
3902 }
3903
3904
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003905 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3906 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003907 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003908 final int uidRules;
3909 final int uid = Binder.getCallingUid();
3910 synchronized(mRulesLock) {
3911 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3912 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003913 if (uidRules != RULE_ALLOW_ALL) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003914 // we could silently fail or we can filter the available nets to only give
3915 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003916 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003917 }
3918 }
3919 }
3920
Robert Greenwalt9258c642014-03-26 16:47:06 -07003921 @Override
3922 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3923 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003924 checkNotNull(operation, "PendingIntent cannot be null.");
3925 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3926 enforceNetworkRequestPermissions(networkCapabilities);
3927 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003928 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003929
3930 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3931 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003932 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09003933 NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003934 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003935 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3936 nri));
3937 return networkRequest;
3938 }
3939
Jeremy Joslin79294842014-12-03 17:15:28 -08003940 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3941 mHandler.sendMessageDelayed(
3942 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3943 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3944 }
3945
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003946 @Override
3947 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003948 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003949 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3950 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003951 }
3952
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003953 // In order to implement the compatibility measure for pre-M apps that call
3954 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3955 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3956 // This ensures it has permission to do so.
3957 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3958 if (nc == null) {
3959 return false;
3960 }
3961 int[] transportTypes = nc.getTransportTypes();
3962 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3963 return false;
3964 }
3965 try {
3966 mContext.enforceCallingOrSelfPermission(
3967 android.Manifest.permission.ACCESS_WIFI_STATE,
3968 "ConnectivityService");
3969 } catch (SecurityException e) {
3970 return false;
3971 }
3972 return true;
3973 }
3974
Robert Greenwalt9258c642014-03-26 16:47:06 -07003975 @Override
3976 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3977 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003978 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3979 enforceAccessPermission();
3980 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003981
Erik Kline7523eb32015-07-09 18:24:03 +09003982 NetworkRequest networkRequest = new NetworkRequest(
3983 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003984 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
Erik Kline371c7b72016-03-22 17:04:20 +09003985 NetworkRequestType.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003986 if (DBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003987
3988 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3989 return networkRequest;
3990 }
3991
3992 @Override
3993 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3994 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003995 checkNotNull(operation, "PendingIntent cannot be null.");
3996 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3997 enforceAccessPermission();
3998 }
3999
Erik Kline7523eb32015-07-09 18:24:03 +09004000 NetworkRequest networkRequest = new NetworkRequest(
4001 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04004002 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09004003 NetworkRequestType.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09004004 if (DBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004005
4006 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004007 }
4008
4009 @Override
4010 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04004011 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4012 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004013 }
4014
4015 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004016 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004017 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004018 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4019 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004020 }
4021
Robert Greenwalta67be032014-05-16 15:49:14 -07004022 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004023 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004024 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4025 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4026 }
4027
4028 @Override
4029 public void unregisterNetworkFactory(Messenger messenger) {
4030 enforceConnectivityInternalPermission();
4031 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4032 }
4033
4034 private void handleUnregisterNetworkFactory(Messenger messenger) {
4035 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4036 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004037 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004038 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004039 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004040 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004041 }
4042
Robert Greenwalt7b816022014-04-18 15:25:25 -07004043 /**
4044 * NetworkAgentInfo supporting a request by requestId.
4045 * These have already been vetted (their Capabilities satisfy the request)
4046 * and the are the highest scored network available.
4047 * the are keyed off the Requests requestId.
4048 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004049 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004050 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4051 new SparseArray<NetworkAgentInfo>();
4052
Paul Jensen31a94f42015-02-13 14:18:39 -05004053 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4054 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004055 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4056 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004057 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4058 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4059 // there may not be a strict 1:1 correlation between the two.
4060 @GuardedBy("mNetworkForNetId")
4061 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004062
Robert Greenwalt7b816022014-04-18 15:25:25 -07004063 // NetworkAgentInfo keyed off its connecting messenger
4064 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004065 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004066 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4067 new HashMap<Messenger, NetworkAgentInfo>();
4068
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004069 @GuardedBy("mBlockedAppUids")
4070 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4071
Paul Jensen2c311d62014-11-17 12:34:51 -05004072 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004073 private final NetworkRequest mDefaultRequest;
4074
Erik Klineda4bfa82015-04-30 12:58:40 +09004075 // Request used to optionally keep mobile data active even when higher
4076 // priority networks like Wi-Fi are active.
4077 private final NetworkRequest mDefaultMobileDataRequest;
4078
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004079 private NetworkAgentInfo getDefaultNetwork() {
4080 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4081 }
4082
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004083 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004084 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004085 }
4086
Paul Jensen31a94f42015-02-13 14:18:39 -05004087 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004088 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004089 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004090 enforceConnectivityInternalPermission();
4091
Paul Jensen2c311d62014-11-17 12:34:51 -05004092 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4093 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004094 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004095 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4096 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004097 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004098 synchronized (this) {
4099 nai.networkMonitor.systemReady = mSystemReady;
4100 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07004101 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004102 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004103 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004104 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004105 }
4106
4107 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4108 if (VDBG) log("Got NetworkAgent Messenger");
4109 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004110 synchronized (mNetworkForNetId) {
4111 mNetworkForNetId.put(na.network.netId, na);
4112 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004113 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4114 NetworkInfo networkInfo = na.networkInfo;
4115 na.networkInfo = null;
4116 updateNetworkInfo(na, networkInfo);
4117 }
4118
4119 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4120 LinkProperties newLp = networkAgent.linkProperties;
4121 int netId = networkAgent.network.netId;
4122
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004123 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4124 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004125 if (networkAgent.clatd != null) {
4126 networkAgent.clatd.fixupLinkProperties(oldLp);
4127 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004128
Paul Jensen992f2522014-04-28 10:33:11 -04004129 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004130 updateMtu(newLp, oldLp);
4131 // TODO - figure out what to do for clat
4132// for (LinkProperties lp : newLp.getStackedLinks()) {
4133// updateMtu(lp, null);
4134// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004135 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004136
Erik Kline94887872016-04-05 13:30:49 +09004137 updateRoutes(newLp, oldLp, netId);
4138 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004139
Paul Jensen3b759822014-05-13 11:44:01 -04004140 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004141 if (isDefaultNetwork(networkAgent)) {
4142 handleApplyDefaultProxy(newLp.getHttpProxy());
4143 } else {
4144 updateProxy(newLp, oldLp, networkAgent);
4145 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004146 // TODO - move this check to cover the whole function
4147 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004148 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004149 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4150 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004151
4152 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004153 }
4154
Lorenzo Colitti95439462014-10-09 13:44:48 +09004155 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4156 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4157 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004158
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004159 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004160 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4161 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004162 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004163 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004164 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004165 }
Paul Jensen992f2522014-04-28 10:33:11 -04004166
4167 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4168 CompareResult<String> interfaceDiff = new CompareResult<String>();
4169 if (oldLp != null) {
4170 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4171 } else if (newLp != null) {
4172 interfaceDiff.added = newLp.getAllInterfaceNames();
4173 }
4174 for (String iface : interfaceDiff.added) {
4175 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004176 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004177 mNetd.addInterfaceToNetwork(iface, netId);
4178 } catch (Exception e) {
4179 loge("Exception adding interface: " + e);
4180 }
4181 }
4182 for (String iface : interfaceDiff.removed) {
4183 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004184 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004185 mNetd.removeInterfaceFromNetwork(iface, netId);
4186 } catch (Exception e) {
4187 loge("Exception removing interface: " + e);
4188 }
4189 }
4190 }
4191
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004192 /**
4193 * Have netd update routes from oldLp to newLp.
4194 * @return true if routes changed between oldLp and newLp
4195 */
4196 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004197 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4198 if (oldLp != null) {
4199 routeDiff = oldLp.compareAllRoutes(newLp);
4200 } else if (newLp != null) {
4201 routeDiff.added = newLp.getAllRoutes();
4202 }
4203
4204 // add routes before removing old in case it helps with continuous connectivity
4205
4206 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4207 for (RouteInfo route : routeDiff.added) {
4208 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004209 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004210 try {
4211 mNetd.addRoute(netId, route);
4212 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004213 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4214 loge("Exception in addRoute for non-gateway: " + e);
4215 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004216 }
4217 }
4218 for (RouteInfo route : routeDiff.added) {
4219 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004220 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004221 try {
4222 mNetd.addRoute(netId, route);
4223 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004224 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4225 loge("Exception in addRoute for gateway: " + e);
4226 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004227 }
4228 }
4229
4230 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004231 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004232 try {
4233 mNetd.removeRoute(netId, route);
4234 } catch (Exception e) {
4235 loge("Exception in removeRoute: " + e);
4236 }
4237 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004238 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004239 }
Erik Kline41368502015-06-17 13:19:54 +09004240
Erik Kline94887872016-04-05 13:30:49 +09004241 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4242 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4243 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004244 }
Erik Kline94887872016-04-05 13:30:49 +09004245
4246 Collection<InetAddress> dnses = newLp.getDnsServers();
4247 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
4248 try {
4249 mNetd.setDnsServersForNetwork(
4250 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4251 } catch (Exception e) {
4252 loge("Exception in setDnsServersForNetwork: " + e);
4253 }
4254 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4255 if (defaultNai != null && defaultNai.network.netId == netId) {
4256 setDefaultDnsSystemProperties(dnses);
4257 }
4258 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004259 }
4260
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004261 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4262 int last = 0;
4263 for (InetAddress dns : dnses) {
4264 ++last;
4265 String key = "net.dns" + last;
4266 String value = dns.getHostAddress();
4267 SystemProperties.set(key, value);
4268 }
4269 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4270 String key = "net.dns" + i;
4271 SystemProperties.set(key, "");
4272 }
4273 mNumDnsEntries = last;
4274 }
4275
Paul Jensen3d194ea2015-06-16 14:27:36 -04004276 /**
4277 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4278 * augmented with any stateful capabilities implied from {@code networkAgent}
4279 * (e.g., validated status and captive portal status).
4280 *
Paul Jensene0988542015-06-25 15:30:08 -04004281 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004282 * @param networkCapabilities the new network capabilities.
4283 */
Paul Jensene0988542015-06-25 15:30:08 -04004284 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004285 // Don't modify caller's NetworkCapabilities.
4286 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004287 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004288 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4289 } else {
4290 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4291 }
Paul Jensene0988542015-06-25 15:30:08 -04004292 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004293 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4294 } else {
4295 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4296 }
Paul Jensene0988542015-06-25 15:30:08 -04004297 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4298 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004299 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4300 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4301 try {
4302 mNetd.setNetworkPermission(nai.network.netId,
4303 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4304 null : NetworkManagementService.PERMISSION_SYSTEM);
4305 } catch (RemoteException e) {
4306 loge("Exception in setNetworkPermission: " + e);
4307 }
4308 }
Paul Jensene0988542015-06-25 15:30:08 -04004309 synchronized (nai) {
4310 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004311 }
Paul Jensene0988542015-06-25 15:30:08 -04004312 rematchAllNetworksAndRequests(nai, oldScore);
4313 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004314 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004315 }
4316
Paul Jensenc8b9a742014-09-30 15:37:41 -04004317 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4318 for (int i = 0; i < nai.networkRequests.size(); i++) {
4319 NetworkRequest nr = nai.networkRequests.valueAt(i);
4320 // Don't send listening requests to factories. b/17393458
4321 if (!isRequest(nr)) continue;
4322 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4323 }
4324 }
4325
Robert Greenwalt7b816022014-04-18 15:25:25 -07004326 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4327 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004328 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004329 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4330 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004331 }
4332 }
4333
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004334 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4335 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004336 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004337 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004338 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4339 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004340 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004341 sendIntent(nri.mPendingIntent, intent);
4342 }
4343 // else not handled
4344 }
4345
4346 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4347 mPendingIntentWakeLock.acquire();
4348 try {
4349 if (DBG) log("Sending " + pendingIntent);
4350 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4351 } catch (PendingIntent.CanceledException e) {
4352 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4353 mPendingIntentWakeLock.release();
4354 releasePendingNetworkRequest(pendingIntent);
4355 }
4356 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4357 }
4358
4359 @Override
4360 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4361 String resultData, Bundle resultExtras) {
4362 if (DBG) log("Finished sending " + pendingIntent);
4363 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004364 // Release with a delay so the receiving client has an opportunity to put in its
4365 // own request.
4366 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004367 }
4368
Robert Greenwalt9258c642014-03-26 16:47:06 -07004369 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004370 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004371 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004372 Bundle bundle = new Bundle();
4373 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4374 new NetworkRequest(nri.request));
4375 Message msg = Message.obtain();
4376 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4377 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4378 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4379 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004380 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004381 case ConnectivityManager.CALLBACK_LOSING: {
4382 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4383 break;
4384 }
4385 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4386 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4387 new NetworkCapabilities(networkAgent.networkCapabilities));
4388 break;
4389 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004390 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004391 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4392 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004393 break;
4394 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004395 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004396 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004397 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004398 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004399 if (VDBG) {
4400 log("sending notification " + notifyTypeToName(notificationType) +
4401 " for " + nri.request);
4402 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004403 nri.messenger.send(msg);
4404 } catch (RemoteException e) {
4405 // may occur naturally in the race of binder death.
4406 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4407 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004408 }
4409
Paul Jensenc8b9a742014-09-30 15:37:41 -04004410 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4411 for (int i = 0; i < nai.networkRequests.size(); i++) {
4412 NetworkRequest nr = nai.networkRequests.valueAt(i);
4413 // Ignore listening requests.
4414 if (!isRequest(nr)) continue;
4415 loge("Dead network still had at least " + nr);
4416 break;
4417 }
4418 nai.asyncChannel.disconnect();
4419 }
4420
Robert Greenwalt7b816022014-04-18 15:25:25 -07004421 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4422 if (oldNetwork == null) {
4423 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4424 return;
4425 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004426 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4427 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004428 }
4429
Paul Jensen27b02b72014-07-14 12:03:33 -04004430 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004431 if (DBG) log("Switching to new default network: " + newNetwork);
Pierre Imai55618be2016-02-19 15:25:54 +09004432 ConnectivityServiceChangeEvent.logEvent(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04004433 setupDataActivityTracking(newNetwork);
4434 try {
4435 mNetd.setDefaultNetId(newNetwork.network.netId);
4436 } catch (Exception e) {
4437 loge("Exception setting default network :" + e);
4438 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004439 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004440 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004441 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004442 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004443 }
4444
Paul Jensen2161a8e2014-09-11 11:00:39 -04004445 // Handles a network appearing or improving its score.
4446 //
4447 // - Evaluates all current NetworkRequests that can be
4448 // satisfied by newNetwork, and reassigns to newNetwork
4449 // any such requests for which newNetwork is the best.
4450 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004451 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004452 // needed. A network is needed if it is the best network for
4453 // one or more NetworkRequests, or if it is a VPN.
4454 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004455 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004456 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004457 //
4458 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4459 // networks that have no chance (i.e. even if validated)
4460 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004461 //
4462 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4463 // it does not remove NetworkRequests that other Networks could better satisfy.
4464 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4465 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4466 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004467 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004468 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004469 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4470 // performed to tear down unvalidated networks that have no chance (i.e. even if
4471 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004472 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004473 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004474 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004475 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004476 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004477 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004478 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004479 // Find and migrate to this Network any NetworkRequests for
4480 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004481 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004482 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004483 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004484 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004485 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4486 final boolean satisfies = newNetwork.satisfies(nri.request);
4487 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004488 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004489 log("Network " + newNetwork.name() + " was already satisfying" +
4490 " request " + nri.request.requestId + ". No change.");
4491 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004492 keep = true;
4493 continue;
4494 }
4495
4496 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004497 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004498 if (satisfies) {
Erik Kline371c7b72016-03-22 17:04:20 +09004499 if (!nri.isRequest()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004500 // This is not a request, it's a callback listener.
4501 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004502 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004503 continue;
4504 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004505
Robert Greenwalt7b816022014-04-18 15:25:25 -07004506 // next check if it's better than any current network we're using for
4507 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004508 if (VDBG) {
4509 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004510 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4511 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004512 }
4513 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004514 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004515 if (DBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004516 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004517 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004518 currentNetwork.networkRequests.remove(nri.request.requestId);
4519 currentNetwork.networkLingered.add(nri.request);
4520 affectedNetworks.add(currentNetwork);
4521 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004522 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004523 }
Paul Jensen573a0352015-01-08 10:49:34 -05004524 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004525 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004526 if (!newNetwork.addRequest(nri.request)) {
4527 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4528 }
4529 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004530 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004531 // Tell NetworkFactories about the new score, so they can stop
4532 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004533 // TODO - this could get expensive if we have alot of requests for this
4534 // network. Think about if there is a way to reduce this. Push
4535 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004536 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004537 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004538 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004539 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004540 }
4541 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004542 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4543 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4544 // mark it as no longer satisfying "nri". Because networks are processed by
4545 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4546 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4547 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4548 // This means this code doesn't have to handle the case where "currentNetwork" no
4549 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4550 if (DBG) {
4551 log("Network " + newNetwork.name() + " stopped satisfying" +
4552 " request " + nri.request.requestId);
4553 }
4554 newNetwork.networkRequests.remove(nri.request.requestId);
4555 if (currentNetwork == newNetwork) {
4556 mNetworkForRequestId.remove(nri.request.requestId);
4557 sendUpdatedScoreToFactories(nri.request, 0);
4558 } else {
Erik Kline371c7b72016-03-22 17:04:20 +09004559 if (nri.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004560 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4561 newNetwork.name() +
4562 " without updating mNetworkForRequestId or factories!");
4563 }
4564 }
4565 // TODO: technically, sending CALLBACK_LOST here is
4566 // incorrect if nri is a request (not a listen) and there
4567 // is a replacement network currently connected that can
4568 // satisfy it. However, the only capability that can both
4569 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4570 // so this code is only incorrect for a network that loses
4571 // the TRUSTED capability, which is a rare case.
4572 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004573 }
4574 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004575 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004576 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004577 if (nai.lingering) {
4578 // Already lingered. Nothing to do. This can only happen if "nai" is in
4579 // "affectedNetworks" twice. The reasoning being that to get added to
4580 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4581 // (i.e. not lingered) so it could have only been lingered by this loop.
4582 // unneeded(nai) will be false and we'll call unlinger() below which would
4583 // be bad, so handle it here.
4584 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004585 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004586 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004587 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004588 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004589 }
4590 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004591 if (isNewDefault) {
4592 // Notify system services that this network is up.
4593 makeDefault(newNetwork);
4594 synchronized (ConnectivityService.this) {
4595 // have a new default network, release the transition wakelock in
4596 // a second if it's held. The second pause is to allow apps
4597 // to reconnect over the new network
4598 if (mNetTransitionWakeLock.isHeld()) {
4599 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4600 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4601 mNetTransitionWakeLockSerialNumber, 0),
4602 1000);
4603 }
4604 }
4605 }
4606
4607 // do this after the default net is switched, but
4608 // before LegacyTypeTracker sends legacy broadcasts
4609 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4610
4611 if (isNewDefault) {
4612 // Maintain the illusion: since the legacy API only
4613 // understands one network at a time, we must pretend
4614 // that the current default network disconnected before
4615 // the new one connected.
4616 if (oldDefaultNetwork != null) {
4617 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4618 oldDefaultNetwork, true);
4619 }
4620 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4621 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4622 notifyLockdownVpn(newNetwork);
4623 }
4624
Robert Greenwalt7b816022014-04-18 15:25:25 -07004625 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004626 // Notify battery stats service about this network, both the normal
4627 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004628 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004629 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004630 final IBatteryStats bs = BatteryStatsService.getService();
4631 final int type = newNetwork.networkInfo.getType();
4632
4633 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4634 bs.noteNetworkInterfaceType(baseIface, type);
4635 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4636 final String stackedIface = stacked.getInterfaceName();
4637 bs.noteNetworkInterfaceType(stackedIface, type);
4638 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4639 }
4640 } catch (RemoteException ignored) {
4641 }
4642
Robert Greenwalt152ed372014-12-17 17:19:53 -08004643 // This has to happen after the notifyNetworkCallbacks as that tickles each
4644 // ConnectivityManager instance so that legacy requests correctly bind dns
4645 // requests to this network. The legacy users are listening for this bcast
4646 // and will generally do a dns request so they can ensureRouteToHost and if
4647 // they do that before the callbacks happen they'll use the default network.
4648 //
4649 // TODO: Is there still a race here? We send the broadcast
4650 // after sending the callback, but if the app can receive the
4651 // broadcast before the callback, it might still break.
4652 //
4653 // This *does* introduce a race where if the user uses the new api
4654 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4655 // they may get old info. Reverse this after the old startUsing api is removed.
4656 // This is on top of the multiple intent sequencing referenced in the todo above.
4657 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4658 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4659 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4660 // legacy type tracker filters out repeat adds
4661 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4662 }
4663 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004664
4665 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4666 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4667 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4668 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4669 if (newNetwork.isVPN()) {
4670 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4671 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004672 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004673 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4674 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004675 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004676 if (DBG) log("Reaping " + nai.name());
4677 teardownUnneededNetwork(nai);
4678 }
4679 }
4680 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004681 }
4682
Paul Jensen1c7ba022015-06-16 14:27:36 -04004683 /**
4684 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4685 * being disconnected.
4686 * @param changed If only one Network's score or capabilities have been modified since the last
4687 * time this function was called, pass this Network in this argument, otherwise pass
4688 * null.
4689 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4690 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4691 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4692 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4693 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004694 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004695 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004696 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4697 // to avoid the slowness. It is not simply enough to process just "changed", for
4698 // example in the case where "changed"'s score decreases and another network should begin
4699 // satifying a NetworkRequest that "changed" currently satisfies.
4700
4701 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4702 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4703 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004704 if (changed != null && oldScore < changed.getCurrentScore()) {
4705 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004706 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004707 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4708 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4709 // Rematch higher scoring networks first to prevent requests first matching a lower
4710 // scoring network and then a higher scoring network, which could produce multiple
4711 // callbacks and inadvertently unlinger networks.
4712 Arrays.sort(nais);
4713 for (NetworkAgentInfo nai : nais) {
4714 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004715 // Only reap the last time through the loop. Reaping before all rematching
4716 // is complete could incorrectly teardown a network that hasn't yet been
4717 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004718 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004719 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004720 }
4721 }
4722 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004723
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004724 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004725 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004726 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004727 // For now only update icons for default connection.
4728 // TODO: Update WiFi and cellular icons separately. b/17237507
4729 if (!isDefaultNetwork(nai)) return;
4730
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004731 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004732 // Don't repeat publish.
4733 if (newInetCondition == mDefaultInetConditionPublished) return;
4734
4735 mDefaultInetConditionPublished = newInetCondition;
4736 sendInetConditionBroadcast(nai.networkInfo);
4737 }
4738
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004739 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4740 if (mLockdownTracker != null) {
4741 if (nai != null && nai.isVPN()) {
4742 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4743 } else {
4744 mLockdownTracker.onNetworkInfoChanged();
4745 }
4746 }
4747 }
4748
Robert Greenwalt7b816022014-04-18 15:25:25 -07004749 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4750 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004751 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004752 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004753 synchronized (networkAgent) {
4754 oldInfo = networkAgent.networkInfo;
4755 networkAgent.networkInfo = newInfo;
4756 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004757 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004758
4759 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004760 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4761 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4762 notifyIfacesChangedForNetworkStats();
4763 } else if (VDBG) log("ignoring duplicate network state non-change");
4764 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004765 return;
4766 }
4767 if (DBG) {
4768 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4769 (oldInfo == null ? "null" : oldInfo.getState()) +
4770 " to " + state);
4771 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004772
Paul Jenseneec75412014-08-04 12:21:19 -04004773 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004774 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004775 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004776 if (networkAgent.isVPN()) {
4777 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004778 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4779 (networkAgent.networkMisc == null ||
4780 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004781 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004782 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4783 networkAgent.networkCapabilities.hasCapability(
4784 NET_CAPABILITY_NOT_RESTRICTED) ?
4785 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004786 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004787 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004788 loge("Error creating network " + networkAgent.network.netId + ": "
4789 + e.getMessage());
4790 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004791 }
Paul Jenseneec75412014-08-04 12:21:19 -04004792 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004793 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004794 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004795
Paul Jensenca8f16a2014-05-09 12:47:55 -04004796 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004797 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004798
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004799 if (networkAgent.isVPN()) {
4800 // Temporarily disable the default proxy (not global).
4801 synchronized (mProxyLock) {
4802 if (!mDefaultProxyDisabled) {
4803 mDefaultProxyDisabled = true;
4804 if (mGlobalProxy == null && mDefaultProxy != null) {
4805 sendProxyBroadcast(null);
4806 }
4807 }
4808 }
4809 // TODO: support proxy per network.
4810 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004811
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004812 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4813 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4814 // capabilities, so it only needs to be done once on initial connect, not every time the
4815 // network's capabilities change. Note that we do this before rematching the network,
4816 // so we could decide to tear it down immediately afterwards. That's fine though - on
4817 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4818 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004819 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004820
Paul Jensen2161a8e2014-09-11 11:00:39 -04004821 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004822 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004823
4824 // This has to happen after matching the requests, because callbacks are just requests.
4825 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004826 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004827 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004828 if (networkAgent.isVPN()) {
4829 synchronized (mProxyLock) {
4830 if (mDefaultProxyDisabled) {
4831 mDefaultProxyDisabled = false;
4832 if (mGlobalProxy == null && mDefaultProxy != null) {
4833 sendProxyBroadcast(mDefaultProxy);
4834 }
4835 }
4836 }
4837 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004838 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4839 state == NetworkInfo.State.SUSPENDED) {
4840 // going into or coming out of SUSPEND: rescore and notify
4841 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004842 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004843 }
4844 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4845 ConnectivityManager.CALLBACK_SUSPENDED :
4846 ConnectivityManager.CALLBACK_RESUMED));
4847 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004848 }
4849 }
4850
Robert Greenwaltac96c522014-06-03 16:43:57 -07004851 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4852 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004853 if (score < 0) {
4854 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4855 "). Bumping score to min of 0");
4856 score = 0;
4857 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004858
Paul Jensen2161a8e2014-09-11 11:00:39 -04004859 final int oldScore = nai.getCurrentScore();
4860 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004861
Paul Jensen85cf78e2015-06-25 13:25:07 -04004862 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004863
Paul Jensenc8b9a742014-09-30 15:37:41 -04004864 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004865 }
4866
Robert Greenwalt9258c642014-03-26 16:47:06 -07004867 // notify only this one new request of the current state
4868 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4869 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4870 // TODO - read state from monitor to decide what to send.
4871// if (nai.networkMonitor.isLingering()) {
4872// notifyType = NetworkCallbacks.LOSING;
4873// } else if (nai.networkMonitor.isEvaluating()) {
4874// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4875// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004876 if (nri.mPendingIntent == null) {
4877 callCallbackForRequest(nri, nai, notifyType);
4878 } else {
4879 sendPendingIntentForRequest(nri, nai, notifyType);
4880 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004881 }
4882
Robert Greenwalt8d482522015-06-24 13:23:42 -07004883 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004884 // The NetworkInfo we actually send out has no bearing on the real
4885 // state of affairs. For example, if the default connection is mobile,
4886 // and a request for HIPRI has just gone away, we need to pretend that
4887 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4888 // the state to DISCONNECTED, even though the network is of type MOBILE
4889 // and is still connected.
4890 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4891 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004892 if (state != DetailedState.DISCONNECTED) {
4893 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004894 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004895 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004896 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004897 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4898 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4899 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4900 if (info.isFailover()) {
4901 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4902 nai.networkInfo.setFailover(false);
4903 }
4904 if (info.getReason() != null) {
4905 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4906 }
4907 if (info.getExtraInfo() != null) {
4908 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4909 }
4910 NetworkAgentInfo newDefaultAgent = null;
4911 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004912 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004913 if (newDefaultAgent != null) {
4914 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4915 newDefaultAgent.networkInfo);
4916 } else {
4917 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4918 }
4919 }
4920 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4921 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004922 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004923 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004924 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004925 }
4926 }
4927 }
4928
Robert Greenwalt7b816022014-04-18 15:25:25 -07004929 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004930 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004931 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004932 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4933 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4934 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004935 if (nri.mPendingIntent == null) {
4936 callCallbackForRequest(nri, networkAgent, notifyType);
4937 } else {
4938 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4939 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004940 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004941 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004942
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004943 private String notifyTypeToName(int notifyType) {
4944 switch (notifyType) {
4945 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4946 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4947 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4948 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4949 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4950 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4951 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4952 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4953 }
4954 return "UNKNOWN";
4955 }
4956
Jeff Sharkey69736342014-12-08 14:50:12 -08004957 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004958 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
4959 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08004960 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004961 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08004962 try {
4963 mStatsService.forceUpdateIfaces();
4964 } catch (Exception ignored) {
4965 }
4966 }
4967
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004968 @Override
4969 public boolean addVpnAddress(String address, int prefixLength) {
4970 throwIfLockdownEnabled();
4971 int user = UserHandle.getUserId(Binder.getCallingUid());
4972 synchronized (mVpns) {
4973 return mVpns.get(user).addAddress(address, prefixLength);
4974 }
4975 }
4976
4977 @Override
4978 public boolean removeVpnAddress(String address, int prefixLength) {
4979 throwIfLockdownEnabled();
4980 int user = UserHandle.getUserId(Binder.getCallingUid());
4981 synchronized (mVpns) {
4982 return mVpns.get(user).removeAddress(address, prefixLength);
4983 }
4984 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004985
4986 @Override
4987 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4988 throwIfLockdownEnabled();
4989 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004990 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004991 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004992 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004993 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004994 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004995 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004996 }
4997 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004998 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004999
5000 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005001 public String getCaptivePortalServerUrl() {
5002 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5003 }
5004
5005 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005006 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5007 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5008 enforceKeepalivePermission();
5009 mKeepaliveTracker.startNattKeepalive(
5010 getNetworkAgentInfoForNetwork(network),
5011 intervalSeconds, messenger, binder,
5012 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5013 }
5014
5015 @Override
5016 public void stopKeepalive(Network network, int slot) {
5017 mHandler.sendMessage(mHandler.obtainMessage(
5018 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5019 }
5020
5021 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005022 public void factoryReset() {
5023 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005024
5025 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5026 return;
5027 }
5028
Robin Lee3b3dd942015-05-12 18:14:58 +01005029 final int userId = UserHandle.getCallingUserId();
5030
Stuart Scottf1fb3972015-04-02 18:00:02 -07005031 // Turn airplane mode off
5032 setAirplaneMode(false);
5033
Stuart Scotte3e314d2015-04-20 14:07:45 -07005034 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5035 // Untether
5036 for (String tether : getTetheredIfaces()) {
5037 untether(tether);
5038 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005039 }
5040
Stuart Scotte3e314d2015-04-20 14:07:45 -07005041 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
5042 // Turn VPN off
5043 VpnConfig vpnConfig = getVpnConfig(userId);
5044 if (vpnConfig != null) {
5045 if (vpnConfig.legacy) {
5046 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5047 } else {
5048 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5049 // in the future without user intervention.
5050 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005051
Stuart Scotte3e314d2015-04-20 14:07:45 -07005052 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
5053 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005054 }
5055 }
5056 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005057
5058 @VisibleForTesting
5059 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5060 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5061 return new NetworkMonitor(context, handler, nai, defaultRequest);
5062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005063}