blob: d836a903b5cecf230d4c8f0d5f799617fa7762bd [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;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900119import com.android.internal.util.MessageUtils;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700120import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700121import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400122import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900123import com.android.server.connectivity.KeepaliveTracker;
Erik Kline379747a2015-06-05 17:47:34 +0900124import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900125import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700126import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400127import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400128import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700129import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800130import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700131import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700132import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700133import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700134import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700135import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700136
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700137import org.xmlpull.v1.XmlPullParser;
138import org.xmlpull.v1.XmlPullParserException;
139
140import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700142import java.io.FileNotFoundException;
143import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700144import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700146import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700147import java.net.InetAddress;
148import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700149import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700150import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700151import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700152import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700153import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700154import java.util.HashSet;
Lorenzo Colittic3f21f32015-07-06 23:50:27 +0900155import java.util.SortedSet;
156import java.util.TreeSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700157import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700158import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700159import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
161/**
162 * @hide
163 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800164public class ConnectivityService extends IConnectivityManager.Stub
165 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700166 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167
Joe Onorato12acbd72016-02-01 17:49:31 -0800168 private static final boolean DBG = false;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700169 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170
Jake Hamby786e71a2014-02-06 14:43:50 -0800171 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900172 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700173
Jeff Sharkey899223b2012-08-04 15:24:58 -0700174 // TODO: create better separation between radio types and network types
175
Robert Greenwalt42acef32009-08-12 16:08:25 -0700176 // how long to wait before switching back to a radio's default network
177 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
178 // system property that can override the above value
179 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
180 "android.telephony.apn-restore";
181
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900182 // How long to wait before putting up a "This network doesn't have an Internet connection,
183 // connect anyway?" dialog after the user selects a network that doesn't validate.
184 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
185
Jeremy Joslin79294842014-12-03 17:15:28 -0800186 // How long to delay to removal of a pending intent based request.
187 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
188 private final int mReleasePendingIntentDelayMs;
189
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800190 private Tethering mTethering;
191
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700192 private final PermissionMonitor mPermissionMonitor;
193
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700194 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700195
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700196 @GuardedBy("mVpns")
197 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700198
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700199 private boolean mLockdownEnabled;
200 private LockdownVpnTracker mLockdownTracker;
201
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700202 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
203 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700204 /** Currently active network rules by UID. */
205 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700206 /** Set of ifaces that are costly. */
207 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700208
Erik Klineda4bfa82015-04-30 12:58:40 +0900209 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700211 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700212 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800214 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215
216 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700217 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700219 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800220 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700221 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700222
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700223 private String mCurrentTcpBufferSizes;
224
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700225 private static final int ENABLED = 1;
226 private static final int DISABLED = 0;
227
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900228 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
229 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class });
230
Paul Jensenb10e37f2014-11-25 12:33:08 -0500231 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400232 // Tear down networks that have no chance (e.g. even if validated) of becoming
233 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500234 // all networks have been rematched against all NetworkRequests.
235 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400236 // Don't reap networks. This should be passed when some networks have not yet been
237 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500238 DONT_REAP
239 };
240
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700241 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700242 * used internally to change our mobile data enabled flag
243 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700244 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700245
246 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700247 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700248 * from one net to another. Clear happens when we get a new
249 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
250 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700251 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700252 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700253
Robert Greenwalt434203a2010-10-11 16:00:27 -0700254 /**
255 * used internally to reload global proxy settings
256 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700257 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700258
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700259 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400260 * PAC manager has received new port.
261 */
262 private static final int EVENT_PROXY_HAS_CHANGED = 16;
263
Robert Greenwalte049c232014-04-11 15:53:27 -0700264 /**
265 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700266 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700267 */
268 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
269
Robert Greenwalt7b816022014-04-18 15:25:25 -0700270 /**
271 * used internally when registering NetworkAgents
272 * obj = Messenger
273 */
274 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
275
Robert Greenwalt9258c642014-03-26 16:47:06 -0700276 /**
277 * used to add a network request
278 * includes a NetworkRequestInfo
279 */
280 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
281
282 /**
283 * indicates a timeout period is over - check if we had a network yet or not
284 * and if not, call the timeout calback (but leave the request live until they
285 * cancel it.
286 * includes a NetworkRequestInfo
287 */
288 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
289
290 /**
291 * used to add a network listener - no request
292 * includes a NetworkRequestInfo
293 */
294 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
295
296 /**
297 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400298 * arg1 = UID of caller
299 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700300 */
301 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
302
Robert Greenwalta67be032014-05-16 15:49:14 -0700303 /**
304 * used internally when registering NetworkFactories
305 * obj = Messenger
306 */
307 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
308
Robert Greenwalt27711812014-06-25 16:45:57 -0700309 /**
310 * used internally to expire a wakelock when transitioning
311 * from one net to another. Expire happens when we fail to find
312 * a new network (typically after 1 minute) -
313 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
314 * a replacement network.
315 */
316 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
317
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700318 /**
319 * Used internally to indicate the system is ready.
320 */
321 private static final int EVENT_SYSTEM_READY = 25;
322
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800323 /**
324 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400325 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800326 */
327 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
328
329 /**
330 * used to remove a pending intent and its associated network request.
331 * arg1 = UID of caller
332 * obj = PendingIntent
333 */
334 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
335
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900336 /**
337 * used to specify whether a network should be used even if unvalidated.
338 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
339 * arg2 = whether to remember this choice in the future (1 or 0)
340 * obj = network
341 */
342 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
343
344 /**
345 * used to ask the user to confirm a connection to an unvalidated network.
346 * obj = network
347 */
348 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700349
Erik Klineda4bfa82015-04-30 12:58:40 +0900350 /**
351 * used internally to (re)configure mobile data always-on settings.
352 */
353 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
354
Paul Jensen694f2b82015-06-17 14:15:39 -0400355 /**
356 * used to add a network listener with a pending intent
357 * obj = NetworkRequestInfo
358 */
359 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
360
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900361 /** Handler thread used for both of the handlers below. */
362 @VisibleForTesting
363 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700364 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700365 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700366 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700367 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700368
Mike Lockwood0f79b542009-08-14 14:18:49 -0400369 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800370 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400371
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700372 private PowerManager.WakeLock mNetTransitionWakeLock;
373 private String mNetTransitionWakeLockCausedBy = "";
374 private int mNetTransitionWakeLockSerialNumber;
375 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800376 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700377
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700378 // used in DBG mode to track inet condition reports
379 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
380 private ArrayList mInetLog;
381
Robert Greenwalt434203a2010-10-11 16:00:27 -0700382 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400383 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700384 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700385 private boolean mDefaultProxyDisabled = false;
386
Robert Greenwalt434203a2010-10-11 16:00:27 -0700387 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400388 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700389
Jason Monk602b2322013-07-03 17:04:33 -0400390 private PacManager mPacManager = null;
391
Erik Klineda4bfa82015-04-30 12:58:40 +0900392 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700393
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400394 private UserManager mUserManager;
395
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700396 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700397 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700398
Robert Greenwalt50393202011-06-21 17:26:14 -0700399 // the set of network types that can only be enabled by system/sig apps
400 List mProtectedNetworks;
401
John Spurlockbf991a82013-06-24 14:20:23 -0400402 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700403
Wink Savilleab9321d2013-06-29 21:10:57 -0700404 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400405
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900406 private KeepaliveTracker mKeepaliveTracker;
407
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700408 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
409 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700410 private final static int MAX_NET_ID = 65535;
411 private int mNextNetId = MIN_NET_ID;
412
Robert Greenwalt34524f02014-05-18 16:22:10 -0700413 // sequence number of NetworkRequests
414 private int mNextNetworkRequestId = 1;
415
Erik Kline7523eb32015-07-09 18:24:03 +0900416 // NetworkRequest activity String log entries.
417 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
418 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
419
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700420 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
421 private static final int MAX_VALIDATION_LOGS = 10;
422 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
423 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
424
425 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
426 synchronized(mValidationLogs) {
427 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
428 mValidationLogs.removeLast();
429 }
430 mValidationLogs.addFirst(new Pair(network, log));
431 }
432 }
433
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700434 /**
435 * Implements support for the legacy "one network per network type" model.
436 *
437 * We used to have a static array of NetworkStateTrackers, one for each
438 * network type, but that doesn't work any more now that we can have,
439 * for example, more that one wifi network. This class stores all the
440 * NetworkAgentInfo objects that support a given type, but the legacy
441 * API will only see the first one.
442 *
443 * It serves two main purposes:
444 *
445 * 1. Provide information about "the network for a given type" (since this
446 * API only supports one).
447 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
448 * the first network for a given type changes, or if the default network
449 * changes.
450 */
451 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900452
Joe Onorato12acbd72016-02-01 17:49:31 -0800453 private static final boolean DBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900454 private static final boolean VDBG = false;
455 private static final String TAG = "CSLegacyTypeTracker";
456
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700457 /**
458 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
459 * Each list holds references to all NetworkAgentInfos that are used to
460 * satisfy requests for that network type.
461 *
462 * This array is built out at startup such that an unsupported network
463 * doesn't get an ArrayList instance, making this a tristate:
464 * unsupported, supported but not active and active.
465 *
466 * The actual lists are populated when we scan the network types that
467 * are supported on this device.
468 */
469 private ArrayList<NetworkAgentInfo> mTypeLists[];
470
471 public LegacyTypeTracker() {
472 mTypeLists = (ArrayList<NetworkAgentInfo>[])
473 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
474 }
475
476 public void addSupportedType(int type) {
477 if (mTypeLists[type] != null) {
478 throw new IllegalStateException(
479 "legacy list for type " + type + "already initialized");
480 }
481 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
482 }
483
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700484 public boolean isTypeSupported(int type) {
485 return isNetworkTypeValid(type) && mTypeLists[type] != null;
486 }
487
488 public NetworkAgentInfo getNetworkForType(int type) {
489 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
490 return mTypeLists[type].get(0);
491 } else {
492 return null;
493 }
494 }
495
Robert Greenwalt8d482522015-06-24 13:23:42 -0700496 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900497 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900498 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700499 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900500 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900501 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900502 }
503 }
504
505 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700506 public void add(int type, NetworkAgentInfo nai) {
507 if (!isTypeSupported(type)) {
508 return; // Invalid network type.
509 }
510 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
511
512 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
513 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700514 return;
515 }
516
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900517 list.add(nai);
518
519 // 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 +0900520 final boolean isDefaultNetwork = isDefaultNetwork(nai);
521 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700522 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
523 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700524 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700525 }
526
Lorenzo Colittia793a672014-07-31 23:20:17 +0900527 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900528 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900529 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
530 if (list == null || list.isEmpty()) {
531 return;
532 }
533
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900534 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900535
536 if (!list.remove(nai)) {
537 return;
538 }
539
Robert Greenwalt8d482522015-06-24 13:23:42 -0700540 final DetailedState state = DetailedState.DISCONNECTED;
541
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900542 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700543 maybeLogBroadcast(nai, state, type, wasDefault);
544 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900545 }
546
547 if (!list.isEmpty() && wasFirstNetwork) {
548 if (DBG) log("Other network available for type " + type +
549 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900550 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700551 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
552 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900553 }
554 }
555
556 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900557 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
558 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700559 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900560 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561 }
562 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700563
Robert Greenwalt8d482522015-06-24 13:23:42 -0700564 // send out another legacy broadcast - currently only used for suspend/unsuspend
565 // toggle
566 public void update(NetworkAgentInfo nai) {
567 final boolean isDefault = isDefaultNetwork(nai);
568 final DetailedState state = nai.networkInfo.getDetailedState();
569 for (int type = 0; type < mTypeLists.length; type++) {
570 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700571 final boolean contains = (list != null && list.contains(nai));
Robert Greenwalt8d482522015-06-24 13:23:42 -0700572 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700573 if (isFirst || (contains && isDefault)) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700574 maybeLogBroadcast(nai, state, type, isDefault);
575 sendLegacyNetworkBroadcast(nai, state, type);
576 }
577 }
578 }
579
Lorenzo Colittia793a672014-07-31 23:20:17 +0900580 private String naiToString(NetworkAgentInfo nai) {
581 String name = (nai != null) ? nai.name() : "null";
582 String state = (nai.networkInfo != null) ?
583 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
584 "???/???";
585 return name + " " + state;
586 }
587
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700588 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900589 pw.println("mLegacyTypeTracker:");
590 pw.increaseIndent();
591 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700592 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900593 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700594 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900595 pw.println();
596 pw.println("Current state:");
597 pw.increaseIndent();
598 for (int type = 0; type < mTypeLists.length; type++) {
599 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
600 for (NetworkAgentInfo nai : mTypeLists[type]) {
601 pw.println(type + " " + naiToString(nai));
602 }
603 }
604 pw.decreaseIndent();
605 pw.decreaseIndent();
606 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700607 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900608
609 // This class needs its own log method because it has a different TAG.
610 private void log(String s) {
611 Slog.d(TAG, s);
612 }
613
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700614 }
615 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
616
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900617 @VisibleForTesting
618 protected HandlerThread createHandlerThread() {
619 return new HandlerThread("ConnectivityServiceThread");
620 }
621
Jeff Sharkey899223b2012-08-04 15:24:58 -0700622 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700623 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800624 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800625
Erik Klineda4bfa82015-04-30 12:58:40 +0900626 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900627 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
Erik Kline371c7b72016-03-22 17:04:20 +0900628 new Binder(), NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +0900629 mNetworkRequests.put(mDefaultRequest, defaultNRI);
630 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900631
632 mDefaultMobileDataRequest = createInternetRequestForTransport(
633 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700634
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900635 mHandlerThread = createHandlerThread();
636 mHandlerThread.start();
637 mHandler = new InternalHandler(mHandlerThread.getLooper());
638 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700639
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800640 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800641 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
642 String id = Settings.Secure.getString(context.getContentResolver(),
643 Settings.Secure.ANDROID_ID);
644 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700645 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800646 SystemProperties.set("net.hostname", name);
647 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800648 }
649
Jeremy Joslin79294842014-12-03 17:15:28 -0800650 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
651 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
652
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700653 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700654 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800655 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700656 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700657 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700658 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700659
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700660 try {
661 mPolicyManager.registerListener(mPolicyListener);
662 } catch (RemoteException e) {
663 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700664 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700665 }
666
667 final PowerManager powerManager = (PowerManager) context.getSystemService(
668 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700669 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
670 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
671 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800672 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700673
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700674 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700675
Wink Saville51f456f2013-04-23 14:26:51 -0700676 // TODO: What is the "correct" way to do determine if this is a wifi only device?
677 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
678 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700679 String[] naStrings = context.getResources().getStringArray(
680 com.android.internal.R.array.networkAttributes);
681 for (String naString : naStrings) {
682 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700683 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700684 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700685 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800686 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700687 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700688 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700689 }
Wink Saville51f456f2013-04-23 14:26:51 -0700690 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
691 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
692 n.type);
693 continue;
694 }
Wink Saville975c8482011-04-07 14:23:45 -0700695 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800696 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700697 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700698 continue;
699 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700700 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700701
Wink Saville975c8482011-04-07 14:23:45 -0700702 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700703 mNetworksDefined++;
704 } catch(Exception e) {
705 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700706 }
707 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700708
709 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
710 if (mNetConfigs[TYPE_VPN] == null) {
711 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
712 // don't need to add TYPE_VPN to mNetConfigs.
713 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
714 mNetworksDefined++; // used only in the log() statement below.
715 }
716
Wink Saville5e56bc52013-07-29 15:00:57 -0700717 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700718
Robert Greenwalt50393202011-06-21 17:26:14 -0700719 mProtectedNetworks = new ArrayList<Integer>();
720 int[] protectedNetworks = context.getResources().getIntArray(
721 com.android.internal.R.array.config_protectedNetworks);
722 for (int p : protectedNetworks) {
723 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
724 mProtectedNetworks.add(p);
725 } else {
726 if (DBG) loge("Ignoring protectedNetwork " + p);
727 }
728 }
729
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700730 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
731 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700732
Jeremy Kleinfa8712b2016-01-26 11:10:55 -0800733 mTethering = new Tethering(mContext, mNetd, statsService);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800734
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700735 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
736
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700737 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700738 IntentFilter intentFilter = new IntentFilter();
739 intentFilter.addAction(Intent.ACTION_USER_STARTING);
740 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700741 intentFilter.addAction(Intent.ACTION_USER_ADDED);
742 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000743 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700744 mContext.registerReceiverAsUser(
745 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900746
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700747 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700748 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700749 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700750 } catch (RemoteException e) {
751 loge("Error registering observer :" + e);
752 }
753
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700754 if (DBG) {
755 mInetLog = new ArrayList();
756 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700757
Erik Klineda4bfa82015-04-30 12:58:40 +0900758 mSettingsObserver = new SettingsObserver(mContext, mHandler);
759 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800760
John Spurlockbf991a82013-06-24 14:20:23 -0400761 mDataConnectionStats = new DataConnectionStats(mContext);
762 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400763
Jason Monkdecd2952013-10-10 14:02:51 -0400764 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700765
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400766 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900767
768 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700770
Erik Klineda4bfa82015-04-30 12:58:40 +0900771 private NetworkRequest createInternetRequestForTransport(int transportType) {
772 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900773 netCap.addCapability(NET_CAPABILITY_INTERNET);
774 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900775 if (transportType > -1) {
776 netCap.addTransportType(transportType);
777 }
778 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
779 }
780
781 private void handleMobileDataAlwaysOn() {
782 final boolean enable = (Settings.Global.getInt(
783 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
784 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
785 if (enable == isEnabled) {
786 return; // Nothing to do.
787 }
788
789 if (enable) {
790 handleRegisterNetworkRequest(new NetworkRequestInfo(
Erik Kline371c7b72016-03-22 17:04:20 +0900791 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestType.REQUEST));
Erik Klineda4bfa82015-04-30 12:58:40 +0900792 } else {
793 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
794 }
795 }
796
797 private void registerSettingsCallbacks() {
798 // Watch for global HTTP proxy changes.
799 mSettingsObserver.observe(
800 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
801 EVENT_APPLY_GLOBAL_HTTP_PROXY);
802
803 // Watch for whether or not to keep mobile data always on.
804 mSettingsObserver.observe(
805 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
806 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
807 }
808
Robert Greenwalt34524f02014-05-18 16:22:10 -0700809 private synchronized int nextNetworkRequestId() {
810 return mNextNetworkRequestId++;
811 }
812
Paul Jensen67b0b072015-06-10 11:22:17 -0400813 @VisibleForTesting
814 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400815 synchronized (mNetworkForNetId) {
816 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
817 int netId = mNextNetId;
818 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
819 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500820 if (!mNetIdInUse.get(netId)) {
821 mNetIdInUse.put(netId, true);
822 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400823 }
824 }
825 }
826 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700827 }
828
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800829 private NetworkState getFilteredNetworkState(int networkType, int uid) {
830 NetworkInfo info = null;
831 LinkProperties lp = null;
832 NetworkCapabilities nc = null;
833 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800834 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800835
836 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
837 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
838 if (nai != null) {
839 synchronized (nai) {
840 info = new NetworkInfo(nai.networkInfo);
841 lp = new LinkProperties(nai.linkProperties);
842 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400843 // Network objects are outwardly immutable so there is no point to duplicating.
844 // Duplicating also precludes sharing socket factories and connection pools.
845 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800846 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800847 }
848 info.setType(networkType);
849 } else {
850 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
851 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
852 info.setIsAvailable(true);
853 lp = new LinkProperties();
854 nc = new NetworkCapabilities();
855 network = null;
856 }
857 info = getFilteredNetworkInfo(info, lp, uid);
858 }
859
Jeff Sharkey32566012014-12-02 18:30:14 -0800860 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400861 }
862
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800863 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
864 if (network == null) {
865 return null;
866 }
867 synchronized (mNetworkForNetId) {
868 return mNetworkForNetId.get(network.netId);
869 }
870 };
871
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900872 private Network[] getVpnUnderlyingNetworks(int uid) {
873 if (!mLockdownEnabled) {
874 int user = UserHandle.getUserId(uid);
875 synchronized (mVpns) {
876 Vpn vpn = mVpns.get(user);
877 if (vpn != null && vpn.appliesToUid(uid)) {
878 return vpn.getUnderlyingNetworks();
879 }
880 }
881 }
882 return null;
883 }
884
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800885 private NetworkState getUnfilteredActiveNetworkState(int uid) {
886 NetworkInfo info = null;
887 LinkProperties lp = null;
888 NetworkCapabilities nc = null;
889 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800890 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800891
Paul Jensen85cf78e2015-06-25 13:25:07 -0400892 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800893
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900894 final Network[] networks = getVpnUnderlyingNetworks(uid);
895 if (networks != null) {
896 // getUnderlyingNetworks() returns:
897 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
898 // empty array => the VPN explicitly said "no default network".
899 // non-empty array => the VPN specified one or more default networks; we use the
900 // first one.
901 if (networks.length > 0) {
902 nai = getNetworkAgentInfoForNetwork(networks[0]);
903 } else {
904 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800905 }
906 }
907
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800908 if (nai != null) {
909 synchronized (nai) {
910 info = new NetworkInfo(nai.networkInfo);
911 lp = new LinkProperties(nai.linkProperties);
912 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400913 // Network objects are outwardly immutable so there is no point to duplicating.
914 // Duplicating also precludes sharing socket factories and connection pools.
915 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800916 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800917 }
918 }
919
Jeff Sharkey32566012014-12-02 18:30:14 -0800920 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400921 }
922
923 /**
924 * Check if UID should be blocked from using the network with the given LinkProperties.
925 */
926 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700927 final boolean networkCostly;
928 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700929
Robert Greenwalt12e67352014-05-13 21:41:06 -0700930 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700931 synchronized (mRulesLock) {
932 networkCostly = mMeteredIfaces.contains(iface);
933 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700934 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700935
Jeff Sharkeydc988062015-09-14 10:09:47 -0700936 if (uidRules == RULE_REJECT_ALL) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700937 return true;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700938 } else if ((uidRules == RULE_REJECT_METERED) && networkCostly) {
939 return true;
940 } else {
941 return false;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700942 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700943 }
944
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900945 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
946 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) return;
947 boolean removed = false;
948 boolean added = false;
949 synchronized (mBlockedAppUids) {
950 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
951 added = true;
952 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
953 removed = true;
954 }
955 }
956 if (added) log("Returning blocked NetworkInfo to uid=" + uid);
957 else if (removed) log("Returning unblocked NetworkInfo to uid=" + uid);
958 }
959
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700960 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700961 * Return a filtered {@link NetworkInfo}, potentially marked
962 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800963 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700964 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800965 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
966 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400967 // network is blocked; clone and override state
968 info = new NetworkInfo(info);
969 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700970 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800971 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700972 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900973 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700974 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700975 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700976 }
977
978 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 * Return NetworkInfo for the active (i.e., connected) network interface.
980 * It is assumed that at most one network is active at a time. If more
981 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700982 * @return the info for the active network, or {@code null} if none is
983 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700985 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700987 enforceAccessPermission();
988 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800989 NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900990 NetworkInfo ni = getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
991 maybeLogBlockedNetworkInfo(ni, uid);
992 return ni;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 }
994
Paul Jensen31a94f42015-02-13 14:18:39 -0500995 @Override
996 public Network getActiveNetwork() {
997 enforceAccessPermission();
998 final int uid = Binder.getCallingUid();
999 final int user = UserHandle.getUserId(uid);
1000 int vpnNetId = NETID_UNSET;
1001 synchronized (mVpns) {
1002 final Vpn vpn = mVpns.get(user);
1003 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1004 }
1005 NetworkAgentInfo nai;
1006 if (vpnNetId != NETID_UNSET) {
1007 synchronized (mNetworkForNetId) {
1008 nai = mNetworkForNetId.get(vpnNetId);
1009 }
1010 if (nai != null) return nai.network;
1011 }
1012 nai = getDefaultNetwork();
1013 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
1014 return nai != null ? nai.network : null;
1015 }
1016
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001017 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1018 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001019 final int uid = Binder.getCallingUid();
1020 NetworkState state = getUnfilteredActiveNetworkState(uid);
1021 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001022 }
1023
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001024 @Override
1025 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1026 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001027 NetworkState state = getUnfilteredActiveNetworkState(uid);
1028 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001029 }
1030
1031 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 public NetworkInfo getNetworkInfo(int networkType) {
1033 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001034 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001035 if (getVpnUnderlyingNetworks(uid) != null) {
1036 // A VPN is active, so we may need to return one of its underlying networks. This
1037 // information is not available in LegacyTypeTracker, so we have to get it from
1038 // getUnfilteredActiveNetworkState.
1039 NetworkState state = getUnfilteredActiveNetworkState(uid);
1040 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1041 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1042 }
1043 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001044 NetworkState state = getFilteredNetworkState(networkType, uid);
1045 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 }
1047
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001048 @Override
1049 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1050 enforceAccessPermission();
1051 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001052 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001053 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1054 if (nai != null) {
1055 synchronized (nai) {
1056 info = new NetworkInfo(nai.networkInfo);
1057 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001058 }
1059 }
1060 return info;
1061 }
1062
1063 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 public NetworkInfo[] getAllNetworkInfo() {
1065 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001066 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001067 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1068 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001069 NetworkInfo info = getNetworkInfo(networkType);
1070 if (info != null) {
1071 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001074 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 }
1076
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001077 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001078 public Network getNetworkForType(int networkType) {
1079 enforceAccessPermission();
1080 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001081 NetworkState state = getFilteredNetworkState(networkType, uid);
1082 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1083 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001084 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001085 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001086 }
1087
1088 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001089 public Network[] getAllNetworks() {
1090 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001091 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001092 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001093 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001094 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001095 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001096 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001097 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001098 }
1099
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001100 @Override
1101 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1102 // The basic principle is: if an app's traffic could possibly go over a
1103 // network, without the app doing anything multinetwork-specific,
1104 // (hence, by "default"), then include that network's capabilities in
1105 // the array.
1106 //
1107 // In the normal case, app traffic only goes over the system's default
1108 // network connection, so that's the only network returned.
1109 //
1110 // With a VPN in force, some app traffic may go into the VPN, and thus
1111 // over whatever underlying networks the VPN specifies, while other app
1112 // traffic may go over the system default network (e.g.: a split-tunnel
1113 // VPN, or an app disallowed by the VPN), so the set of networks
1114 // returned includes the VPN's underlying networks and the system
1115 // default.
1116 enforceAccessPermission();
1117
1118 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1119
1120 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001121 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001122 if (nc != null) {
1123 result.put(nai.network, nc);
1124 }
1125
1126 if (!mLockdownEnabled) {
1127 synchronized (mVpns) {
1128 Vpn vpn = mVpns.get(userId);
1129 if (vpn != null) {
1130 Network[] networks = vpn.getUnderlyingNetworks();
1131 if (networks != null) {
1132 for (Network network : networks) {
1133 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001134 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001135 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001136 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001137 }
1138 }
1139 }
1140 }
1141 }
1142 }
1143
1144 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1145 out = result.values().toArray(out);
1146 return out;
1147 }
1148
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001149 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001150 public boolean isNetworkSupported(int networkType) {
1151 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001152 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001153 }
1154
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001155 /**
1156 * Return LinkProperties for the active (i.e., connected) default
1157 * network interface. It is assumed that at most one default network
1158 * is active at a time. If more than one is active, it is indeterminate
1159 * which will be returned.
1160 * @return the ip properties for the active network, or {@code null} if
1161 * none is active
1162 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001163 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001164 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001165 enforceAccessPermission();
1166 final int uid = Binder.getCallingUid();
1167 NetworkState state = getUnfilteredActiveNetworkState(uid);
1168 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001169 }
1170
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001171 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001172 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001173 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001174 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1175 if (nai != null) {
1176 synchronized (nai) {
1177 return new LinkProperties(nai.linkProperties);
1178 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001179 }
1180 return null;
1181 }
1182
Robert Greenwalt12e67352014-05-13 21:41:06 -07001183 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001184 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001185 public LinkProperties getLinkProperties(Network network) {
1186 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001187 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001188 if (nai != null) {
1189 synchronized (nai) {
1190 return new LinkProperties(nai.linkProperties);
1191 }
1192 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001193 return null;
1194 }
1195
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001196 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001197 if (nai != null) {
1198 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001199 if (nai.networkCapabilities != null) {
1200 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001201 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001202 }
1203 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001204 return null;
1205 }
1206
1207 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001208 public NetworkCapabilities getNetworkCapabilities(Network network) {
1209 enforceAccessPermission();
1210 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1211 }
1212
1213 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001214 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001215 // Require internal since we're handing out IMSI details
1216 enforceConnectivityInternalPermission();
1217
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001218 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001219 for (Network network : getAllNetworks()) {
1220 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1221 if (nai != null) {
1222 synchronized (nai) {
1223 final String subscriberId = (nai.networkMisc != null)
1224 ? nai.networkMisc.subscriberId : null;
1225 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1226 nai.networkCapabilities, network, subscriberId, null));
1227 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001228 }
1229 }
1230 return result.toArray(new NetworkState[result.size()]);
1231 }
1232
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001233 @Override
1234 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1235 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001236 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001237 final long token = Binder.clearCallingIdentity();
1238 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001239 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1240 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001241 try {
1242 return mPolicyManager.getNetworkQuotaInfo(state);
1243 } catch (RemoteException e) {
1244 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001245 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001246 return null;
1247 } finally {
1248 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001249 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001250 }
1251
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001252 @Override
1253 public boolean isActiveNetworkMetered() {
1254 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001255 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001256 final long token = Binder.clearCallingIdentity();
1257 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001258 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001259 } finally {
1260 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001261 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001262 }
1263
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001264 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1265 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1266 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001267 try {
1268 return mPolicyManager.isNetworkMetered(state);
1269 } catch (RemoteException e) {
1270 }
1271 }
1272 return false;
1273 }
1274
Jeff Sharkey216c1812012-08-05 14:29:23 -07001275 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1276 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001277 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001278 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001279 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001280 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001281 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001282
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001283 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 * Ensure that a network route exists to deliver traffic to the specified
1285 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001286 * @param networkType the type of the network over which traffic to the
1287 * specified host is to be routed
1288 * @param hostAddress the IP address of the host to which the route is
1289 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 * @return {@code true} on success, {@code false} on failure
1291 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001292 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001294 if (mProtectedNetworks.contains(networkType)) {
1295 enforceConnectivityInternalPermission();
1296 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001297
Chad Brubakerc0234532014-02-14 13:24:29 -08001298 InetAddress addr;
1299 try {
1300 addr = InetAddress.getByAddress(hostAddress);
1301 } catch (UnknownHostException e) {
1302 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1303 return false;
1304 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001307 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 return false;
1309 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001310
1311 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1312 if (nai == null) {
1313 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1314 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1315 } else {
1316 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1317 }
1318 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001319 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001320
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001321 DetailedState netState;
1322 synchronized (nai) {
1323 netState = nai.networkInfo.getDetailedState();
1324 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001325
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001326 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001327 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001328 log("requestRouteToHostAddress on down network "
1329 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001330 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001331 }
1332 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001334
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001335 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001336 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001337 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001338 LinkProperties lp;
1339 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001340 synchronized (nai) {
1341 lp = nai.linkProperties;
1342 netId = nai.network.netId;
1343 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001344 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001345 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1346 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001347 } finally {
1348 Binder.restoreCallingIdentity(token);
1349 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001350 }
1351
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001352 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001353 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001354 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001355 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001356 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001357 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001358 if (bestRoute.getGateway().equals(addr)) {
1359 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001360 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001361 } else {
1362 // if we will connect to this through another route, add a direct route
1363 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001364 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001365 }
1366 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001367 if (DBG) log("Adding legacy route " + bestRoute +
1368 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001369 try {
1370 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1371 } catch (Exception e) {
1372 // never crash - catch them all
1373 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001374 return false;
1375 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001376 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 }
1378
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001379 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1380 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001381 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001382 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001383 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001384 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001385 }
1386
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001387 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001388 // skip update when we've already applied rules
1389 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1390 if (oldRules == uidRules) return;
1391
1392 mUidRules.put(uid, uidRules);
1393 }
1394
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001395 // TODO: notify UID when it has requested targeted updates
1396 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001397
1398 @Override
1399 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001400 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001401 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001402 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001403 }
1404
1405 synchronized (mRulesLock) {
1406 mMeteredIfaces.clear();
1407 for (String iface : meteredIfaces) {
1408 mMeteredIfaces.add(iface);
1409 }
1410 }
1411 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001412
1413 @Override
1414 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1415 // caller is NPMS, since we only register with them
1416 if (LOGD_RULES) {
1417 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1418 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001419 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001420 };
1421
Robin Lee3b3dd942015-05-12 18:14:58 +01001422 /**
1423 * Require that the caller is either in the same user or has appropriate permission to interact
1424 * across users.
1425 *
1426 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1427 */
1428 private void enforceCrossUserPermission(int userId) {
1429 if (userId == UserHandle.getCallingUserId()) {
1430 // Not a cross-user call.
1431 return;
1432 }
1433 mContext.enforceCallingOrSelfPermission(
1434 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1435 "ConnectivityService");
1436 }
1437
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001438 private void enforceInternetPermission() {
1439 mContext.enforceCallingOrSelfPermission(
1440 android.Manifest.permission.INTERNET,
1441 "ConnectivityService");
1442 }
1443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001445 mContext.enforceCallingOrSelfPermission(
1446 android.Manifest.permission.ACCESS_NETWORK_STATE,
1447 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 }
1449
1450 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001451 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 }
1453
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001454 private void enforceTetherAccessPermission() {
1455 mContext.enforceCallingOrSelfPermission(
1456 android.Manifest.permission.ACCESS_NETWORK_STATE,
1457 "ConnectivityService");
1458 }
1459
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001460 private void enforceConnectivityInternalPermission() {
1461 mContext.enforceCallingOrSelfPermission(
1462 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1463 "ConnectivityService");
1464 }
1465
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001466 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001467 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001468 }
1469
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001470 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001471 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001472 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001473 }
1474
1475 private void sendInetConditionBroadcast(NetworkInfo info) {
1476 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1477 }
1478
Wink Saville628b0852011-08-04 15:01:58 -07001479 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001480 if (mLockdownTracker != null) {
1481 info = mLockdownTracker.augmentNetworkInfo(info);
1482 }
1483
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001484 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001485 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001486 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 if (info.isFailover()) {
1488 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1489 info.setFailover(false);
1490 }
1491 if (info.getReason() != null) {
1492 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1493 }
1494 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001495 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1496 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001498 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001499 return intent;
1500 }
1501
1502 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1503 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1504 }
1505
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001506 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001507 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1508 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1509 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001510 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001511 final long ident = Binder.clearCallingIdentity();
1512 try {
1513 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1514 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1515 } finally {
1516 Binder.restoreCallingIdentity(ident);
1517 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001518 }
1519
Mike Lockwood0f79b542009-08-14 14:18:49 -04001520 private void sendStickyBroadcast(Intent intent) {
1521 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001522 if (!mSystemReady) {
1523 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001524 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001525 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001526 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001527 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001528 }
1529
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001530 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001531 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001532 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001533 final NetworkInfo ni = intent.getParcelableExtra(
1534 ConnectivityManager.EXTRA_NETWORK_INFO);
1535 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1536 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1537 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001538 } else {
1539 BroadcastOptions opts = BroadcastOptions.makeBasic();
1540 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1541 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001542 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001543 final IBatteryStats bs = BatteryStatsService.getService();
1544 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001545 bs.noteConnectivityChanged(intent.getIntExtra(
1546 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1547 ni != null ? ni.getState().toString() : "?");
1548 } catch (RemoteException e) {
1549 }
1550 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001551 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001552 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001553 } finally {
1554 Binder.restoreCallingIdentity(ident);
1555 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001556 }
1557 }
1558
1559 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001560 loadGlobalProxy();
1561
Mike Lockwood0f79b542009-08-14 14:18:49 -04001562 synchronized(this) {
1563 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001564 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001565 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001566 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001567 }
1568 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001569 // load the global proxy at startup
1570 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001571
Robin Lee244ce8e2016-01-05 18:03:46 +00001572 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1573 // for user to unlock device too.
1574 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001575
Erik Klineda4bfa82015-04-30 12:58:40 +09001576 // Configure whether mobile data is always on.
1577 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1578
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001579 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001580
1581 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 }
1583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001585 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001586 *
1587 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001588 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001589 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001590 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1591 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001592
1593 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001594 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001595
Robert Greenwalt7b816022014-04-18 15:25:25 -07001596 if (networkAgent.networkCapabilities.hasTransport(
1597 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001598 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1599 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001600 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001601 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001602 } else if (networkAgent.networkCapabilities.hasTransport(
1603 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001604 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1605 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001606 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001607 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001608 } else {
1609 // do not track any other networks
1610 timeout = 0;
1611 }
1612
Robert Greenwalt7b816022014-04-18 15:25:25 -07001613 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001614 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001615 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001616 } catch (Exception e) {
1617 // You shall not crash!
1618 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001619 }
1620 }
1621 }
1622
1623 /**
1624 * Remove data activity tracking when network disconnects.
1625 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001626 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1627 final String iface = networkAgent.linkProperties.getInterfaceName();
1628 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001629
Robert Greenwalt7b816022014-04-18 15:25:25 -07001630 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1631 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001632 try {
1633 // the call fails silently if no idletimer setup for this interface
1634 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001635 } catch (Exception e) {
1636 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001637 }
1638 }
1639 }
1640
1641 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001642 * Reads the network specific MTU size from reources.
1643 * and set it on it's iface.
1644 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001645 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1646 final String iface = newLp.getInterfaceName();
1647 final int mtu = newLp.getMtu();
1648 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1649 if (VDBG) log("identical MTU - not setting");
1650 return;
1651 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001652
Robert Greenwalt43074032014-08-15 17:53:05 -07001653 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001654 loge("Unexpected mtu value: " + mtu + ", " + iface);
1655 return;
1656 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001657
w1997615afd812014-08-05 15:18:11 -07001658 // Cannot set MTU without interface name
1659 if (TextUtils.isEmpty(iface)) {
1660 loge("Setting MTU size with null iface.");
1661 return;
1662 }
1663
Robert Greenwalt7b816022014-04-18 15:25:25 -07001664 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001665 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001666 mNetd.setMtu(iface, mtu);
1667 } catch (Exception e) {
1668 Slog.e(TAG, "exception in setMtu()" + e);
1669 }
1670 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001671
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001672 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001673 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1674
1675 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001676 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001677 protected int getDefaultTcpRwnd() {
1678 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1679 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001680
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001681 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1682 if (isDefaultNetwork(nai) == false) {
1683 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001684 }
1685
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001686 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1687 String[] values = null;
1688 if (tcpBufferSizes != null) {
1689 values = tcpBufferSizes.split(",");
1690 }
1691
1692 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001693 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001694 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1695 values = tcpBufferSizes.split(",");
1696 }
1697
1698 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1699
1700 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001701 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001702
1703 final String prefix = "/sys/kernel/ipv4/tcp_";
1704 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1705 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1706 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1707 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1708 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1709 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1710 mCurrentTcpBufferSizes = tcpBufferSizes;
1711 } catch (IOException e) {
1712 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001713 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001714
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001715 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001716 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001717 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1718 if (rwndValue != 0) {
1719 SystemProperties.set(sysctlKey, rwndValue.toString());
1720 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001721 }
1722
Mattias Falk8b47b362011-08-23 14:15:13 +02001723 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001724 /*
1725 * Tell the VMs to toss their DNS caches
1726 */
1727 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1728 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001729 /*
1730 * Connectivity events can happen before boot has completed ...
1731 */
1732 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001733 final long ident = Binder.clearCallingIdentity();
1734 try {
1735 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1736 } finally {
1737 Binder.restoreCallingIdentity(ident);
1738 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001739 }
1740
Robert Greenwalt562cc542014-05-15 18:07:26 -07001741 @Override
1742 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001743 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1744 NETWORK_RESTORE_DELAY_PROP_NAME);
1745 if(restoreDefaultNetworkDelayStr != null &&
1746 restoreDefaultNetworkDelayStr.length() != 0) {
1747 try {
1748 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1749 } catch (NumberFormatException e) {
1750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001752 // if the system property isn't set, use the value for the apn type
1753 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1754
1755 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1756 (mNetConfigs[networkType] != null)) {
1757 ret = mNetConfigs[networkType].restoreTime;
1758 }
1759 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 }
1761
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001762 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001763 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001764 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001765 }
1766 return false;
1767 }
1768
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001769 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1770 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1771 final long DIAG_TIME_MS = 5000;
1772 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1773 // Start gathering diagnostic information.
1774 netDiags.add(new NetworkDiagnostics(
1775 nai.network,
1776 new LinkProperties(nai.linkProperties), // Must be a copy.
1777 DIAG_TIME_MS));
1778 }
1779
1780 for (NetworkDiagnostics netDiag : netDiags) {
1781 pw.println();
1782 netDiag.waitForMeasurements();
1783 netDiag.dump(pw);
1784 }
1785 }
1786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001788 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1789 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001790 if (mContext.checkCallingOrSelfPermission(
1791 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001793 pw.println("Permission Denial: can't dump ConnectivityService " +
1794 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1795 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 return;
1797 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001798
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001799 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001800 dumpNetworkDiagnostics(pw);
1801 return;
1802 }
Erik Kline379747a2015-06-05 17:47:34 +09001803
Lorenzo Colittie3805462015-06-03 11:18:24 +09001804 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001805 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001806 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001807 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001808 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001809 pw.println();
1810
Paul Jensen85cf78e2015-06-25 13:25:07 -04001811 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001812 pw.print("Active default network: ");
1813 if (defaultNai == null) {
1814 pw.println("none");
1815 } else {
1816 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001818 pw.println();
1819
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001820 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001821 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001822 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1823 pw.println(nai.toString());
1824 pw.increaseIndent();
1825 pw.println("Requests:");
1826 pw.increaseIndent();
1827 for (int i = 0; i < nai.networkRequests.size(); i++) {
1828 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001829 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001830 pw.decreaseIndent();
1831 pw.println("Lingered:");
1832 pw.increaseIndent();
1833 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1834 pw.decreaseIndent();
1835 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001836 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001837 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001838 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001839
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001840 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001841 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001842 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1843 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001844 }
1845 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001846 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001847
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001848 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001849
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001850 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001851 pw.print("mNetTransitionWakeLock: currently " +
1852 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1853 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1854 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1855 } else {
1856 pw.println(", last requested never");
1857 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001858 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001859
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001860 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001861 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001862
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001863 pw.println();
1864 mKeepaliveTracker.dump(pw);
1865
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001866 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001867
Lorenzo Colittie3805462015-06-03 11:18:24 +09001868 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001869 pw.println();
1870 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001871 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001872 for(int i = 0; i < mInetLog.size(); i++) {
1873 pw.println(mInetLog.get(i));
1874 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001875 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001876 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001877
1878 if (argsContain(args, "--short") == false) {
1879 pw.println();
1880 synchronized (mValidationLogs) {
1881 pw.println("mValidationLogs (most recent first):");
1882 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1883 pw.println(p.first);
1884 pw.increaseIndent();
1885 p.second.dump(fd, pw, args);
1886 pw.decreaseIndent();
1887 }
1888 }
Erik Kline7523eb32015-07-09 18:24:03 +09001889
1890 pw.println();
1891 pw.println("mNetworkRequestInfoLogs (most recent first):");
1892 pw.increaseIndent();
1893 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1894 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 }
1897
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001898 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001899 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001900 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001901 if (officialNai != null && officialNai.equals(nai)) return true;
1902 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001903 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001904 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001905 " - " + nai);
1906 }
1907 return false;
1908 }
1909
Paul Jensenc8b9a742014-09-30 15:37:41 -04001910 private boolean isRequest(NetworkRequest request) {
Erik Kline371c7b72016-03-22 17:04:20 +09001911 return mNetworkRequests.get(request).isRequest();
Paul Jensenc8b9a742014-09-30 15:37:41 -04001912 }
1913
Robert Greenwalt42acef32009-08-12 16:08:25 -07001914 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001915 private class NetworkStateTrackerHandler extends Handler {
1916 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001917 super(looper);
1918 }
1919
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001920 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001922 default:
1923 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07001924 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001925 handleAsyncChannelHalfConnect(msg);
1926 break;
1927 }
1928 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1929 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1930 if (nai != null) nai.asyncChannel.disconnect();
1931 break;
1932 }
1933 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1934 handleAsyncChannelDisconnected(msg);
1935 break;
1936 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001937 }
1938 return true;
1939 }
1940
1941 private void maybeHandleNetworkAgentMessage(Message msg) {
1942 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1943 if (nai == null) {
1944 if (VDBG) {
1945 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
1946 log(String.format("%s from unknown NetworkAgent", what));
1947 }
1948 return;
1949 }
1950
1951 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001952 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001953 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
1954 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1955 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
1956 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07001957 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001958 if (nai.created && !nai.networkCapabilities.equalImmutableCapabilities(
1959 networkCapabilities)) {
1960 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
1961 + nai.networkCapabilities + " -> " + networkCapabilities);
1962 }
1963 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001964 break;
1965 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001966 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001967 if (VDBG) {
1968 log("Update of LinkProperties for " + nai.name() +
1969 "; created=" + nai.created);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001970 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001971 LinkProperties oldLp = nai.linkProperties;
1972 synchronized (nai) {
1973 nai.linkProperties = (LinkProperties)msg.obj;
1974 }
1975 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001976 break;
1977 }
1978 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001979 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001980 updateNetworkInfo(nai, info);
1981 break;
1982 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001983 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07001984 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001985 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001986 break;
1987 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001988 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001989 try {
1990 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001991 } catch (Exception e) {
1992 // Never crash!
1993 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001994 }
1995 break;
1996 }
1997 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001998 try {
1999 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002000 } catch (Exception e) {
2001 // Never crash!
2002 loge("Exception in removeVpnUidRanges: " + e);
2003 }
2004 break;
2005 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002006 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002007 if (nai.created && !nai.networkMisc.explicitlySelected) {
2008 loge("ERROR: created network explicitly selected.");
2009 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002010 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002011 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002012 break;
2013 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002014 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002015 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2016 break;
2017 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002018 }
2019 }
2020
2021 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2022 switch (msg.what) {
2023 default:
2024 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002025 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002026 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002027 if (isLiveNetworkAgent(nai, msg.what)) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002028 final boolean valid =
2029 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002030 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
2031 if (valid != nai.lastValidated) {
2032 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002033 nai.lastValidated = valid;
2034 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002035 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002036 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2037 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002038 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002039 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002040 // Let the NetworkAgent know the state of its network
2041 nai.asyncChannel.sendMessage(
2042 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2043 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2044 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002045 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002046 break;
2047 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002048 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002049 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002050 if (isLiveNetworkAgent(nai, msg.what)) {
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002051 handleLingerComplete(nai);
2052 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002053 break;
2054 }
Paul Jensen869868be2014-05-15 10:33:05 -04002055 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002056 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002057 final boolean visible = (msg.arg1 != 0);
2058 final NetworkAgentInfo nai;
2059 synchronized (mNetworkForNetId) {
2060 nai = mNetworkForNetId.get(netId);
2061 }
2062 // If captive portal status has changed, update capabilities.
2063 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2064 nai.lastCaptivePortalDetected = visible;
2065 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002066 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002067 }
2068 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002069 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002070 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002071 if (nai == null) {
2072 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2073 break;
2074 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002075 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002076 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2077 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002078 }
Paul Jensen869868be2014-05-15 10:33:05 -04002079 break;
2080 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002081 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002082 return true;
2083 }
2084
2085 @Override
2086 public void handleMessage(Message msg) {
2087 if (!maybeHandleAsyncChannelMessage(msg) && !maybeHandleNetworkMonitorMessage(msg)) {
2088 maybeHandleNetworkAgentMessage(msg);
2089 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002090 }
2091 }
2092
Paul Jensen85cf78e2015-06-25 13:25:07 -04002093 private void linger(NetworkAgentInfo nai) {
2094 nai.lingering = true;
2095 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2096 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2097 }
2098
Paul Jensen0cc17322014-11-25 15:26:53 -05002099 // Cancel any lingering so the linger timeout doesn't teardown a network.
2100 // This should be called when a network begins satisfying a NetworkRequest.
2101 // Note: depending on what state the NetworkMonitor is in (e.g.,
2102 // if it's awaiting captive portal login, or if validation failed), this
2103 // may trigger a re-evaluation of the network.
2104 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002105 nai.networkLingered.clear();
2106 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002107 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002108 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002109 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2110 }
2111
Robert Greenwalt7b816022014-04-18 15:25:25 -07002112 private void handleAsyncChannelHalfConnect(Message msg) {
2113 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002114 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002115 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2116 if (VDBG) log("NetworkFactory connected");
2117 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002118 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Erik Kline371c7b72016-03-22 17:04:20 +09002119 if (!nri.isRequest()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002120 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002121 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002122 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002123 }
2124 } else {
2125 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002126 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002127 }
2128 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2129 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2130 if (VDBG) log("NetworkAgent connected");
2131 // A network agent has requested a connection. Establish the connection.
2132 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2133 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2134 } else {
2135 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002136 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002137 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002138 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002139 synchronized (mNetworkForNetId) {
2140 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002141 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002142 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002143 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002144 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002145 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002146 }
2147 }
2148 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002149
Robert Greenwalt7b816022014-04-18 15:25:25 -07002150 private void handleAsyncChannelDisconnected(Message msg) {
2151 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2152 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002153 if (DBG) {
2154 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2155 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002156 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002157 // TODO - if we move the logic to the network agent (have them disconnect
2158 // because they lost all their requests or because their score isn't good)
2159 // then they would disconnect organically, report their new state and then
2160 // disconnect the channel.
2161 if (nai.networkInfo.isConnected()) {
2162 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2163 null, null);
2164 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002165 final boolean wasDefault = isDefaultNetwork(nai);
2166 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002167 mDefaultInetConditionPublished = 0;
2168 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002169 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002170 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2171 // by other networks that are already connected. Perhaps that can be done by
2172 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2173 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002174 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002175 mKeepaliveTracker.handleStopAllKeepalives(nai,
2176 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002177 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002178 mNetworkAgentInfos.remove(msg.replyTo);
2179 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002180 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002181 // Remove the NetworkAgent, but don't mark the netId as
2182 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002183 mNetworkForNetId.remove(nai.network.netId);
2184 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002185 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002186 for (int i = 0; i < nai.networkRequests.size(); i++) {
2187 NetworkRequest request = nai.networkRequests.valueAt(i);
2188 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2189 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2190 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002191 sendUpdatedScoreToFactories(request, 0);
2192 }
2193 }
2194 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2195 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002196 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002197 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002198 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002199 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002200 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002201 if (nai.created) {
2202 // Tell netd to clean up the configuration for this network
2203 // (routing rules, DNS, etc).
2204 // This may be slow as it requires a lot of netd shelling out to ip and
2205 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2206 // after we've rematched networks with requests which should make a potential
2207 // fallback network the default or requested a new network from the
2208 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2209 // long time.
2210 try {
2211 mNetd.removeNetwork(nai.network.netId);
2212 } catch (Exception e) {
2213 loge("Exception removing network: " + e);
2214 }
2215 }
2216 synchronized (mNetworkForNetId) {
2217 mNetIdInUse.delete(nai.network.netId);
2218 }
2219 } else {
2220 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2221 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002222 }
2223 }
2224
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002225 // If this method proves to be too slow then we can maintain a separate
2226 // pendingIntent => NetworkRequestInfo map.
2227 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2228 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2229 Intent intent = pendingIntent.getIntent();
2230 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2231 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2232 if (existingPendingIntent != null &&
2233 existingPendingIntent.getIntent().filterEquals(intent)) {
2234 return entry.getValue();
2235 }
2236 }
2237 return null;
2238 }
2239
2240 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2241 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2242
2243 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2244 if (existingRequest != null) { // remove the existing request.
2245 if (DBG) log("Replacing " + existingRequest.request + " with "
2246 + nri.request + " because their intents matched.");
2247 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2248 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002249 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002250 }
2251
Erik Klineda4bfa82015-04-30 12:58:40 +09002252 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002253 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002254 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002255 if (!nri.isRequest()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002256 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002257 if (nri.request.networkCapabilities.hasSignalStrength() &&
2258 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2259 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002260 }
2261 }
2262 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002263 rematchAllNetworksAndRequests(null, 0);
Erik Kline371c7b72016-03-22 17:04:20 +09002264 if (nri.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002265 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002266 }
2267 }
2268
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002269 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2270 int callingUid) {
2271 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2272 if (nri != null) {
2273 handleReleaseNetworkRequest(nri.request, callingUid);
2274 }
2275 }
2276
Paul Jensen99364842014-12-09 11:43:45 -05002277 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002278 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2279 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002280 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002281 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002282 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2283 // If this Network is already the highest scoring Network for a request, or if
2284 // there is hope for it to become one if it validated, then it is needed.
Erik Kline371c7b72016-03-22 17:04:20 +09002285 if (nri.isRequest() && nai.satisfies(nri.request) &&
Paul Jensene0988542015-06-25 15:30:08 -04002286 (nai.networkRequests.get(nri.request.requestId) != null ||
2287 // Note that this catches two important cases:
2288 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2289 // is currently satisfying the request. This is desirable when
2290 // cellular ends up validating but WiFi does not.
2291 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002292 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002293 // WiFi ends up validating and out scoring cellular.
2294 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2295 nai.getCurrentScoreAsValidated())) {
2296 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002297 }
2298 }
Paul Jensene0988542015-06-25 15:30:08 -04002299 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002300 }
2301
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002302 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2303 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002304 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002305 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002306 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2307 return;
2308 }
2309 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002310 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002311 mNetworkRequests.remove(request);
Erik Kline7523eb32015-07-09 18:24:03 +09002312 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002313 if (nri.isRequest()) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002314 // Find all networks that are satisfying this request and remove the request
2315 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002316 // TODO - it's my understanding that for a request there is only a single
2317 // network satisfying it, so this loop is wasteful
2318 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002319 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2320 if (nai.networkRequests.get(nri.request.requestId) != null) {
2321 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002322 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002323 log(" Removing from current network " + nai.name() +
2324 ", leaving " + nai.networkRequests.size() +
2325 " requests.");
2326 }
Paul Jensen99364842014-12-09 11:43:45 -05002327 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002328 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002329 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002330 } else {
2331 // suspect there should only be one pass through here
2332 // but if any were kept do the check below
2333 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002334 }
2335 }
2336 }
2337
Robert Greenwalt51481852015-01-08 14:43:31 -08002338 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2339 if (nai != null) {
2340 mNetworkForRequestId.remove(nri.request.requestId);
2341 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002342 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002343 // that a network connected to serve it, even though the network was already
2344 // connected. Now that this request has gone away, we might have to pretend
2345 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002346 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002347 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2348 boolean doRemove = true;
2349 if (wasKept) {
2350 // check if any of the remaining requests for this network are for the
2351 // same legacy type - if so, don't remove the nai
2352 for (int i = 0; i < nai.networkRequests.size(); i++) {
2353 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2354 if (otherRequest.legacyType == nri.request.legacyType &&
2355 isRequest(otherRequest)) {
2356 if (DBG) log(" still have other legacy request - leaving");
2357 doRemove = false;
2358 }
2359 }
2360 }
2361
2362 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002363 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002364 }
2365 }
2366
Robert Greenwalta67be032014-05-16 15:49:14 -07002367 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002368 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2369 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002370 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002371 } else {
2372 // listens don't have a singular affectedNetwork. Check all networks to see
2373 // if this listen request applies and remove it.
2374 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2375 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002376 if (nri.request.networkCapabilities.hasSignalStrength() &&
2377 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2378 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002379 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002380 }
2381 }
2382 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2383 }
2384 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002385
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002386 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2387 enforceConnectivityInternalPermission();
2388 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2389 accept ? 1 : 0, always ? 1: 0, network));
2390 }
2391
2392 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2393 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2394 " accept=" + accept + " always=" + always);
2395
2396 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2397 if (nai == null) {
2398 // Nothing to do.
2399 return;
2400 }
2401
2402 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002403 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002404 return;
2405 }
2406
2407 if (!nai.networkMisc.explicitlySelected) {
2408 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2409 }
2410
2411 if (accept != nai.networkMisc.acceptUnvalidated) {
2412 int oldScore = nai.getCurrentScore();
2413 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002414 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002415 sendUpdatedScoreToFactories(nai);
2416 }
2417
2418 if (always) {
2419 nai.asyncChannel.sendMessage(
2420 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2421 }
2422
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002423 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002424 // Tell the NetworkAgent to not automatically reconnect to the network.
2425 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2426 // Teardown the nework.
2427 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002428 }
2429
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002430 }
2431
2432 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002433 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002434 mHandler.sendMessageDelayed(
2435 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2436 PROMPT_UNVALIDATED_DELAY_MS);
2437 }
2438
2439 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002440 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002441 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2442
2443 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2444 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002445 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002446 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002447 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2448 return;
2449 }
2450
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002451 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002452 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002453 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2454 intent.setClassName("com.android.settings",
2455 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002456
2457 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2458 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2459 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002460 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002461 }
2462
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002463 private class InternalHandler extends Handler {
2464 public InternalHandler(Looper looper) {
2465 super(looper);
2466 }
2467
2468 @Override
2469 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002470 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002471 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002472 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002473 String causedBy = null;
2474 synchronized (ConnectivityService.this) {
2475 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2476 mNetTransitionWakeLock.isHeld()) {
2477 mNetTransitionWakeLock.release();
2478 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002479 } else {
2480 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002481 }
2482 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002483 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2484 log("Failed to find a new network - expiring NetTransition Wakelock");
2485 } else {
2486 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2487 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002488 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002489 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002490 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002491 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002492 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002493 break;
2494 }
Jason Monkdecd2952013-10-10 14:02:51 -04002495 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002496 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002497 break;
2498 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002499 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002500 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2501 break;
2502 }
2503 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2504 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002505 break;
2506 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002507 case EVENT_REGISTER_NETWORK_AGENT: {
2508 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2509 break;
2510 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002511 case EVENT_REGISTER_NETWORK_REQUEST:
2512 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002513 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002514 break;
2515 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002516 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2517 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002518 handleRegisterNetworkRequestWithIntent(msg);
2519 break;
2520 }
2521 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2522 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2523 break;
2524 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002525 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002526 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002527 break;
2528 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002529 case EVENT_SET_ACCEPT_UNVALIDATED: {
2530 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2531 break;
2532 }
2533 case EVENT_PROMPT_UNVALIDATED: {
2534 handlePromptUnvalidated((Network) msg.obj);
2535 break;
2536 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002537 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2538 handleMobileDataAlwaysOn();
2539 break;
2540 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002541 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2542 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2543 mKeepaliveTracker.handleStartKeepalive(msg);
2544 break;
2545 }
2546 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2547 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2548 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2549 int slot = msg.arg1;
2550 int reason = msg.arg2;
2551 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2552 break;
2553 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002554 case EVENT_SYSTEM_READY: {
2555 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2556 nai.networkMonitor.systemReady = true;
2557 }
2558 break;
2559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 }
2561 }
2562 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002563
2564 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002565 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002566 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002567 if (isTetheringSupported()) {
2568 return mTethering.tether(iface);
2569 } else {
2570 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2571 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002572 }
2573
2574 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002575 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002576 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002577
2578 if (isTetheringSupported()) {
2579 return mTethering.untether(iface);
2580 } else {
2581 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2582 }
2583 }
2584
2585 // javadoc from interface
2586 public int getLastTetherError(String iface) {
2587 enforceTetherAccessPermission();
2588
2589 if (isTetheringSupported()) {
2590 return mTethering.getLastTetherError(iface);
2591 } else {
2592 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2593 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002594 }
2595
2596 // TODO - proper iface API for selection by property, inspection, etc
2597 public String[] getTetherableUsbRegexs() {
2598 enforceTetherAccessPermission();
2599 if (isTetheringSupported()) {
2600 return mTethering.getTetherableUsbRegexs();
2601 } else {
2602 return new String[0];
2603 }
2604 }
2605
2606 public String[] getTetherableWifiRegexs() {
2607 enforceTetherAccessPermission();
2608 if (isTetheringSupported()) {
2609 return mTethering.getTetherableWifiRegexs();
2610 } else {
2611 return new String[0];
2612 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002613 }
2614
Danica Chang6fdd0c62010-08-11 14:54:43 -07002615 public String[] getTetherableBluetoothRegexs() {
2616 enforceTetherAccessPermission();
2617 if (isTetheringSupported()) {
2618 return mTethering.getTetherableBluetoothRegexs();
2619 } else {
2620 return new String[0];
2621 }
2622 }
2623
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002624 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002625 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002626 if (isTetheringSupported()) {
2627 return mTethering.setUsbTethering(enable);
2628 } else {
2629 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2630 }
2631 }
2632
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002633 // TODO - move iface listing, queries, etc to new module
2634 // javadoc from interface
2635 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002636 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002637 return mTethering.getTetherableIfaces();
2638 }
2639
2640 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002641 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002642 return mTethering.getTetheredIfaces();
2643 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002644
Robert Greenwalt5a735062010-03-02 17:25:02 -08002645 public String[] getTetheringErroredIfaces() {
2646 enforceTetherAccessPermission();
2647 return mTethering.getErroredIfaces();
2648 }
2649
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002650 public String[] getTetheredDhcpRanges() {
2651 enforceConnectivityInternalPermission();
2652 return mTethering.getTetheredDhcpRanges();
2653 }
2654
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002655 // if ro.tether.denied = true we default to no tethering
2656 // gservices could set the secure setting to 1 though to enable it on a build where it
2657 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002658 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002659 public boolean isTetheringSupported() {
2660 enforceTetherAccessPermission();
2661 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002662 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002663 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2664 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002665 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2666 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002667 mTethering.getTetherableWifiRegexs().length != 0 ||
2668 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2669 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002670 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002671
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002672 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002673 public void startTethering(int type, ResultReceiver receiver,
2674 boolean showProvisioningUi) {
2675 ConnectivityManager.enforceTetherChangePermission(mContext);
2676 if (!isTetheringSupported()) {
2677 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2678 return;
2679 }
2680 mTethering.startTethering(type, receiver, showProvisioningUi);
2681 }
2682
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002683 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002684 public void stopTethering(int type) {
2685 ConnectivityManager.enforceTetherChangePermission(mContext);
2686 mTethering.stopTethering(type);
2687 }
2688
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002689 // Called when we lose the default network and have no replacement yet.
2690 // This will automatically be cleared after X seconds or a new default network
2691 // becomes CONNECTED, whichever happens first. The timer is started by the
2692 // first caller and not restarted by subsequent callers.
2693 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002694 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002695 synchronized (this) {
2696 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002697 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002698 mNetTransitionWakeLock.acquire();
2699 mNetTransitionWakeLockCausedBy = forWhom;
2700 }
2701 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002702 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002703 mNetTransitionWakeLockTimeout);
2704 return;
2705 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002706
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002707 // 100 percent is full good, 0 is full bad.
2708 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002709 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002710 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002711 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002712 }
2713
Paul Jensenbfd17b72015-04-07 12:43:13 -04002714 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002715 enforceAccessPermission();
2716 enforceInternetPermission();
2717
Paul Jensenbfd17b72015-04-07 12:43:13 -04002718 NetworkAgentInfo nai;
2719 if (network == null) {
2720 nai = getDefaultNetwork();
2721 } else {
2722 nai = getNetworkAgentInfoForNetwork(network);
2723 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002724 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2725 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2726 return;
2727 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002728 // Revalidate if the app report does not match our current validated state.
2729 if (hasConnectivity == nai.lastValidated) return;
2730 final int uid = Binder.getCallingUid();
2731 if (DBG) {
2732 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2733 ") by " + uid);
2734 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002735 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002736 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2737 // which isn't meant to work on uncreated networks.
2738 if (!nai.created) return;
2739
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002740 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002741
2742 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2743 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002744 }
2745
Paul Jensencee9b512015-05-06 07:32:40 -04002746 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002747 // this information is already available as a world read/writable jvm property
2748 // so this API change wouldn't have a benifit. It also breaks the passing
2749 // of proxy info to all the JVMs.
2750 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002751 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002752 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002753 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2754 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002755 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002756 }
2757
Paul Jensencee9b512015-05-06 07:32:40 -04002758 public ProxyInfo getProxyForNetwork(Network network) {
2759 if (network == null) return getDefaultProxy();
2760 final ProxyInfo globalProxy = getGlobalProxy();
2761 if (globalProxy != null) return globalProxy;
2762 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2763 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2764 // caller may not have.
2765 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2766 if (nai == null) return null;
2767 synchronized (nai) {
2768 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2769 if (proxyInfo == null) return null;
2770 return new ProxyInfo(proxyInfo);
2771 }
2772 }
2773
Paul Jensene0bef712014-12-10 15:12:18 -05002774 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2775 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2776 // proxy is null then there is no proxy in place).
2777 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2778 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2779 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2780 proxy = null;
2781 }
2782 return proxy;
2783 }
2784
2785 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2786 // better for determining if a new proxy broadcast is necessary:
2787 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2788 // avoid unnecessary broadcasts.
2789 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2790 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2791 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2792 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2793 // all set.
2794 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2795 a = canonicalizeProxyInfo(a);
2796 b = canonicalizeProxyInfo(b);
2797 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2798 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2799 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2800 }
2801
Jason Monk207900c2014-04-25 15:00:09 -04002802 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002803 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002804
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002805 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002806 if (proxyProperties == mGlobalProxy) return;
2807 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2808 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2809
2810 String host = "";
2811 int port = 0;
2812 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002813 String pacFileUrl = "";
2814 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002815 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002816 if (!proxyProperties.isValid()) {
2817 if (DBG)
2818 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2819 return;
2820 }
Jason Monk207900c2014-04-25 15:00:09 -04002821 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002822 host = mGlobalProxy.getHost();
2823 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002824 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002825 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002826 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002827 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002828 } else {
2829 mGlobalProxy = null;
2830 }
2831 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002832 final long token = Binder.clearCallingIdentity();
2833 try {
2834 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2835 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2836 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2837 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002838 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002839 } finally {
2840 Binder.restoreCallingIdentity(token);
2841 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002842
Jason Monkcf0f97a2014-10-02 15:39:38 -04002843 if (mGlobalProxy == null) {
2844 proxyProperties = mDefaultProxy;
2845 }
2846 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002847 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002848 }
2849
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002850 private void loadGlobalProxy() {
2851 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002852 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2853 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2854 String exclList = Settings.Global.getString(res,
2855 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002856 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2857 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002858 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002859 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002860 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002861 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002862 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002863 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002864 if (!proxyProperties.isValid()) {
2865 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2866 return;
2867 }
2868
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002869 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002870 mGlobalProxy = proxyProperties;
2871 }
2872 }
2873 }
2874
Jason Monk207900c2014-04-25 15:00:09 -04002875 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002876 // this information is already available as a world read/writable jvm property
2877 // so this API change wouldn't have a benifit. It also breaks the passing
2878 // of proxy info to all the JVMs.
2879 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002880 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002881 return mGlobalProxy;
2882 }
2883 }
2884
Jason Monk207900c2014-04-25 15:00:09 -04002885 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002886 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002887 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002888 proxy = null;
2889 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002890 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002891 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002892 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002893 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002894 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2895 return;
2896 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002897
2898 // This call could be coming from the PacManager, containing the port of the local
2899 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2900 // global (to get the correct local port), and send a broadcast.
2901 // TODO: Switch PacManager to have its own message to send back rather than
2902 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002903 if ((mGlobalProxy != null) && (proxy != null)
2904 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002905 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2906 mGlobalProxy = proxy;
2907 sendProxyBroadcast(mGlobalProxy);
2908 return;
2909 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002910 mDefaultProxy = proxy;
2911
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002912 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002913 if (!mDefaultProxyDisabled) {
2914 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002915 }
2916 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002917 }
2918
Paul Jensene0bef712014-12-10 15:12:18 -05002919 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2920 // This method gets called when any network changes proxy, but the broadcast only ever contains
2921 // the default proxy (even if it hasn't changed).
2922 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2923 // world where an app might be bound to a non-default network.
2924 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2925 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2926 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2927
2928 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2929 sendProxyBroadcast(getDefaultProxy());
2930 }
2931 }
2932
Robert Greenwalt434203a2010-10-11 16:00:27 -07002933 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002934 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2935 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002936 if (!TextUtils.isEmpty(proxy)) {
2937 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002938 if (data.length == 0) {
2939 return;
2940 }
2941
Robert Greenwalt434203a2010-10-11 16:00:27 -07002942 String proxyHost = data[0];
2943 int proxyPort = 8080;
2944 if (data.length > 1) {
2945 try {
2946 proxyPort = Integer.parseInt(data[1]);
2947 } catch (NumberFormatException e) {
2948 return;
2949 }
2950 }
Jason Monk207900c2014-04-25 15:00:09 -04002951 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002952 setGlobalProxy(p);
2953 }
2954 }
2955
Jason Monk207900c2014-04-25 15:00:09 -04002956 private void sendProxyBroadcast(ProxyInfo proxy) {
2957 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002958 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002959 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002960 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002961 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2962 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002963 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002964 final long ident = Binder.clearCallingIdentity();
2965 try {
2966 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2967 } finally {
2968 Binder.restoreCallingIdentity(ident);
2969 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002970 }
2971
2972 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002973 final private HashMap<Uri, Integer> mUriEventMap;
2974 final private Context mContext;
2975 final private Handler mHandler;
2976
2977 SettingsObserver(Context context, Handler handler) {
2978 super(null);
2979 mUriEventMap = new HashMap<Uri, Integer>();
2980 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002981 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002982 }
2983
Erik Klineda4bfa82015-04-30 12:58:40 +09002984 void observe(Uri uri, int what) {
2985 mUriEventMap.put(uri, what);
2986 final ContentResolver resolver = mContext.getContentResolver();
2987 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002988 }
2989
2990 @Override
2991 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002992 Slog.wtf(TAG, "Should never be reached.");
2993 }
2994
2995 @Override
2996 public void onChange(boolean selfChange, Uri uri) {
2997 final Integer what = mUriEventMap.get(uri);
2998 if (what != null) {
2999 mHandler.obtainMessage(what.intValue()).sendToTarget();
3000 } else {
3001 loge("No matching event to send for URI=" + uri);
3002 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003003 }
3004 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003005
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003006 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003007 Slog.d(TAG, s);
3008 }
3009
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003010 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003011 Slog.e(TAG, s);
3012 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003013
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003014 private static <T> T checkNotNull(T value, String message) {
3015 if (value == null) {
3016 throw new NullPointerException(message);
3017 }
3018 return value;
3019 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003020
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003021 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003022 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003023 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3024 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3025 *
3026 * @param oldPackage Package name of the application which currently controls VPN, which will
3027 * be replaced. If there is no such application, this should should either be
3028 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3029 * @param newPackage Package name of the application which should gain control of VPN, or
3030 * {@code null} to disable.
3031 * @param userId User for whom to prepare the new VPN.
3032 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003033 * @hide
3034 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003035 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003036 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3037 int userId) {
3038 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003039 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003040
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003041 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003042 Vpn vpn = mVpns.get(userId);
3043 if (vpn != null) {
3044 return vpn.prepare(oldPackage, newPackage);
3045 } else {
3046 return false;
3047 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003048 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003049 }
3050
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003051 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003052 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3053 * This method is used by system-privileged apps.
3054 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3055 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3056 *
3057 * @param packageName The package for which authorization state should change.
3058 * @param userId User for whom {@code packageName} is installed.
3059 * @param authorized {@code true} if this app should be able to start a VPN connection without
3060 * explicit user approval, {@code false} if not.
3061 *
Jeff Davidson05542602014-08-11 14:07:27 -07003062 * @hide
3063 */
3064 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003065 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3066 enforceCrossUserPermission(userId);
3067
Jeff Davidson05542602014-08-11 14:07:27 -07003068 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003069 Vpn vpn = mVpns.get(userId);
3070 if (vpn != null) {
3071 vpn.setPackageAuthorization(packageName, authorized);
3072 }
Jeff Davidson05542602014-08-11 14:07:27 -07003073 }
3074 }
3075
3076 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003077 * Configure a TUN interface and return its file descriptor. Parameters
3078 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003079 * and not available in ConnectivityManager. Permissions are checked in
3080 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003081 * @hide
3082 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003083 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003084 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003085 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003086 int user = UserHandle.getUserId(Binder.getCallingUid());
3087 synchronized(mVpns) {
3088 return mVpns.get(user).establish(config);
3089 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003090 }
3091
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003092 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003093 * Start legacy VPN, controlling native daemons as needed. Creates a
3094 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003095 */
3096 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003097 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003098 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003099 final LinkProperties egress = getActiveLinkProperties();
3100 if (egress == null) {
3101 throw new IllegalStateException("Missing active network connection");
3102 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003103 int user = UserHandle.getUserId(Binder.getCallingUid());
3104 synchronized(mVpns) {
3105 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3106 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003107 }
3108
3109 /**
3110 * Return the information of the ongoing legacy VPN. This method is used
3111 * by VpnSettings and not available in ConnectivityManager. Permissions
3112 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003113 */
3114 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003115 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3116 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003117 if (mLockdownEnabled) {
3118 return null;
3119 }
3120
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003121 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003122 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003123 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003124 }
3125
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003126 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003127 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3128 * and not available in ConnectivityManager.
3129 */
3130 @Override
3131 public VpnInfo[] getAllVpnInfo() {
3132 enforceConnectivityInternalPermission();
3133 if (mLockdownEnabled) {
3134 return new VpnInfo[0];
3135 }
3136
3137 synchronized(mVpns) {
3138 List<VpnInfo> infoList = new ArrayList<>();
3139 for (int i = 0; i < mVpns.size(); i++) {
3140 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3141 if (info != null) {
3142 infoList.add(info);
3143 }
3144 }
3145 return infoList.toArray(new VpnInfo[infoList.size()]);
3146 }
3147 }
3148
3149 /**
3150 * @return VPN information for accounting, or null if we can't retrieve all required
3151 * information, e.g primary underlying iface.
3152 */
3153 @Nullable
3154 private VpnInfo createVpnInfo(Vpn vpn) {
3155 VpnInfo info = vpn.getVpnInfo();
3156 if (info == null) {
3157 return null;
3158 }
3159 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3160 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3161 // the underlyingNetworks list.
3162 if (underlyingNetworks == null) {
3163 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3164 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3165 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3166 }
3167 } else if (underlyingNetworks.length > 0) {
3168 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3169 if (linkProperties != null) {
3170 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3171 }
3172 }
3173 return info.primaryUnderlyingIface == null ? null : info;
3174 }
3175
3176 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003177 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3178 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003179 * Permissions are checked in Vpn class.
3180 * @hide
3181 */
3182 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003183 public VpnConfig getVpnConfig(int userId) {
3184 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003185 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003186 Vpn vpn = mVpns.get(userId);
3187 if (vpn != null) {
3188 return vpn.getVpnConfig();
3189 } else {
3190 return null;
3191 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003192 }
3193 }
3194
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003195 @Override
3196 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003197 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3198 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3199 return false;
3200 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003201
3202 // Tear down existing lockdown if profile was removed
3203 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3204 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003205 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3206 final VpnProfile profile = VpnProfile.decode(
3207 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003208 if (profile == null) {
3209 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3210 setLockdownTracker(null);
3211 return true;
3212 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003213 int user = UserHandle.getUserId(Binder.getCallingUid());
3214 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003215 Vpn vpn = mVpns.get(user);
3216 if (vpn == null) {
3217 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3218 return false;
3219 }
3220 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003221 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003222 } else {
3223 setLockdownTracker(null);
3224 }
3225
3226 return true;
3227 }
3228
3229 /**
3230 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3231 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3232 */
3233 private void setLockdownTracker(LockdownVpnTracker tracker) {
3234 // Shutdown any existing tracker
3235 final LockdownVpnTracker existing = mLockdownTracker;
3236 mLockdownTracker = null;
3237 if (existing != null) {
3238 existing.shutdown();
3239 }
3240
3241 try {
3242 if (tracker != null) {
3243 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003244 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003245 mLockdownTracker = tracker;
3246 mLockdownTracker.init();
3247 } else {
3248 mNetd.setFirewallEnabled(false);
3249 }
3250 } catch (RemoteException e) {
3251 // ignored; NMS lives inside system_server
3252 }
3253 }
3254
3255 private void throwIfLockdownEnabled() {
3256 if (mLockdownEnabled) {
3257 throw new IllegalStateException("Unavailable in lockdown mode");
3258 }
3259 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003260
Robin Lee244ce8e2016-01-05 18:03:46 +00003261 /**
3262 * Sets up or tears down the always-on VPN for user {@param user} as appropriate.
3263 *
3264 * @return {@code false} in case of errors; {@code true} otherwise.
3265 */
3266 private boolean updateAlwaysOnVpn(int user) {
3267 final String lockdownPackage = getAlwaysOnVpnPackage(user);
3268 if (lockdownPackage == null) {
3269 return true;
3270 }
3271
3272 // Create an intent to start the VPN service declared in the app's manifest.
3273 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
3274 serviceIntent.setPackage(lockdownPackage);
3275
3276 try {
3277 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(user)) != null;
3278 } catch (RuntimeException e) {
3279 return false;
3280 }
3281 }
3282
3283 @Override
3284 public boolean setAlwaysOnVpnPackage(int userId, String packageName) {
3285 enforceConnectivityInternalPermission();
3286 enforceCrossUserPermission(userId);
3287
3288 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3289 if (LockdownVpnTracker.isEnabled()) {
3290 return false;
3291 }
3292
3293 // If the current VPN package is the same as the new one, this is a no-op
3294 final String oldPackage = getAlwaysOnVpnPackage(userId);
3295 if (TextUtils.equals(oldPackage, packageName)) {
3296 return true;
3297 }
3298
3299 synchronized (mVpns) {
3300 Vpn vpn = mVpns.get(userId);
3301 if (vpn == null) {
3302 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3303 return false;
3304 }
3305 if (!vpn.setAlwaysOnPackage(packageName)) {
3306 return false;
3307 }
3308 if (!updateAlwaysOnVpn(userId)) {
3309 vpn.setAlwaysOnPackage(null);
3310 return false;
3311 }
3312 }
3313 return true;
3314 }
3315
3316 @Override
3317 public String getAlwaysOnVpnPackage(int userId) {
3318 enforceConnectivityInternalPermission();
3319 enforceCrossUserPermission(userId);
3320
3321 synchronized (mVpns) {
3322 Vpn vpn = mVpns.get(userId);
3323 if (vpn == null) {
3324 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3325 return null;
3326 }
3327 return vpn.getAlwaysOnPackage();
3328 }
3329 }
3330
Wink Savilleab9321d2013-06-29 21:10:57 -07003331 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003332 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003333 // TODO: Remove? Any reason to trigger a provisioning check?
3334 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003335 }
3336
3337 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003338 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003339
Paul Jensen89e0f092014-09-15 15:59:36 -04003340 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003341 if (DBG) {
3342 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003343 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003344 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003345 Intent intent = new Intent(action);
3346 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003347 // Concatenate the range of types onto the range of NetIDs.
3348 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003349 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003350 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003351 }
3352
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003353 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003354 * Show or hide network provisioning notifications.
3355 *
3356 * We use notifications for two purposes: to notify that a network requires sign in
3357 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3358 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3359 * particular network we can display the notification type that was most recently requested.
3360 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3361 * might first display NO_INTERNET, and then when the captive portal check completes, display
3362 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003363 *
3364 * @param id an identifier that uniquely identifies this notification. This must match
3365 * between show and hide calls. We use the NetID value but for legacy callers
3366 * we concatenate the range of types with the range of NetIDs.
3367 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003368 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003369 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3370 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003371 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003372 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3373 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003374 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003375 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003376
3377 Resources r = Resources.getSystem();
3378 NotificationManager notificationManager = (NotificationManager) mContext
3379 .getSystemService(Context.NOTIFICATION_SERVICE);
3380
3381 if (visible) {
3382 CharSequence title;
3383 CharSequence details;
3384 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003385 if (notifyType == NotificationType.NO_INTERNET &&
3386 networkType == ConnectivityManager.TYPE_WIFI) {
3387 title = r.getString(R.string.wifi_no_internet, 0);
3388 details = r.getString(R.string.wifi_no_internet_detailed);
3389 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3390 } else if (notifyType == NotificationType.SIGN_IN) {
3391 switch (networkType) {
3392 case ConnectivityManager.TYPE_WIFI:
3393 title = r.getString(R.string.wifi_available_sign_in, 0);
3394 details = r.getString(R.string.network_available_sign_in_detailed,
3395 extraInfo);
3396 icon = R.drawable.stat_notify_wifi_in_range;
3397 break;
3398 case ConnectivityManager.TYPE_MOBILE:
3399 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3400 title = r.getString(R.string.network_available_sign_in, 0);
3401 // TODO: Change this to pull from NetworkInfo once a printable
3402 // name has been added to it
3403 details = mTelephonyManager.getNetworkOperatorName();
3404 icon = R.drawable.stat_notify_rssi_in_range;
3405 break;
3406 default:
3407 title = r.getString(R.string.network_available_sign_in, 0);
3408 details = r.getString(R.string.network_available_sign_in_detailed,
3409 extraInfo);
3410 icon = R.drawable.stat_notify_rssi_in_range;
3411 break;
3412 }
3413 } else {
3414 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3415 + getNetworkTypeName(networkType));
3416 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003417 }
3418
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003419 Notification notification = new Notification.Builder(mContext)
3420 .setWhen(0)
3421 .setSmallIcon(icon)
3422 .setAutoCancel(true)
3423 .setTicker(title)
3424 .setColor(mContext.getColor(
3425 com.android.internal.R.color.system_notification_accent_color))
3426 .setContentTitle(title)
3427 .setContentText(details)
3428 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003429 .setLocalOnly(true)
3430 .setPriority(highPriority ?
3431 Notification.PRIORITY_HIGH :
3432 Notification.PRIORITY_DEFAULT)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003433 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003434 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003435 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003436
Wink Saville948282b2013-08-29 08:55:16 -07003437 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003438 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003439 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003440 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003441 npe.printStackTrace();
3442 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003443 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003444 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003445 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003446 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003447 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003448 npe.printStackTrace();
3449 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003450 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003451 }
3452
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003453 /** Location to an updatable file listing carrier provisioning urls.
3454 * An example:
3455 *
3456 * <?xml version="1.0" encoding="utf-8"?>
3457 * <provisioningUrls>
3458 * <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 -07003459 * </provisioningUrls>
3460 */
3461 private static final String PROVISIONING_URL_PATH =
3462 "/data/misc/radio/provisioning_urls.xml";
3463 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003464
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003465 /** XML tag for root element. */
3466 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3467 /** XML tag for individual url */
3468 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003469 /** XML attribute for mcc */
3470 private static final String ATTR_MCC = "mcc";
3471 /** XML attribute for mnc */
3472 private static final String ATTR_MNC = "mnc";
3473
Paul Jensen434dde82015-06-11 09:43:30 -04003474 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003475 FileReader fileReader = null;
3476 XmlPullParser parser = null;
3477 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003478
3479 try {
3480 fileReader = new FileReader(mProvisioningUrlFile);
3481 parser = Xml.newPullParser();
3482 parser.setInput(fileReader);
3483 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3484
3485 while (true) {
3486 XmlUtils.nextElement(parser);
3487
3488 String element = parser.getName();
3489 if (element == null) break;
3490
Paul Jensen434dde82015-06-11 09:43:30 -04003491 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003492 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3493 try {
3494 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3495 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3496 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3497 parser.next();
3498 if (parser.getEventType() == XmlPullParser.TEXT) {
3499 return parser.getText();
3500 }
3501 }
3502 }
3503 } catch (NumberFormatException e) {
3504 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3505 }
3506 }
3507 }
3508 return null;
3509 } catch (FileNotFoundException e) {
3510 loge("Carrier Provisioning Urls file not found");
3511 } catch (XmlPullParserException e) {
3512 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3513 } catch (IOException e) {
3514 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3515 } finally {
3516 if (fileReader != null) {
3517 try {
3518 fileReader.close();
3519 } catch (IOException e) {}
3520 }
3521 }
3522 return null;
3523 }
3524
Wink Saville42d4f082013-07-20 20:31:59 -07003525 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003526 public String getMobileProvisioningUrl() {
3527 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003528 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003529 if (TextUtils.isEmpty(url)) {
3530 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003531 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003532 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003533 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003534 }
Wink Saville8cf35602013-07-10 23:00:07 -07003535 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003536 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003537 String phoneNumber = mTelephonyManager.getLine1Number();
3538 if (TextUtils.isEmpty(phoneNumber)) {
3539 phoneNumber = "0000000000";
3540 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003541 url = String.format(url,
3542 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3543 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003544 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003545 }
3546
Wink Savilleab9321d2013-06-29 21:10:57 -07003547 return url;
3548 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003549
Wink Saville948282b2013-08-29 08:55:16 -07003550 @Override
3551 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003552 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003553 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003554 final long ident = Binder.clearCallingIdentity();
3555 try {
3556 setProvNotificationVisible(visible, networkType, action);
3557 } finally {
3558 Binder.restoreCallingIdentity(ident);
3559 }
Wink Saville948282b2013-08-29 08:55:16 -07003560 }
Wink Saville7788c612013-08-29 14:57:08 -07003561
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003562 @Override
3563 public void setAirplaneMode(boolean enable) {
3564 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003565 final long ident = Binder.clearCallingIdentity();
3566 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003567 final ContentResolver cr = mContext.getContentResolver();
3568 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3569 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3570 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003571 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003572 } finally {
3573 Binder.restoreCallingIdentity(ident);
3574 }
3575 }
3576
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003577 private void onUserStart(int userId) {
3578 synchronized(mVpns) {
3579 Vpn userVpn = mVpns.get(userId);
3580 if (userVpn != null) {
3581 loge("Starting user already has a VPN");
3582 return;
3583 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003584 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003585 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003586 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003587 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3588 updateLockdownVpn();
3589 } else {
3590 updateAlwaysOnVpn(userId);
3591 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003592 }
3593
3594 private void onUserStop(int userId) {
3595 synchronized(mVpns) {
3596 Vpn userVpn = mVpns.get(userId);
3597 if (userVpn == null) {
3598 loge("Stopping user has no VPN");
3599 return;
3600 }
3601 mVpns.delete(userId);
3602 }
3603 }
3604
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003605 private void onUserAdded(int userId) {
3606 synchronized(mVpns) {
3607 final int vpnsSize = mVpns.size();
3608 for (int i = 0; i < vpnsSize; i++) {
3609 Vpn vpn = mVpns.valueAt(i);
3610 vpn.onUserAdded(userId);
3611 }
3612 }
3613 }
3614
3615 private void onUserRemoved(int userId) {
3616 synchronized(mVpns) {
3617 final int vpnsSize = mVpns.size();
3618 for (int i = 0; i < vpnsSize; i++) {
3619 Vpn vpn = mVpns.valueAt(i);
3620 vpn.onUserRemoved(userId);
3621 }
3622 }
3623 }
3624
Robin Lee89e7a692016-02-29 14:38:17 +00003625 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003626 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3627 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3628 updateLockdownVpn();
3629 } else {
3630 updateAlwaysOnVpn(userId);
3631 }
3632 }
3633
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003634 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3635 @Override
3636 public void onReceive(Context context, Intent intent) {
3637 final String action = intent.getAction();
3638 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3639 if (userId == UserHandle.USER_NULL) return;
3640
3641 if (Intent.ACTION_USER_STARTING.equals(action)) {
3642 onUserStart(userId);
3643 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3644 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003645 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3646 onUserAdded(userId);
3647 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3648 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003649 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3650 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003651 }
3652 }
3653 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003654
Robert Greenwalta67be032014-05-16 15:49:14 -07003655 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3656 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003657 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3658 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003659
Robert Greenwalta67be032014-05-16 15:49:14 -07003660 private static class NetworkFactoryInfo {
3661 public final String name;
3662 public final Messenger messenger;
3663 public final AsyncChannel asyncChannel;
3664
3665 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3666 this.name = name;
3667 this.messenger = messenger;
3668 this.asyncChannel = asyncChannel;
3669 }
3670 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003671
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003672 /**
Erik Kline371c7b72016-03-22 17:04:20 +09003673 * A NetworkRequest as registered by an application can be one of three
3674 * types:
3675 *
3676 * - "listen", for which the framework will issue callbacks about any
3677 * and all networks that match the specified NetworkCapabilities,
3678 *
3679 * - "request", capable of causing a specific network to be created
3680 * first (e.g. a telephony DUN request), the framework will issue
3681 * callbacks about the single, highest scoring current network
3682 * (if any) that matches the specified NetworkCapabilities, or
3683 *
3684 * - "track the default network", a hybrid of the two designed such
3685 * that the framework will issue callbacks for the single, highest
3686 * scoring current network (if any) that matches the capabilities of
3687 * the default Internet request (mDefaultRequest), but which cannot
3688 * cause the framework to either create or retain the existence of
3689 * any specific network.
3690 *
3691 */
3692 private static enum NetworkRequestType {
3693 LISTEN,
3694 TRACK_DEFAULT,
3695 REQUEST
3696 };
3697
3698 /**
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003699 * Tracks info about the requester.
3700 * Also used to notice when the calling process dies so we can self-expire
3701 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003702 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003703 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003704 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003705 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003706 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003707 final int mPid;
3708 final int mUid;
3709 final Messenger messenger;
Erik Kline371c7b72016-03-22 17:04:20 +09003710 private final NetworkRequestType mType;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003711
Erik Kline371c7b72016-03-22 17:04:20 +09003712 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, NetworkRequestType type) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003713 request = r;
3714 mPendingIntent = pi;
3715 messenger = null;
3716 mBinder = null;
3717 mPid = getCallingPid();
3718 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003719 mType = type;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003720 }
3721
Erik Kline371c7b72016-03-22 17:04:20 +09003722 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, NetworkRequestType type) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003723 super();
3724 messenger = m;
3725 request = r;
3726 mBinder = binder;
3727 mPid = getCallingPid();
3728 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003729 mType = type;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003730 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003731
3732 try {
3733 mBinder.linkToDeath(this, 0);
3734 } catch (RemoteException e) {
3735 binderDied();
3736 }
3737 }
3738
Erik Kline371c7b72016-03-22 17:04:20 +09003739 private String typeString() {
3740 switch (mType) {
3741 case LISTEN: return "Listen";
3742 case REQUEST: return "Request";
3743 case TRACK_DEFAULT: return "Track default";
3744 default:
3745 return "unknown type";
3746 }
3747 }
3748
Robert Greenwalt9258c642014-03-26 16:47:06 -07003749 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003750 if (mBinder != null) {
3751 mBinder.unlinkToDeath(this, 0);
3752 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003753 }
3754
3755 public void binderDied() {
3756 log("ConnectivityService NetworkRequestInfo binderDied(" +
3757 request + ", " + mBinder + ")");
3758 releaseNetworkRequest(request);
3759 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003760
Erik Kline371c7b72016-03-22 17:04:20 +09003761 /**
3762 * Returns true iff. the contained NetworkRequest is one that:
3763 *
3764 * - should be associated with at most one satisfying network
3765 * at a time;
3766 *
3767 * - should cause a network to be kept up if it is the only network
3768 * which can satisfy the NetworkReqeust.
3769 *
3770 * For full detail of how isRequest() is used for pairing Networks with
3771 * NetworkRequests read rematchNetworkAndRequests().
3772 *
3773 * TODO: Rename to something more properly descriptive.
3774 */
3775 public boolean isRequest() {
3776 return (mType == NetworkRequestType.TRACK_DEFAULT) ||
3777 (mType == NetworkRequestType.REQUEST);
3778 }
3779
Robert Greenwalta67be032014-05-16 15:49:14 -07003780 public String toString() {
Erik Kline371c7b72016-03-22 17:04:20 +09003781 return typeString() +
Erik Kline7523eb32015-07-09 18:24:03 +09003782 " from uid/pid:" + mUid + "/" + mPid +
3783 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003784 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003785 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003786 }
3787
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003788 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3789 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3790 if (badCapability != null) {
3791 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003792 }
3793 }
3794
Erik Kline9d598e12015-07-13 16:37:51 +09003795 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003796 final SortedSet<Integer> thresholds = new TreeSet();
3797 synchronized (nai) {
3798 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3799 if (nri.request.networkCapabilities.hasSignalStrength() &&
3800 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3801 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3802 }
3803 }
3804 }
Erik Kline9d598e12015-07-13 16:37:51 +09003805 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003806 }
3807
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003808 private void updateSignalStrengthThresholds(
3809 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3810 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003811 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003812 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3813
3814 // TODO: Switch to VDBG.
3815 if (DBG) {
3816 String detail;
3817 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3818 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3819 } else {
3820 detail = reason;
3821 }
3822 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3823 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3824 }
3825
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003826 nai.asyncChannel.sendMessage(
3827 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003828 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003829 }
3830
Robert Greenwalt9258c642014-03-26 16:47:06 -07003831 @Override
3832 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003833 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Erik Kline371c7b72016-03-22 17:04:20 +09003834 final NetworkRequestType type = (networkCapabilities == null)
3835 ? NetworkRequestType.TRACK_DEFAULT
3836 : NetworkRequestType.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09003837 // If the requested networkCapabilities is null, take them instead from
3838 // the default network request. This allows callers to keep track of
3839 // the system default network.
Erik Kline371c7b72016-03-22 17:04:20 +09003840 if (type == NetworkRequestType.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09003841 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
3842 enforceAccessPermission();
3843 } else {
3844 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3845 enforceNetworkRequestPermissions(networkCapabilities);
3846 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003847 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003848 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003849
Robert Greenwalt6078b502014-06-11 16:05:07 -07003850 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003851 throw new IllegalArgumentException("Bad timeout specified");
3852 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003853
Etan Cohenddb9ef02015-11-18 10:56:15 -08003854 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
3855 .equals(networkCapabilities.getNetworkSpecifier())) {
3856 throw new IllegalArgumentException("Invalid network specifier - must not be '"
3857 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
3858 }
3859
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003860 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3861 nextNetworkRequestId());
Erik Kline371c7b72016-03-22 17:04:20 +09003862 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, type);
Erik Kline7523eb32015-07-09 18:24:03 +09003863 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003864
3865 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003866 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003867 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003868 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003869 }
3870 return networkRequest;
3871 }
3872
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003873 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003874 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003875 enforceConnectivityInternalPermission();
3876 } else {
3877 enforceChangePermission();
3878 }
3879 }
3880
fenglub15e72b2015-03-20 11:29:56 -07003881 @Override
fengludb571472015-04-21 17:12:05 -07003882 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003883 enforceAccessPermission();
3884 NetworkAgentInfo nai = null;
3885 if (network == null) {
3886 return false;
3887 }
3888 synchronized (mNetworkForNetId) {
3889 nai = mNetworkForNetId.get(network.netId);
3890 }
3891 if (nai != null) {
3892 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3893 return true;
3894 }
3895 return false;
3896 }
3897
3898
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003899 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3900 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003901 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003902 final int uidRules;
3903 final int uid = Binder.getCallingUid();
3904 synchronized(mRulesLock) {
3905 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3906 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003907 if (uidRules != RULE_ALLOW_ALL) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003908 // we could silently fail or we can filter the available nets to only give
3909 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003910 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003911 }
3912 }
3913 }
3914
Robert Greenwalt9258c642014-03-26 16:47:06 -07003915 @Override
3916 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3917 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003918 checkNotNull(operation, "PendingIntent cannot be null.");
3919 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3920 enforceNetworkRequestPermissions(networkCapabilities);
3921 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003922 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003923
3924 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3925 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003926 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09003927 NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003928 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003929 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3930 nri));
3931 return networkRequest;
3932 }
3933
Jeremy Joslin79294842014-12-03 17:15:28 -08003934 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3935 mHandler.sendMessageDelayed(
3936 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3937 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3938 }
3939
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003940 @Override
3941 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003942 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003943 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3944 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003945 }
3946
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003947 // In order to implement the compatibility measure for pre-M apps that call
3948 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3949 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3950 // This ensures it has permission to do so.
3951 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3952 if (nc == null) {
3953 return false;
3954 }
3955 int[] transportTypes = nc.getTransportTypes();
3956 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3957 return false;
3958 }
3959 try {
3960 mContext.enforceCallingOrSelfPermission(
3961 android.Manifest.permission.ACCESS_WIFI_STATE,
3962 "ConnectivityService");
3963 } catch (SecurityException e) {
3964 return false;
3965 }
3966 return true;
3967 }
3968
Robert Greenwalt9258c642014-03-26 16:47:06 -07003969 @Override
3970 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3971 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003972 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3973 enforceAccessPermission();
3974 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003975
Erik Kline7523eb32015-07-09 18:24:03 +09003976 NetworkRequest networkRequest = new NetworkRequest(
3977 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003978 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
Erik Kline371c7b72016-03-22 17:04:20 +09003979 NetworkRequestType.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003980 if (DBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003981
3982 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3983 return networkRequest;
3984 }
3985
3986 @Override
3987 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3988 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003989 checkNotNull(operation, "PendingIntent cannot be null.");
3990 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3991 enforceAccessPermission();
3992 }
3993
Erik Kline7523eb32015-07-09 18:24:03 +09003994 NetworkRequest networkRequest = new NetworkRequest(
3995 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04003996 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09003997 NetworkRequestType.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003998 if (DBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04003999
4000 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004001 }
4002
4003 @Override
4004 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04004005 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4006 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004007 }
4008
4009 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004010 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004011 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004012 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4013 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004014 }
4015
Robert Greenwalta67be032014-05-16 15:49:14 -07004016 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004017 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004018 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4019 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4020 }
4021
4022 @Override
4023 public void unregisterNetworkFactory(Messenger messenger) {
4024 enforceConnectivityInternalPermission();
4025 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4026 }
4027
4028 private void handleUnregisterNetworkFactory(Messenger messenger) {
4029 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4030 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004031 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004032 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004033 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004034 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004035 }
4036
Robert Greenwalt7b816022014-04-18 15:25:25 -07004037 /**
4038 * NetworkAgentInfo supporting a request by requestId.
4039 * These have already been vetted (their Capabilities satisfy the request)
4040 * and the are the highest scored network available.
4041 * the are keyed off the Requests requestId.
4042 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004043 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004044 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4045 new SparseArray<NetworkAgentInfo>();
4046
Paul Jensen31a94f42015-02-13 14:18:39 -05004047 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4048 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004049 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4050 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004051 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4052 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4053 // there may not be a strict 1:1 correlation between the two.
4054 @GuardedBy("mNetworkForNetId")
4055 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004056
Robert Greenwalt7b816022014-04-18 15:25:25 -07004057 // NetworkAgentInfo keyed off its connecting messenger
4058 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004059 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004060 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4061 new HashMap<Messenger, NetworkAgentInfo>();
4062
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004063 @GuardedBy("mBlockedAppUids")
4064 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4065
Paul Jensen2c311d62014-11-17 12:34:51 -05004066 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004067 private final NetworkRequest mDefaultRequest;
4068
Erik Klineda4bfa82015-04-30 12:58:40 +09004069 // Request used to optionally keep mobile data active even when higher
4070 // priority networks like Wi-Fi are active.
4071 private final NetworkRequest mDefaultMobileDataRequest;
4072
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004073 private NetworkAgentInfo getDefaultNetwork() {
4074 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4075 }
4076
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004077 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004078 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004079 }
4080
Paul Jensen31a94f42015-02-13 14:18:39 -05004081 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004082 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004083 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004084 enforceConnectivityInternalPermission();
4085
Paul Jensen2c311d62014-11-17 12:34:51 -05004086 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4087 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004088 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004089 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4090 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004091 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004092 synchronized (this) {
4093 nai.networkMonitor.systemReady = mSystemReady;
4094 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07004095 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004096 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004097 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004098 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004099 }
4100
4101 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4102 if (VDBG) log("Got NetworkAgent Messenger");
4103 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004104 synchronized (mNetworkForNetId) {
4105 mNetworkForNetId.put(na.network.netId, na);
4106 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004107 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4108 NetworkInfo networkInfo = na.networkInfo;
4109 na.networkInfo = null;
4110 updateNetworkInfo(na, networkInfo);
4111 }
4112
4113 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4114 LinkProperties newLp = networkAgent.linkProperties;
4115 int netId = networkAgent.network.netId;
4116
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004117 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4118 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004119 if (networkAgent.clatd != null) {
4120 networkAgent.clatd.fixupLinkProperties(oldLp);
4121 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004122
Paul Jensen992f2522014-04-28 10:33:11 -04004123 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004124 updateMtu(newLp, oldLp);
4125 // TODO - figure out what to do for clat
4126// for (LinkProperties lp : newLp.getStackedLinks()) {
4127// updateMtu(lp, null);
4128// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004129 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004130
Erik Kline94887872016-04-05 13:30:49 +09004131 updateRoutes(newLp, oldLp, netId);
4132 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004133
Paul Jensen3b759822014-05-13 11:44:01 -04004134 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004135 if (isDefaultNetwork(networkAgent)) {
4136 handleApplyDefaultProxy(newLp.getHttpProxy());
4137 } else {
4138 updateProxy(newLp, oldLp, networkAgent);
4139 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004140 // TODO - move this check to cover the whole function
4141 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004142 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004143 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4144 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004145
4146 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004147 }
4148
Lorenzo Colitti95439462014-10-09 13:44:48 +09004149 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4150 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4151 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004152
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004153 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004154 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4155 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004156 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004157 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004158 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004159 }
Paul Jensen992f2522014-04-28 10:33:11 -04004160
4161 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4162 CompareResult<String> interfaceDiff = new CompareResult<String>();
4163 if (oldLp != null) {
4164 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4165 } else if (newLp != null) {
4166 interfaceDiff.added = newLp.getAllInterfaceNames();
4167 }
4168 for (String iface : interfaceDiff.added) {
4169 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004170 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004171 mNetd.addInterfaceToNetwork(iface, netId);
4172 } catch (Exception e) {
4173 loge("Exception adding interface: " + e);
4174 }
4175 }
4176 for (String iface : interfaceDiff.removed) {
4177 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004178 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004179 mNetd.removeInterfaceFromNetwork(iface, netId);
4180 } catch (Exception e) {
4181 loge("Exception removing interface: " + e);
4182 }
4183 }
4184 }
4185
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004186 /**
4187 * Have netd update routes from oldLp to newLp.
4188 * @return true if routes changed between oldLp and newLp
4189 */
4190 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004191 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4192 if (oldLp != null) {
4193 routeDiff = oldLp.compareAllRoutes(newLp);
4194 } else if (newLp != null) {
4195 routeDiff.added = newLp.getAllRoutes();
4196 }
4197
4198 // add routes before removing old in case it helps with continuous connectivity
4199
4200 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4201 for (RouteInfo route : routeDiff.added) {
4202 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004203 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004204 try {
4205 mNetd.addRoute(netId, route);
4206 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004207 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4208 loge("Exception in addRoute for non-gateway: " + e);
4209 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004210 }
4211 }
4212 for (RouteInfo route : routeDiff.added) {
4213 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004214 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004215 try {
4216 mNetd.addRoute(netId, route);
4217 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004218 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4219 loge("Exception in addRoute for gateway: " + e);
4220 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004221 }
4222 }
4223
4224 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004225 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004226 try {
4227 mNetd.removeRoute(netId, route);
4228 } catch (Exception e) {
4229 loge("Exception in removeRoute: " + e);
4230 }
4231 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004232 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004233 }
Erik Kline41368502015-06-17 13:19:54 +09004234
Erik Kline94887872016-04-05 13:30:49 +09004235 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4236 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4237 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004238 }
Erik Kline94887872016-04-05 13:30:49 +09004239
4240 Collection<InetAddress> dnses = newLp.getDnsServers();
4241 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
4242 try {
4243 mNetd.setDnsServersForNetwork(
4244 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4245 } catch (Exception e) {
4246 loge("Exception in setDnsServersForNetwork: " + e);
4247 }
4248 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4249 if (defaultNai != null && defaultNai.network.netId == netId) {
4250 setDefaultDnsSystemProperties(dnses);
4251 }
4252 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004253 }
4254
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004255 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4256 int last = 0;
4257 for (InetAddress dns : dnses) {
4258 ++last;
4259 String key = "net.dns" + last;
4260 String value = dns.getHostAddress();
4261 SystemProperties.set(key, value);
4262 }
4263 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4264 String key = "net.dns" + i;
4265 SystemProperties.set(key, "");
4266 }
4267 mNumDnsEntries = last;
4268 }
4269
Paul Jensen3d194ea2015-06-16 14:27:36 -04004270 /**
4271 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4272 * augmented with any stateful capabilities implied from {@code networkAgent}
4273 * (e.g., validated status and captive portal status).
4274 *
Paul Jensene0988542015-06-25 15:30:08 -04004275 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004276 * @param networkCapabilities the new network capabilities.
4277 */
Paul Jensene0988542015-06-25 15:30:08 -04004278 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004279 // Don't modify caller's NetworkCapabilities.
4280 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004281 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004282 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4283 } else {
4284 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4285 }
Paul Jensene0988542015-06-25 15:30:08 -04004286 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004287 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4288 } else {
4289 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4290 }
Paul Jensene0988542015-06-25 15:30:08 -04004291 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4292 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004293 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4294 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4295 try {
4296 mNetd.setNetworkPermission(nai.network.netId,
4297 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4298 null : NetworkManagementService.PERMISSION_SYSTEM);
4299 } catch (RemoteException e) {
4300 loge("Exception in setNetworkPermission: " + e);
4301 }
4302 }
Paul Jensene0988542015-06-25 15:30:08 -04004303 synchronized (nai) {
4304 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004305 }
Paul Jensene0988542015-06-25 15:30:08 -04004306 rematchAllNetworksAndRequests(nai, oldScore);
4307 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004308 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004309 }
4310
Paul Jensenc8b9a742014-09-30 15:37:41 -04004311 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4312 for (int i = 0; i < nai.networkRequests.size(); i++) {
4313 NetworkRequest nr = nai.networkRequests.valueAt(i);
4314 // Don't send listening requests to factories. b/17393458
4315 if (!isRequest(nr)) continue;
4316 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4317 }
4318 }
4319
Robert Greenwalt7b816022014-04-18 15:25:25 -07004320 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4321 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004322 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004323 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4324 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004325 }
4326 }
4327
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004328 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4329 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004330 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004331 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004332 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4333 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004334 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004335 sendIntent(nri.mPendingIntent, intent);
4336 }
4337 // else not handled
4338 }
4339
4340 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4341 mPendingIntentWakeLock.acquire();
4342 try {
4343 if (DBG) log("Sending " + pendingIntent);
4344 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4345 } catch (PendingIntent.CanceledException e) {
4346 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4347 mPendingIntentWakeLock.release();
4348 releasePendingNetworkRequest(pendingIntent);
4349 }
4350 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4351 }
4352
4353 @Override
4354 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4355 String resultData, Bundle resultExtras) {
4356 if (DBG) log("Finished sending " + pendingIntent);
4357 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004358 // Release with a delay so the receiving client has an opportunity to put in its
4359 // own request.
4360 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004361 }
4362
Robert Greenwalt9258c642014-03-26 16:47:06 -07004363 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004364 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004365 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004366 Bundle bundle = new Bundle();
4367 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4368 new NetworkRequest(nri.request));
4369 Message msg = Message.obtain();
4370 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4371 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4372 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4373 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004374 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004375 case ConnectivityManager.CALLBACK_LOSING: {
4376 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4377 break;
4378 }
4379 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4380 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4381 new NetworkCapabilities(networkAgent.networkCapabilities));
4382 break;
4383 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004384 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004385 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4386 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004387 break;
4388 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004389 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004390 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004391 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004392 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004393 if (VDBG) {
4394 log("sending notification " + notifyTypeToName(notificationType) +
4395 " for " + nri.request);
4396 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004397 nri.messenger.send(msg);
4398 } catch (RemoteException e) {
4399 // may occur naturally in the race of binder death.
4400 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4401 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004402 }
4403
Paul Jensenc8b9a742014-09-30 15:37:41 -04004404 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4405 for (int i = 0; i < nai.networkRequests.size(); i++) {
4406 NetworkRequest nr = nai.networkRequests.valueAt(i);
4407 // Ignore listening requests.
4408 if (!isRequest(nr)) continue;
4409 loge("Dead network still had at least " + nr);
4410 break;
4411 }
4412 nai.asyncChannel.disconnect();
4413 }
4414
Robert Greenwalt7b816022014-04-18 15:25:25 -07004415 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4416 if (oldNetwork == null) {
4417 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4418 return;
4419 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004420 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4421 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004422 }
4423
Paul Jensen27b02b72014-07-14 12:03:33 -04004424 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004425 if (DBG) log("Switching to new default network: " + newNetwork);
Pierre Imai55618be2016-02-19 15:25:54 +09004426 ConnectivityServiceChangeEvent.logEvent(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04004427 setupDataActivityTracking(newNetwork);
4428 try {
4429 mNetd.setDefaultNetId(newNetwork.network.netId);
4430 } catch (Exception e) {
4431 loge("Exception setting default network :" + e);
4432 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004433 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004434 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004435 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004436 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004437 }
4438
Paul Jensen2161a8e2014-09-11 11:00:39 -04004439 // Handles a network appearing or improving its score.
4440 //
4441 // - Evaluates all current NetworkRequests that can be
4442 // satisfied by newNetwork, and reassigns to newNetwork
4443 // any such requests for which newNetwork is the best.
4444 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004445 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004446 // needed. A network is needed if it is the best network for
4447 // one or more NetworkRequests, or if it is a VPN.
4448 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004449 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004450 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004451 //
4452 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4453 // networks that have no chance (i.e. even if validated)
4454 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004455 //
4456 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4457 // it does not remove NetworkRequests that other Networks could better satisfy.
4458 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4459 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4460 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004461 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004462 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004463 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4464 // performed to tear down unvalidated networks that have no chance (i.e. even if
4465 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004466 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004467 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004468 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004469 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004470 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004471 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004472 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004473 // Find and migrate to this Network any NetworkRequests for
4474 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004475 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004476 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004477 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004478 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004479 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4480 final boolean satisfies = newNetwork.satisfies(nri.request);
4481 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004482 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004483 log("Network " + newNetwork.name() + " was already satisfying" +
4484 " request " + nri.request.requestId + ". No change.");
4485 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004486 keep = true;
4487 continue;
4488 }
4489
4490 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004491 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004492 if (satisfies) {
Erik Kline371c7b72016-03-22 17:04:20 +09004493 if (!nri.isRequest()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004494 // This is not a request, it's a callback listener.
4495 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004496 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004497 continue;
4498 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004499
Robert Greenwalt7b816022014-04-18 15:25:25 -07004500 // next check if it's better than any current network we're using for
4501 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004502 if (VDBG) {
4503 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004504 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4505 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004506 }
4507 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004508 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004509 if (DBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004510 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004511 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004512 currentNetwork.networkRequests.remove(nri.request.requestId);
4513 currentNetwork.networkLingered.add(nri.request);
4514 affectedNetworks.add(currentNetwork);
4515 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004516 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004517 }
Paul Jensen573a0352015-01-08 10:49:34 -05004518 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004519 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004520 if (!newNetwork.addRequest(nri.request)) {
4521 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4522 }
4523 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004524 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004525 // Tell NetworkFactories about the new score, so they can stop
4526 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004527 // TODO - this could get expensive if we have alot of requests for this
4528 // network. Think about if there is a way to reduce this. Push
4529 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004530 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004531 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004532 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004533 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004534 }
4535 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004536 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4537 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4538 // mark it as no longer satisfying "nri". Because networks are processed by
4539 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4540 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4541 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4542 // This means this code doesn't have to handle the case where "currentNetwork" no
4543 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4544 if (DBG) {
4545 log("Network " + newNetwork.name() + " stopped satisfying" +
4546 " request " + nri.request.requestId);
4547 }
4548 newNetwork.networkRequests.remove(nri.request.requestId);
4549 if (currentNetwork == newNetwork) {
4550 mNetworkForRequestId.remove(nri.request.requestId);
4551 sendUpdatedScoreToFactories(nri.request, 0);
4552 } else {
Erik Kline371c7b72016-03-22 17:04:20 +09004553 if (nri.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004554 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4555 newNetwork.name() +
4556 " without updating mNetworkForRequestId or factories!");
4557 }
4558 }
4559 // TODO: technically, sending CALLBACK_LOST here is
4560 // incorrect if nri is a request (not a listen) and there
4561 // is a replacement network currently connected that can
4562 // satisfy it. However, the only capability that can both
4563 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4564 // so this code is only incorrect for a network that loses
4565 // the TRUSTED capability, which is a rare case.
4566 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004567 }
4568 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004569 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004570 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004571 if (nai.lingering) {
4572 // Already lingered. Nothing to do. This can only happen if "nai" is in
4573 // "affectedNetworks" twice. The reasoning being that to get added to
4574 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4575 // (i.e. not lingered) so it could have only been lingered by this loop.
4576 // unneeded(nai) will be false and we'll call unlinger() below which would
4577 // be bad, so handle it here.
4578 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004579 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004580 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004581 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004582 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004583 }
4584 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004585 if (isNewDefault) {
4586 // Notify system services that this network is up.
4587 makeDefault(newNetwork);
4588 synchronized (ConnectivityService.this) {
4589 // have a new default network, release the transition wakelock in
4590 // a second if it's held. The second pause is to allow apps
4591 // to reconnect over the new network
4592 if (mNetTransitionWakeLock.isHeld()) {
4593 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4594 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4595 mNetTransitionWakeLockSerialNumber, 0),
4596 1000);
4597 }
4598 }
4599 }
4600
4601 // do this after the default net is switched, but
4602 // before LegacyTypeTracker sends legacy broadcasts
4603 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4604
4605 if (isNewDefault) {
4606 // Maintain the illusion: since the legacy API only
4607 // understands one network at a time, we must pretend
4608 // that the current default network disconnected before
4609 // the new one connected.
4610 if (oldDefaultNetwork != null) {
4611 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4612 oldDefaultNetwork, true);
4613 }
4614 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4615 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4616 notifyLockdownVpn(newNetwork);
4617 }
4618
Robert Greenwalt7b816022014-04-18 15:25:25 -07004619 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004620 // Notify battery stats service about this network, both the normal
4621 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004622 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004623 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004624 final IBatteryStats bs = BatteryStatsService.getService();
4625 final int type = newNetwork.networkInfo.getType();
4626
4627 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4628 bs.noteNetworkInterfaceType(baseIface, type);
4629 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4630 final String stackedIface = stacked.getInterfaceName();
4631 bs.noteNetworkInterfaceType(stackedIface, type);
4632 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4633 }
4634 } catch (RemoteException ignored) {
4635 }
4636
Robert Greenwalt152ed372014-12-17 17:19:53 -08004637 // This has to happen after the notifyNetworkCallbacks as that tickles each
4638 // ConnectivityManager instance so that legacy requests correctly bind dns
4639 // requests to this network. The legacy users are listening for this bcast
4640 // and will generally do a dns request so they can ensureRouteToHost and if
4641 // they do that before the callbacks happen they'll use the default network.
4642 //
4643 // TODO: Is there still a race here? We send the broadcast
4644 // after sending the callback, but if the app can receive the
4645 // broadcast before the callback, it might still break.
4646 //
4647 // This *does* introduce a race where if the user uses the new api
4648 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4649 // they may get old info. Reverse this after the old startUsing api is removed.
4650 // This is on top of the multiple intent sequencing referenced in the todo above.
4651 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4652 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4653 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4654 // legacy type tracker filters out repeat adds
4655 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4656 }
4657 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004658
4659 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4660 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4661 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4662 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4663 if (newNetwork.isVPN()) {
4664 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4665 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004666 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004667 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4668 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004669 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004670 if (DBG) log("Reaping " + nai.name());
4671 teardownUnneededNetwork(nai);
4672 }
4673 }
4674 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004675 }
4676
Paul Jensen1c7ba022015-06-16 14:27:36 -04004677 /**
4678 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4679 * being disconnected.
4680 * @param changed If only one Network's score or capabilities have been modified since the last
4681 * time this function was called, pass this Network in this argument, otherwise pass
4682 * null.
4683 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4684 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4685 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4686 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4687 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004688 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004689 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004690 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4691 // to avoid the slowness. It is not simply enough to process just "changed", for
4692 // example in the case where "changed"'s score decreases and another network should begin
4693 // satifying a NetworkRequest that "changed" currently satisfies.
4694
4695 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4696 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4697 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004698 if (changed != null && oldScore < changed.getCurrentScore()) {
4699 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004700 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004701 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4702 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4703 // Rematch higher scoring networks first to prevent requests first matching a lower
4704 // scoring network and then a higher scoring network, which could produce multiple
4705 // callbacks and inadvertently unlinger networks.
4706 Arrays.sort(nais);
4707 for (NetworkAgentInfo nai : nais) {
4708 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004709 // Only reap the last time through the loop. Reaping before all rematching
4710 // is complete could incorrectly teardown a network that hasn't yet been
4711 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004712 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004713 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004714 }
4715 }
4716 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004717
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004718 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004719 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004720 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004721 // For now only update icons for default connection.
4722 // TODO: Update WiFi and cellular icons separately. b/17237507
4723 if (!isDefaultNetwork(nai)) return;
4724
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004725 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004726 // Don't repeat publish.
4727 if (newInetCondition == mDefaultInetConditionPublished) return;
4728
4729 mDefaultInetConditionPublished = newInetCondition;
4730 sendInetConditionBroadcast(nai.networkInfo);
4731 }
4732
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004733 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4734 if (mLockdownTracker != null) {
4735 if (nai != null && nai.isVPN()) {
4736 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4737 } else {
4738 mLockdownTracker.onNetworkInfoChanged();
4739 }
4740 }
4741 }
4742
Robert Greenwalt7b816022014-04-18 15:25:25 -07004743 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4744 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004745 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004746 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004747 synchronized (networkAgent) {
4748 oldInfo = networkAgent.networkInfo;
4749 networkAgent.networkInfo = newInfo;
4750 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004751 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004752
4753 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004754 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4755 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4756 notifyIfacesChangedForNetworkStats();
4757 } else if (VDBG) log("ignoring duplicate network state non-change");
4758 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004759 return;
4760 }
4761 if (DBG) {
4762 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4763 (oldInfo == null ? "null" : oldInfo.getState()) +
4764 " to " + state);
4765 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004766
Paul Jenseneec75412014-08-04 12:21:19 -04004767 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004768 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004769 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004770 if (networkAgent.isVPN()) {
4771 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004772 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4773 (networkAgent.networkMisc == null ||
4774 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004775 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004776 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4777 networkAgent.networkCapabilities.hasCapability(
4778 NET_CAPABILITY_NOT_RESTRICTED) ?
4779 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004780 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004781 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004782 loge("Error creating network " + networkAgent.network.netId + ": "
4783 + e.getMessage());
4784 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004785 }
Paul Jenseneec75412014-08-04 12:21:19 -04004786 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004787 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004788 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004789
Paul Jensenca8f16a2014-05-09 12:47:55 -04004790 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004791 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004792
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004793 if (networkAgent.isVPN()) {
4794 // Temporarily disable the default proxy (not global).
4795 synchronized (mProxyLock) {
4796 if (!mDefaultProxyDisabled) {
4797 mDefaultProxyDisabled = true;
4798 if (mGlobalProxy == null && mDefaultProxy != null) {
4799 sendProxyBroadcast(null);
4800 }
4801 }
4802 }
4803 // TODO: support proxy per network.
4804 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004805
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004806 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4807 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4808 // capabilities, so it only needs to be done once on initial connect, not every time the
4809 // network's capabilities change. Note that we do this before rematching the network,
4810 // so we could decide to tear it down immediately afterwards. That's fine though - on
4811 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4812 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004813 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004814
Paul Jensen2161a8e2014-09-11 11:00:39 -04004815 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004816 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004817
4818 // This has to happen after matching the requests, because callbacks are just requests.
4819 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004820 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004821 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004822 if (networkAgent.isVPN()) {
4823 synchronized (mProxyLock) {
4824 if (mDefaultProxyDisabled) {
4825 mDefaultProxyDisabled = false;
4826 if (mGlobalProxy == null && mDefaultProxy != null) {
4827 sendProxyBroadcast(mDefaultProxy);
4828 }
4829 }
4830 }
4831 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004832 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4833 state == NetworkInfo.State.SUSPENDED) {
4834 // going into or coming out of SUSPEND: rescore and notify
4835 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004836 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004837 }
4838 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4839 ConnectivityManager.CALLBACK_SUSPENDED :
4840 ConnectivityManager.CALLBACK_RESUMED));
4841 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004842 }
4843 }
4844
Robert Greenwaltac96c522014-06-03 16:43:57 -07004845 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4846 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004847 if (score < 0) {
4848 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4849 "). Bumping score to min of 0");
4850 score = 0;
4851 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004852
Paul Jensen2161a8e2014-09-11 11:00:39 -04004853 final int oldScore = nai.getCurrentScore();
4854 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004855
Paul Jensen85cf78e2015-06-25 13:25:07 -04004856 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004857
Paul Jensenc8b9a742014-09-30 15:37:41 -04004858 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004859 }
4860
Robert Greenwalt9258c642014-03-26 16:47:06 -07004861 // notify only this one new request of the current state
4862 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4863 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4864 // TODO - read state from monitor to decide what to send.
4865// if (nai.networkMonitor.isLingering()) {
4866// notifyType = NetworkCallbacks.LOSING;
4867// } else if (nai.networkMonitor.isEvaluating()) {
4868// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4869// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004870 if (nri.mPendingIntent == null) {
4871 callCallbackForRequest(nri, nai, notifyType);
4872 } else {
4873 sendPendingIntentForRequest(nri, nai, notifyType);
4874 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004875 }
4876
Robert Greenwalt8d482522015-06-24 13:23:42 -07004877 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004878 // The NetworkInfo we actually send out has no bearing on the real
4879 // state of affairs. For example, if the default connection is mobile,
4880 // and a request for HIPRI has just gone away, we need to pretend that
4881 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4882 // the state to DISCONNECTED, even though the network is of type MOBILE
4883 // and is still connected.
4884 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4885 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004886 if (state != DetailedState.DISCONNECTED) {
4887 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004888 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004889 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004890 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004891 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4892 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4893 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4894 if (info.isFailover()) {
4895 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4896 nai.networkInfo.setFailover(false);
4897 }
4898 if (info.getReason() != null) {
4899 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4900 }
4901 if (info.getExtraInfo() != null) {
4902 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4903 }
4904 NetworkAgentInfo newDefaultAgent = null;
4905 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004906 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004907 if (newDefaultAgent != null) {
4908 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4909 newDefaultAgent.networkInfo);
4910 } else {
4911 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4912 }
4913 }
4914 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4915 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004916 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004917 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004918 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004919 }
4920 }
4921 }
4922
Robert Greenwalt7b816022014-04-18 15:25:25 -07004923 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004924 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004925 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004926 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4927 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4928 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004929 if (nri.mPendingIntent == null) {
4930 callCallbackForRequest(nri, networkAgent, notifyType);
4931 } else {
4932 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4933 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004934 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004935 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004936
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004937 private String notifyTypeToName(int notifyType) {
4938 switch (notifyType) {
4939 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4940 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4941 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4942 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4943 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4944 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4945 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4946 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4947 }
4948 return "UNKNOWN";
4949 }
4950
Jeff Sharkey69736342014-12-08 14:50:12 -08004951 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004952 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
4953 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08004954 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004955 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08004956 try {
4957 mStatsService.forceUpdateIfaces();
4958 } catch (Exception ignored) {
4959 }
4960 }
4961
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004962 @Override
4963 public boolean addVpnAddress(String address, int prefixLength) {
4964 throwIfLockdownEnabled();
4965 int user = UserHandle.getUserId(Binder.getCallingUid());
4966 synchronized (mVpns) {
4967 return mVpns.get(user).addAddress(address, prefixLength);
4968 }
4969 }
4970
4971 @Override
4972 public boolean removeVpnAddress(String address, int prefixLength) {
4973 throwIfLockdownEnabled();
4974 int user = UserHandle.getUserId(Binder.getCallingUid());
4975 synchronized (mVpns) {
4976 return mVpns.get(user).removeAddress(address, prefixLength);
4977 }
4978 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004979
4980 @Override
4981 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4982 throwIfLockdownEnabled();
4983 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004984 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004985 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004986 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004987 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004988 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004989 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004990 }
4991 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004992 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004993
4994 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08004995 public String getCaptivePortalServerUrl() {
4996 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
4997 }
4998
4999 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005000 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5001 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5002 enforceKeepalivePermission();
5003 mKeepaliveTracker.startNattKeepalive(
5004 getNetworkAgentInfoForNetwork(network),
5005 intervalSeconds, messenger, binder,
5006 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5007 }
5008
5009 @Override
5010 public void stopKeepalive(Network network, int slot) {
5011 mHandler.sendMessage(mHandler.obtainMessage(
5012 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5013 }
5014
5015 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005016 public void factoryReset() {
5017 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005018
5019 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5020 return;
5021 }
5022
Robin Lee3b3dd942015-05-12 18:14:58 +01005023 final int userId = UserHandle.getCallingUserId();
5024
Stuart Scottf1fb3972015-04-02 18:00:02 -07005025 // Turn airplane mode off
5026 setAirplaneMode(false);
5027
Stuart Scotte3e314d2015-04-20 14:07:45 -07005028 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5029 // Untether
5030 for (String tether : getTetheredIfaces()) {
5031 untether(tether);
5032 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005033 }
5034
Stuart Scotte3e314d2015-04-20 14:07:45 -07005035 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
5036 // Turn VPN off
5037 VpnConfig vpnConfig = getVpnConfig(userId);
5038 if (vpnConfig != null) {
5039 if (vpnConfig.legacy) {
5040 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5041 } else {
5042 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5043 // in the future without user intervention.
5044 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005045
Stuart Scotte3e314d2015-04-20 14:07:45 -07005046 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
5047 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005048 }
5049 }
5050 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005051
5052 @VisibleForTesting
5053 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5054 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5055 return new NetworkMonitor(context, handler, nai, defaultRequest);
5056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005057}