blob: 0e752ffdb5a589cf5a146e8f1e7779894be4bc25 [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 Colittif0e9a332016-07-18 18:40:42 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090028import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070032import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060033import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070034import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Leme781ba142016-05-09 16:24:48 -070035import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070036import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060037import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070038import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060039
Wenchao Tongf5ea3402015-03-04 13:26:38 -080040import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080041import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090042import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070043import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070044import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.ContentResolver;
46import android.content.Context;
47import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070048import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070050import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090051import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070052import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090054import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070056import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070057import android.net.INetworkPolicyListener;
58import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070059import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080060import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070061import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070062import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070063import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070064import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070065import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070067import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070068import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070069import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070070import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070071import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070072import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070073import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040074import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070075import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040076import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040077import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090078import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090079import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090080import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090081import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080083import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070084import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040085import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070087import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070088import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070089import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.os.Looper;
91import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070092import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070093import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070094import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070095import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070096import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080097import android.os.ResultReceiver;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090098import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700100import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400101import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700103import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700104import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700105import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700106import android.text.TextUtils;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600107import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700108import android.util.LocalLog;
109import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600110import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700111import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800112import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700113import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500114import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700115import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700116import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117
Wink Savilleab9321d2013-06-29 21:10:57 -0700118import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400119import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400120import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700121import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700122import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700123import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700124import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800125import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700126import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700127import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600128import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700129import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900130import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900131import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700132import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700133import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400134import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900135import com.android.server.connectivity.KeepaliveTracker;
Christopher Wiley497c1472016-10-11 13:26:03 -0700136import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900137import com.android.server.connectivity.Nat464Xlat;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900138import com.android.server.connectivity.LingerMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700139import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600140import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400141import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900142import com.android.server.connectivity.NetworkNotificationManager;
143import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400144import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700145import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800146import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700147import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700148import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700149import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600150
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700151import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700152
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700153import org.xmlpull.v1.XmlPullParser;
154import org.xmlpull.v1.XmlPullParserException;
155
156import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700158import java.io.FileNotFoundException;
159import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700160import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700162import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700163import java.net.InetAddress;
164import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700165import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700166import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700167import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700168import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700169import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700170import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700171import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700172import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700173import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600174import java.util.SortedSet;
175import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176
177/**
178 * @hide
179 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800180public class ConnectivityService extends IConnectivityManager.Stub
181 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900182 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900184 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700185 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186
Jake Hamby786e71a2014-02-06 14:43:50 -0800187 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900188 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700189
Jeff Sharkey899223b2012-08-04 15:24:58 -0700190 // TODO: create better separation between radio types and network types
191
Robert Greenwalt42acef32009-08-12 16:08:25 -0700192 // how long to wait before switching back to a radio's default network
193 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
194 // system property that can override the above value
195 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
196 "android.telephony.apn-restore";
197
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900198 // How long to wait before putting up a "This network doesn't have an Internet connection,
199 // connect anyway?" dialog after the user selects a network that doesn't validate.
200 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
201
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900202 // Default to 30s linger time-out. Modifiable only for testing.
203 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
204 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
205 @VisibleForTesting
206 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
207
Jeremy Joslin79294842014-12-03 17:15:28 -0800208 // How long to delay to removal of a pending intent based request.
209 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
210 private final int mReleasePendingIntentDelayMs;
211
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800212 private Tethering mTethering;
213
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700214 private final PermissionMonitor mPermissionMonitor;
215
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700216 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700217
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700218 @GuardedBy("mVpns")
219 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700220
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700221 private boolean mLockdownEnabled;
222 private LockdownVpnTracker mLockdownTracker;
223
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700224 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
225 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700226 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600227 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700228 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700229 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600230 @GuardedBy("mRulesLock")
231 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
232 /** Flag indicating if background data is restricted. */
233 @GuardedBy("mRulesLock")
234 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700235
Erik Klineda4bfa82015-04-30 12:58:40 +0900236 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700238 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700239 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800241 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242
243 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700244 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700246 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800247 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700248 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700249
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700250 private String mCurrentTcpBufferSizes;
251
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700252 private static final int ENABLED = 1;
253 private static final int DISABLED = 0;
254
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900255 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900256 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
257 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900258
Paul Jensenb10e37f2014-11-25 12:33:08 -0500259 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400260 // Tear down networks that have no chance (e.g. even if validated) of becoming
261 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500262 // all networks have been rematched against all NetworkRequests.
263 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400264 // Don't reap networks. This should be passed when some networks have not yet been
265 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500266 DONT_REAP
267 };
268
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900269 private enum UnneededFor {
270 LINGER, // Determine whether this network is unneeded and should be lingered.
271 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
272 }
273
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700274 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700275 * used internally to change our mobile data enabled flag
276 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700277 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700278
279 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700280 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700281 * from one net to another. Clear happens when we get a new
282 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
283 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700284 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700285 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700286
Robert Greenwalt434203a2010-10-11 16:00:27 -0700287 /**
288 * used internally to reload global proxy settings
289 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700290 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700291
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700292 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400293 * PAC manager has received new port.
294 */
295 private static final int EVENT_PROXY_HAS_CHANGED = 16;
296
Robert Greenwalte049c232014-04-11 15:53:27 -0700297 /**
298 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700299 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700300 */
301 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
302
Robert Greenwalt7b816022014-04-18 15:25:25 -0700303 /**
304 * used internally when registering NetworkAgents
305 * obj = Messenger
306 */
307 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
308
Robert Greenwalt9258c642014-03-26 16:47:06 -0700309 /**
310 * used to add a network request
311 * includes a NetworkRequestInfo
312 */
313 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
314
315 /**
316 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900317 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700318 * cancel it.
319 * includes a NetworkRequestInfo
320 */
321 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
322
323 /**
324 * used to add a network listener - no request
325 * includes a NetworkRequestInfo
326 */
327 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
328
329 /**
330 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400331 * arg1 = UID of caller
332 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700333 */
334 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
335
Robert Greenwalta67be032014-05-16 15:49:14 -0700336 /**
337 * used internally when registering NetworkFactories
338 * obj = Messenger
339 */
340 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
341
Robert Greenwalt27711812014-06-25 16:45:57 -0700342 /**
343 * used internally to expire a wakelock when transitioning
344 * from one net to another. Expire happens when we fail to find
345 * a new network (typically after 1 minute) -
346 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
347 * a replacement network.
348 */
349 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
350
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700351 /**
352 * Used internally to indicate the system is ready.
353 */
354 private static final int EVENT_SYSTEM_READY = 25;
355
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800356 /**
357 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400358 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800359 */
360 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
361
362 /**
363 * used to remove a pending intent and its associated network request.
364 * arg1 = UID of caller
365 * obj = PendingIntent
366 */
367 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
368
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900369 /**
370 * used to specify whether a network should be used even if unvalidated.
371 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
372 * arg2 = whether to remember this choice in the future (1 or 0)
373 * obj = network
374 */
375 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
376
377 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900378 * used to specify whether a network should not be penalized when it becomes unvalidated.
379 */
380 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
381
382 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900383 * used to ask the user to confirm a connection to an unvalidated network.
384 * obj = network
385 */
386 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700387
Erik Klineda4bfa82015-04-30 12:58:40 +0900388 /**
389 * used internally to (re)configure mobile data always-on settings.
390 */
391 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
392
Paul Jensen694f2b82015-06-17 14:15:39 -0400393 /**
394 * used to add a network listener with a pending intent
395 * obj = NetworkRequestInfo
396 */
397 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
398
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900399 /** Handler thread used for both of the handlers below. */
400 @VisibleForTesting
401 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700402 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700403 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700404 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700405 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700406
Mike Lockwood0f79b542009-08-14 14:18:49 -0400407 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800408 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400409
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700410 private PowerManager.WakeLock mNetTransitionWakeLock;
411 private String mNetTransitionWakeLockCausedBy = "";
412 private int mNetTransitionWakeLockSerialNumber;
413 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800414 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700415
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700416 // used in DBG mode to track inet condition reports
417 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
418 private ArrayList mInetLog;
419
Robert Greenwalt434203a2010-10-11 16:00:27 -0700420 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400421 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700422 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700423 private boolean mDefaultProxyDisabled = false;
424
Robert Greenwalt434203a2010-10-11 16:00:27 -0700425 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400426 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700427
Jason Monk602b2322013-07-03 17:04:33 -0400428 private PacManager mPacManager = null;
429
Erik Klineda4bfa82015-04-30 12:58:40 +0900430 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700431
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400432 private UserManager mUserManager;
433
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700434 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700435 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700436
Robert Greenwalt50393202011-06-21 17:26:14 -0700437 // the set of network types that can only be enabled by system/sig apps
438 List mProtectedNetworks;
439
John Spurlockbf991a82013-06-24 14:20:23 -0400440 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700441
Wink Savilleab9321d2013-06-29 21:10:57 -0700442 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400443
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900444 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900445 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900446 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900447
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700448 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
449 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700450 private final static int MAX_NET_ID = 65535;
451 private int mNextNetId = MIN_NET_ID;
452
Robert Greenwalt34524f02014-05-18 16:22:10 -0700453 // sequence number of NetworkRequests
454 private int mNextNetworkRequestId = 1;
455
Erik Kline7523eb32015-07-09 18:24:03 +0900456 // NetworkRequest activity String log entries.
457 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
458 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
459
Hugo Benichic2ae2872016-07-11 11:05:12 +0900460 // NetworkInfo blocked and unblocked String log entries
461 // TODO: consider reducing memory usage. Each log line is ~40 2B chars, for a total of ~8kB.
462 private static final int MAX_NETWORK_INFO_LOGS = 100;
463 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
464
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700465 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
466 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400467 private static class ValidationLog {
468 final Network mNetwork;
469 final String mNetworkExtraInfo;
470 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700471
Paul Jensen0808eb82016-06-03 13:51:21 -0400472 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
473 mNetwork = network;
474 mNetworkExtraInfo = networkExtraInfo;
475 mLog = log;
476 }
477 }
478 private final ArrayDeque<ValidationLog> mValidationLogs =
479 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
480
481 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700482 synchronized(mValidationLogs) {
483 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
484 mValidationLogs.removeLast();
485 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400486 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700487 }
488 }
489
Hugo Benichif9fdf872016-07-28 17:53:06 +0900490 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900491
Erik Kline065ab6e2016-10-02 18:02:14 +0900492 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900493 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900494
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700495 /**
496 * Implements support for the legacy "one network per network type" model.
497 *
498 * We used to have a static array of NetworkStateTrackers, one for each
499 * network type, but that doesn't work any more now that we can have,
500 * for example, more that one wifi network. This class stores all the
501 * NetworkAgentInfo objects that support a given type, but the legacy
502 * API will only see the first one.
503 *
504 * It serves two main purposes:
505 *
506 * 1. Provide information about "the network for a given type" (since this
507 * API only supports one).
508 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
509 * the first network for a given type changes, or if the default network
510 * changes.
511 */
512 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900513
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900514 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900515 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900516
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700517 /**
518 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
519 * Each list holds references to all NetworkAgentInfos that are used to
520 * satisfy requests for that network type.
521 *
522 * This array is built out at startup such that an unsupported network
523 * doesn't get an ArrayList instance, making this a tristate:
524 * unsupported, supported but not active and active.
525 *
526 * The actual lists are populated when we scan the network types that
527 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900528 *
529 * Threading model:
530 * - addSupportedType() is only called in the constructor
531 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
532 * They are therefore not thread-safe with respect to each other.
533 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
534 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
535 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700536 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900537 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700538
539 public LegacyTypeTracker() {
540 mTypeLists = (ArrayList<NetworkAgentInfo>[])
541 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
542 }
543
544 public void addSupportedType(int type) {
545 if (mTypeLists[type] != null) {
546 throw new IllegalStateException(
547 "legacy list for type " + type + "already initialized");
548 }
549 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
550 }
551
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700552 public boolean isTypeSupported(int type) {
553 return isNetworkTypeValid(type) && mTypeLists[type] != null;
554 }
555
556 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900557 synchronized (mTypeLists) {
558 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
559 return mTypeLists[type].get(0);
560 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900562 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700563 }
564
Robert Greenwalt8d482522015-06-24 13:23:42 -0700565 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900566 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900567 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700568 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900569 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900570 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900571 }
572 }
573
574 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700575 public void add(int type, NetworkAgentInfo nai) {
576 if (!isTypeSupported(type)) {
577 return; // Invalid network type.
578 }
579 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
580
581 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
582 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700583 return;
584 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900585 synchronized (mTypeLists) {
586 list.add(nai);
587 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900588
589 // 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 +0900590 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900591 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700592 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
593 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700594 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700595 }
596
Lorenzo Colittia793a672014-07-31 23:20:17 +0900597 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900598 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900599 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
600 if (list == null || list.isEmpty()) {
601 return;
602 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900603 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900604
Hugo Benichi78caa2582016-06-21 09:48:07 +0900605 synchronized (mTypeLists) {
606 if (!list.remove(nai)) {
607 return;
608 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900609 }
610
Robert Greenwalt8d482522015-06-24 13:23:42 -0700611 final DetailedState state = DetailedState.DISCONNECTED;
612
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900613 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700614 maybeLogBroadcast(nai, state, type, wasDefault);
615 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900616 }
617
618 if (!list.isEmpty() && wasFirstNetwork) {
619 if (DBG) log("Other network available for type " + type +
620 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900621 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700622 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
623 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900624 }
625 }
626
627 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900628 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
629 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700630 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900631 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700632 }
633 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700634
Robert Greenwalt8d482522015-06-24 13:23:42 -0700635 // send out another legacy broadcast - currently only used for suspend/unsuspend
636 // toggle
637 public void update(NetworkAgentInfo nai) {
638 final boolean isDefault = isDefaultNetwork(nai);
639 final DetailedState state = nai.networkInfo.getDetailedState();
640 for (int type = 0; type < mTypeLists.length; type++) {
641 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700642 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900643 final boolean isFirst = contains && (nai == list.get(0));
644 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700645 maybeLogBroadcast(nai, state, type, isDefault);
646 sendLegacyNetworkBroadcast(nai, state, type);
647 }
648 }
649 }
650
Lorenzo Colittia793a672014-07-31 23:20:17 +0900651 private String naiToString(NetworkAgentInfo nai) {
652 String name = (nai != null) ? nai.name() : "null";
653 String state = (nai.networkInfo != null) ?
654 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
655 "???/???";
656 return name + " " + state;
657 }
658
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700659 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900660 pw.println("mLegacyTypeTracker:");
661 pw.increaseIndent();
662 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700663 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900664 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700665 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900666 pw.println();
667 pw.println("Current state:");
668 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900669 synchronized (mTypeLists) {
670 for (int type = 0; type < mTypeLists.length; type++) {
671 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
672 for (NetworkAgentInfo nai : mTypeLists[type]) {
673 pw.println(type + " " + naiToString(nai));
674 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900675 }
676 }
677 pw.decreaseIndent();
678 pw.decreaseIndent();
679 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700680 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700681 }
682 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
683
Jeff Sharkey899223b2012-08-04 15:24:58 -0700684 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700685 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900686 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
687 }
688
689 @VisibleForTesting
690 protected ConnectivityService(Context context, INetworkManagementService netManager,
691 INetworkStatsService statsService, INetworkPolicyManager policyManager,
692 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800693 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800694
Hugo Benichif9fdf872016-07-28 17:53:06 +0900695 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900696 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900697 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900698 mNetworkRequests.put(mDefaultRequest, defaultNRI);
699 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900700
701 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900702 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700703
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900704 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900705 mHandlerThread.start();
706 mHandler = new InternalHandler(mHandlerThread.getLooper());
707 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700708
Jeremy Joslin79294842014-12-03 17:15:28 -0800709 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
710 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
711
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900712 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
713
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700714 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700715 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800716 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700717 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700718 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700719 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700720
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700721 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600722 mPolicyManager.setConnectivityListener(mPolicyListener);
723 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700724 } catch (RemoteException e) {
725 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700726 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700727 }
728
729 final PowerManager powerManager = (PowerManager) context.getSystemService(
730 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700731 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
732 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
733 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800734 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700735
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700736 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700737
Wink Saville51f456f2013-04-23 14:26:51 -0700738 // TODO: What is the "correct" way to do determine if this is a wifi only device?
739 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
740 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700741 String[] naStrings = context.getResources().getStringArray(
742 com.android.internal.R.array.networkAttributes);
743 for (String naString : naStrings) {
744 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700745 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700746 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700747 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800748 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700749 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700750 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700751 }
Wink Saville51f456f2013-04-23 14:26:51 -0700752 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
753 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
754 n.type);
755 continue;
756 }
Wink Saville975c8482011-04-07 14:23:45 -0700757 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800758 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700759 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700760 continue;
761 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700762 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700763
Wink Saville975c8482011-04-07 14:23:45 -0700764 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700765 mNetworksDefined++;
766 } catch(Exception e) {
767 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700768 }
769 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700770
771 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
772 if (mNetConfigs[TYPE_VPN] == null) {
773 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
774 // don't need to add TYPE_VPN to mNetConfigs.
775 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
776 mNetworksDefined++; // used only in the log() statement below.
777 }
778
Wink Saville5e56bc52013-07-29 15:00:57 -0700779 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700780
Robert Greenwalt50393202011-06-21 17:26:14 -0700781 mProtectedNetworks = new ArrayList<Integer>();
782 int[] protectedNetworks = context.getResources().getIntArray(
783 com.android.internal.R.array.config_protectedNetworks);
784 for (int p : protectedNetworks) {
785 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
786 mProtectedNetworks.add(p);
787 } else {
788 if (DBG) loge("Ignoring protectedNetwork " + p);
789 }
790 }
791
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700792 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
793 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700794
Christopher Wiley497c1472016-10-11 13:26:03 -0700795 mTethering = new Tethering(mContext, mNetd, statsService, mPolicyManager,
796 IoThread.get().getLooper(), new MockableSystemProperties());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800797
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700798 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
799
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700800 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700801 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100802 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700803 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700804 intentFilter.addAction(Intent.ACTION_USER_ADDED);
805 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000806 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700807 mContext.registerReceiverAsUser(
808 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000809 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
810 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900811
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700812 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700813 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700814 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700815 } catch (RemoteException e) {
816 loge("Error registering observer :" + e);
817 }
818
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700819 if (DBG) {
820 mInetLog = new ArrayList();
821 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700822
Erik Klineda4bfa82015-04-30 12:58:40 +0900823 mSettingsObserver = new SettingsObserver(mContext, mHandler);
824 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800825
John Spurlockbf991a82013-06-24 14:20:23 -0400826 mDataConnectionStats = new DataConnectionStats(mContext);
827 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400828
Jason Monkdecd2952013-10-10 14:02:51 -0400829 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700830
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400831 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900832
833 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900834 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
835 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900836
837 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
838 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
839 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
840 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
841 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
842 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
843 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900844
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900845 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900846 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900847 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700849
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900850 private NetworkRequest createInternetRequestForTransport(
851 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900852 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900853 netCap.addCapability(NET_CAPABILITY_INTERNET);
854 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900855 if (transportType > -1) {
856 netCap.addTransportType(transportType);
857 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900858 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900859 }
860
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900861 // Used only for testing.
862 // TODO: Delete this and either:
863 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
864 // changing ContentResolver to make registerContentObserver non-final).
865 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
866 // by subclassing SettingsObserver.
867 @VisibleForTesting
868 void updateMobileDataAlwaysOn() {
869 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
870 }
871
Erik Klineda4bfa82015-04-30 12:58:40 +0900872 private void handleMobileDataAlwaysOn() {
873 final boolean enable = (Settings.Global.getInt(
Lorenzo Colitti5d6bf6d2017-01-17 11:07:10 +0900874 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1) == 1);
Erik Klineda4bfa82015-04-30 12:58:40 +0900875 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
876 if (enable == isEnabled) {
877 return; // Nothing to do.
878 }
879
880 if (enable) {
881 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900882 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900883 } else {
884 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
885 }
886 }
887
888 private void registerSettingsCallbacks() {
889 // Watch for global HTTP proxy changes.
890 mSettingsObserver.observe(
891 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
892 EVENT_APPLY_GLOBAL_HTTP_PROXY);
893
894 // Watch for whether or not to keep mobile data always on.
895 mSettingsObserver.observe(
896 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
897 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
898 }
899
Robert Greenwalt34524f02014-05-18 16:22:10 -0700900 private synchronized int nextNetworkRequestId() {
901 return mNextNetworkRequestId++;
902 }
903
Paul Jensen67b0b072015-06-10 11:22:17 -0400904 @VisibleForTesting
905 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400906 synchronized (mNetworkForNetId) {
907 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
908 int netId = mNextNetId;
909 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
910 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500911 if (!mNetIdInUse.get(netId)) {
912 mNetIdInUse.put(netId, true);
913 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400914 }
915 }
916 }
917 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700918 }
919
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600920 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800921 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600922 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
923 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800924 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600925 state = nai.getNetworkState();
926 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800927 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600928 final NetworkInfo info = new NetworkInfo(networkType, 0,
929 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800930 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
931 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600932 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
933 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800934 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600935 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600936 return state;
937 } else {
938 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800939 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400940 }
941
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800942 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
943 if (network == null) {
944 return null;
945 }
946 synchronized (mNetworkForNetId) {
947 return mNetworkForNetId.get(network.netId);
948 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600949 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800950
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900951 private Network[] getVpnUnderlyingNetworks(int uid) {
952 if (!mLockdownEnabled) {
953 int user = UserHandle.getUserId(uid);
954 synchronized (mVpns) {
955 Vpn vpn = mVpns.get(user);
956 if (vpn != null && vpn.appliesToUid(uid)) {
957 return vpn.getUnderlyingNetworks();
958 }
959 }
960 }
961 return null;
962 }
963
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800964 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400965 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800966
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900967 final Network[] networks = getVpnUnderlyingNetworks(uid);
968 if (networks != null) {
969 // getUnderlyingNetworks() returns:
970 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
971 // empty array => the VPN explicitly said "no default network".
972 // non-empty array => the VPN specified one or more default networks; we use the
973 // first one.
974 if (networks.length > 0) {
975 nai = getNetworkAgentInfoForNetwork(networks[0]);
976 } else {
977 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800978 }
979 }
980
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800981 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600982 return nai.getNetworkState();
983 } else {
984 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800985 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400986 }
987
988 /**
989 * Check if UID should be blocked from using the network with the given LinkProperties.
990 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600991 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
992 boolean ignoreBlocked) {
993 // Networks aren't blocked when ignoring blocked status
994 if (ignoreBlocked) return false;
995 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -0700996 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600997
998 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700999 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -07001000
Robin Lee17e61832016-05-09 13:46:28 +01001001 synchronized (mVpns) {
1002 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1003 if (vpn != null && vpn.isBlockingUid(uid)) {
1004 return true;
1005 }
1006 }
1007
Robert Greenwalt12e67352014-05-13 21:41:06 -07001008 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001009 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001010 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001011 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001012 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001013
Felipe Lemed31a97f2016-05-06 14:53:50 -07001014 boolean allowed = true;
1015 // Check Data Saver Mode first...
1016 if (networkMetered) {
1017 if ((uidRules & RULE_REJECT_METERED) != 0) {
1018 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1019 // Explicitly blacklisted.
1020 allowed = false;
1021 } else {
1022 allowed = !mRestrictBackground
1023 || (uidRules & RULE_ALLOW_METERED) != 0
1024 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1025 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1026 + " mRestrictBackground=" + mRestrictBackground
1027 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1028 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1029 + ": " + allowed);
1030 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001031 }
Felipe Leme781ba142016-05-09 16:24:48 -07001032 // ...then power restrictions.
1033 if (allowed) {
1034 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001035 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001036 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001037 }
1038 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001039 }
1040
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001041 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001042 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1043 return;
1044 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001045 boolean removed = false;
1046 boolean added = false;
1047 synchronized (mBlockedAppUids) {
1048 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1049 added = true;
1050 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1051 removed = true;
1052 }
1053 }
Hugo Benichic2ae2872016-07-11 11:05:12 +09001054 if (added) {
1055 log("Returning blocked NetworkInfo to uid=" + uid);
1056 mNetworkInfoBlockingLogs.log("BLOCKED " + uid);
1057 } else if (removed) {
1058 log("Returning unblocked NetworkInfo to uid=" + uid);
1059 mNetworkInfoBlockingLogs.log("UNBLOCKED " + uid);
1060 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001061 }
1062
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001063 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001064 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1065 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1066 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1067 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001068 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001069 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001070 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1071
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001072 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001073 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001074 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001075 if (mLockdownTracker != null) {
1076 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001077 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001078
1079 // TODO: apply metered state closer to NetworkAgentInfo
1080 final long token = Binder.clearCallingIdentity();
1081 try {
1082 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1083 } catch (RemoteException e) {
1084 } finally {
1085 Binder.restoreCallingIdentity(token);
1086 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001087 }
1088
1089 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 * Return NetworkInfo for the active (i.e., connected) network interface.
1091 * It is assumed that at most one network is active at a time. If more
1092 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001093 * @return the info for the active network, or {@code null} if none is
1094 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001096 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001098 enforceAccessPermission();
1099 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001100 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001101 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001102 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1103 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 }
1105
Paul Jensen31a94f42015-02-13 14:18:39 -05001106 @Override
1107 public Network getActiveNetwork() {
1108 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001109 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001110 }
1111
1112 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001113 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001114 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001115 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001116 }
1117
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001118 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001119 final int user = UserHandle.getUserId(uid);
1120 int vpnNetId = NETID_UNSET;
1121 synchronized (mVpns) {
1122 final Vpn vpn = mVpns.get(user);
1123 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1124 }
1125 NetworkAgentInfo nai;
1126 if (vpnNetId != NETID_UNSET) {
1127 synchronized (mNetworkForNetId) {
1128 nai = mNetworkForNetId.get(vpnNetId);
1129 }
1130 if (nai != null) return nai.network;
1131 }
1132 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001133 if (nai != null
1134 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1135 nai = null;
1136 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001137 return nai != null ? nai.network : null;
1138 }
1139
Lorenzo Colitti18660282016-07-04 12:55:44 +09001140 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001141 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1142 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001143 final int uid = Binder.getCallingUid();
1144 NetworkState state = getUnfilteredActiveNetworkState(uid);
1145 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001146 }
1147
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001148 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001149 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001150 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001151 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001152 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001153 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001154 }
1155
1156 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 public NetworkInfo getNetworkInfo(int networkType) {
1158 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001159 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001160 if (getVpnUnderlyingNetworks(uid) != null) {
1161 // A VPN is active, so we may need to return one of its underlying networks. This
1162 // information is not available in LegacyTypeTracker, so we have to get it from
1163 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001164 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001165 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001166 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001167 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001168 }
1169 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001170 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001171 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 }
1173
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001174 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001175 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001176 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001177 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001178 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001179 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001180 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001181 return state.networkInfo;
1182 } else {
1183 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001184 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001185 }
1186
1187 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 public NetworkInfo[] getAllNetworkInfo() {
1189 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001190 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001191 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1192 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001193 NetworkInfo info = getNetworkInfo(networkType);
1194 if (info != null) {
1195 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001198 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 }
1200
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001201 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001202 public Network getNetworkForType(int networkType) {
1203 enforceAccessPermission();
1204 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001205 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1206 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001207 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001208 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001209 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001210 }
1211
1212 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001213 public Network[] getAllNetworks() {
1214 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001215 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001216 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001217 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001218 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001219 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001220 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001221 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001222 }
1223
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001224 @Override
1225 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1226 // The basic principle is: if an app's traffic could possibly go over a
1227 // network, without the app doing anything multinetwork-specific,
1228 // (hence, by "default"), then include that network's capabilities in
1229 // the array.
1230 //
1231 // In the normal case, app traffic only goes over the system's default
1232 // network connection, so that's the only network returned.
1233 //
1234 // With a VPN in force, some app traffic may go into the VPN, and thus
1235 // over whatever underlying networks the VPN specifies, while other app
1236 // traffic may go over the system default network (e.g.: a split-tunnel
1237 // VPN, or an app disallowed by the VPN), so the set of networks
1238 // returned includes the VPN's underlying networks and the system
1239 // default.
1240 enforceAccessPermission();
1241
1242 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1243
1244 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001245 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001246 if (nc != null) {
1247 result.put(nai.network, nc);
1248 }
1249
1250 if (!mLockdownEnabled) {
1251 synchronized (mVpns) {
1252 Vpn vpn = mVpns.get(userId);
1253 if (vpn != null) {
1254 Network[] networks = vpn.getUnderlyingNetworks();
1255 if (networks != null) {
1256 for (Network network : networks) {
1257 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001258 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001259 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001260 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001261 }
1262 }
1263 }
1264 }
1265 }
1266 }
1267
1268 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1269 out = result.values().toArray(out);
1270 return out;
1271 }
1272
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001273 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001274 public boolean isNetworkSupported(int networkType) {
1275 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001276 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001277 }
1278
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001279 /**
1280 * Return LinkProperties for the active (i.e., connected) default
1281 * network interface. It is assumed that at most one default network
1282 * is active at a time. If more than one is active, it is indeterminate
1283 * which will be returned.
1284 * @return the ip properties for the active network, or {@code null} if
1285 * none is active
1286 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001287 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001288 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001289 enforceAccessPermission();
1290 final int uid = Binder.getCallingUid();
1291 NetworkState state = getUnfilteredActiveNetworkState(uid);
1292 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001293 }
1294
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001295 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001296 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001297 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001298 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1299 if (nai != null) {
1300 synchronized (nai) {
1301 return new LinkProperties(nai.linkProperties);
1302 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001303 }
1304 return null;
1305 }
1306
Robert Greenwalt12e67352014-05-13 21:41:06 -07001307 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001308 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001309 public LinkProperties getLinkProperties(Network network) {
1310 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001311 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001312 if (nai != null) {
1313 synchronized (nai) {
1314 return new LinkProperties(nai.linkProperties);
1315 }
1316 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001317 return null;
1318 }
1319
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001320 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001321 if (nai != null) {
1322 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001323 if (nai.networkCapabilities != null) {
1324 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001325 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001326 }
1327 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001328 return null;
1329 }
1330
1331 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001332 public NetworkCapabilities getNetworkCapabilities(Network network) {
1333 enforceAccessPermission();
1334 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1335 }
1336
1337 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001338 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001339 // Require internal since we're handing out IMSI details
1340 enforceConnectivityInternalPermission();
1341
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001342 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001343 for (Network network : getAllNetworks()) {
1344 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1345 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001346 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001347 }
1348 }
1349 return result.toArray(new NetworkState[result.size()]);
1350 }
1351
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001352 @Override
1353 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1354 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001355 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001356 final long token = Binder.clearCallingIdentity();
1357 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001358 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1359 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001360 try {
1361 return mPolicyManager.getNetworkQuotaInfo(state);
1362 } catch (RemoteException e) {
1363 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001364 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001365 return null;
1366 } finally {
1367 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001368 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001369 }
1370
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001371 @Override
1372 public boolean isActiveNetworkMetered() {
1373 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001374
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001375 final NetworkInfo info = getActiveNetworkInfo();
1376 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001377 }
1378
Jeff Sharkey216c1812012-08-05 14:29:23 -07001379 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1380 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001381 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001382 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001383 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001384 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001385 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001386
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001387 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 * Ensure that a network route exists to deliver traffic to the specified
1389 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001390 * @param networkType the type of the network over which traffic to the
1391 * specified host is to be routed
1392 * @param hostAddress the IP address of the host to which the route is
1393 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 * @return {@code true} on success, {@code false} on failure
1395 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001396 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001397 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001399 if (mProtectedNetworks.contains(networkType)) {
1400 enforceConnectivityInternalPermission();
1401 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001402
Chad Brubakerc0234532014-02-14 13:24:29 -08001403 InetAddress addr;
1404 try {
1405 addr = InetAddress.getByAddress(hostAddress);
1406 } catch (UnknownHostException e) {
1407 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1408 return false;
1409 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001412 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 return false;
1414 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001415
1416 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1417 if (nai == null) {
1418 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1419 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1420 } else {
1421 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1422 }
1423 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001424 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001425
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001426 DetailedState netState;
1427 synchronized (nai) {
1428 netState = nai.networkInfo.getDetailedState();
1429 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001430
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001431 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001432 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001433 log("requestRouteToHostAddress on down network "
1434 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001435 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001436 }
1437 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001439
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001440 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001441 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001442 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001443 LinkProperties lp;
1444 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001445 synchronized (nai) {
1446 lp = nai.linkProperties;
1447 netId = nai.network.netId;
1448 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001449 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001450 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1451 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001452 } finally {
1453 Binder.restoreCallingIdentity(token);
1454 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001455 }
1456
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001457 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001458 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001459 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001460 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001461 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001462 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001463 if (bestRoute.getGateway().equals(addr)) {
1464 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001465 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001466 } else {
1467 // if we will connect to this through another route, add a direct route
1468 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001469 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001470 }
1471 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001472 if (DBG) log("Adding legacy route " + bestRoute +
1473 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001474 try {
1475 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1476 } catch (Exception e) {
1477 // never crash - catch them all
1478 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001479 return false;
1480 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001481 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 }
1483
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001484 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1485 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001486 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001487 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001488 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001489 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001490 }
1491
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001492 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001493 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001494 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001495 if (oldRules == uidRules) return;
1496
Felipe Leme781ba142016-05-09 16:24:48 -07001497 if (uidRules == RULE_NONE) {
1498 mUidRules.delete(uid);
1499 } else {
1500 mUidRules.put(uid, uidRules);
1501 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001502 }
1503
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001504 // TODO: notify UID when it has requested targeted updates
1505 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001506
1507 @Override
1508 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001509 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001510 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001511 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001512 }
1513
1514 synchronized (mRulesLock) {
1515 mMeteredIfaces.clear();
1516 for (String iface : meteredIfaces) {
1517 mMeteredIfaces.add(iface);
1518 }
1519 }
1520 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001521
1522 @Override
1523 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1524 // caller is NPMS, since we only register with them
1525 if (LOGD_RULES) {
1526 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1527 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001528
1529 synchronized (mRulesLock) {
1530 mRestrictBackground = restrictBackground;
1531 }
1532
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001533 if (restrictBackground) {
1534 log("onRestrictBackgroundChanged(true): disabling tethering");
1535 mTethering.untetherAll();
1536 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001537 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001538
1539 @Override
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001540 public void onUidPoliciesChanged(int uid, int uidPolicies) {
1541 // caller is NPMS, since we only register with them
Felipe Leme019fcd22016-04-19 10:24:39 -07001542 if (LOGD_RULES) {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001543 log("onUidRulesChanged(uid=" + uid + ", uidPolicies=" + uidPolicies + ")");
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001544 }
1545 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001546 };
1547
Robin Lee3b3dd942015-05-12 18:14:58 +01001548 /**
1549 * Require that the caller is either in the same user or has appropriate permission to interact
1550 * across users.
1551 *
1552 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1553 */
1554 private void enforceCrossUserPermission(int userId) {
1555 if (userId == UserHandle.getCallingUserId()) {
1556 // Not a cross-user call.
1557 return;
1558 }
1559 mContext.enforceCallingOrSelfPermission(
1560 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1561 "ConnectivityService");
1562 }
1563
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001564 private void enforceInternetPermission() {
1565 mContext.enforceCallingOrSelfPermission(
1566 android.Manifest.permission.INTERNET,
1567 "ConnectivityService");
1568 }
1569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001571 mContext.enforceCallingOrSelfPermission(
1572 android.Manifest.permission.ACCESS_NETWORK_STATE,
1573 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 }
1575
1576 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001577 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 }
1579
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001580 private void enforceTetherAccessPermission() {
1581 mContext.enforceCallingOrSelfPermission(
1582 android.Manifest.permission.ACCESS_NETWORK_STATE,
1583 "ConnectivityService");
1584 }
1585
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001586 private void enforceConnectivityInternalPermission() {
1587 mContext.enforceCallingOrSelfPermission(
1588 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1589 "ConnectivityService");
1590 }
1591
Hugo Benichi514da602016-07-19 15:59:27 +09001592 private void enforceConnectivityRestrictedNetworksPermission() {
1593 try {
1594 mContext.enforceCallingOrSelfPermission(
1595 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1596 "ConnectivityService");
1597 return;
1598 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1599 enforceConnectivityInternalPermission();
1600 }
1601
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001602 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001603 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001604 }
1605
Lorenzo Colitti18660282016-07-04 12:55:44 +09001606 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001607 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001608 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001609 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001610 }
1611
1612 private void sendInetConditionBroadcast(NetworkInfo info) {
1613 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1614 }
1615
Wink Saville628b0852011-08-04 15:01:58 -07001616 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001617 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001618 info = new NetworkInfo(info);
1619 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001620 }
1621
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001622 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001623 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001624 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 if (info.isFailover()) {
1626 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1627 info.setFailover(false);
1628 }
1629 if (info.getReason() != null) {
1630 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1631 }
1632 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001633 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1634 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001636 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001637 return intent;
1638 }
1639
1640 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1641 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1642 }
1643
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001644 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001645 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1646 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1647 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001648 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001649 final long ident = Binder.clearCallingIdentity();
1650 try {
1651 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1652 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1653 } finally {
1654 Binder.restoreCallingIdentity(ident);
1655 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001656 }
1657
Mike Lockwood0f79b542009-08-14 14:18:49 -04001658 private void sendStickyBroadcast(Intent intent) {
1659 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001660 if (!mSystemReady) {
1661 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001662 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001663 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001664 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001665 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001666 }
1667
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001668 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001669 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001670 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001671 final NetworkInfo ni = intent.getParcelableExtra(
1672 ConnectivityManager.EXTRA_NETWORK_INFO);
1673 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1674 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1675 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001676 } else {
1677 BroadcastOptions opts = BroadcastOptions.makeBasic();
1678 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1679 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001680 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001681 final IBatteryStats bs = BatteryStatsService.getService();
1682 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001683 bs.noteConnectivityChanged(intent.getIntExtra(
1684 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1685 ni != null ? ni.getState().toString() : "?");
1686 } catch (RemoteException e) {
1687 }
1688 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001689 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001690 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001691 } finally {
1692 Binder.restoreCallingIdentity(ident);
1693 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001694 }
1695 }
1696
1697 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001698 loadGlobalProxy();
1699
Mike Lockwood0f79b542009-08-14 14:18:49 -04001700 synchronized(this) {
1701 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001702 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001703 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001704 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001705 }
1706 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001707 // load the global proxy at startup
1708 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001709
Robin Lee244ce8e2016-01-05 18:03:46 +00001710 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1711 // for user to unlock device too.
1712 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001713
Erik Klineda4bfa82015-04-30 12:58:40 +09001714 // Configure whether mobile data is always on.
1715 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1716
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001717 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001718
1719 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 }
1721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001723 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001724 *
1725 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001726 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001727 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001728 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1729 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001730
1731 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001732 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001733
Robert Greenwalt7b816022014-04-18 15:25:25 -07001734 if (networkAgent.networkCapabilities.hasTransport(
1735 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001736 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1737 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001738 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001739 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001740 } else if (networkAgent.networkCapabilities.hasTransport(
1741 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001742 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1743 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001744 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001745 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001746 } else {
1747 // do not track any other networks
1748 timeout = 0;
1749 }
1750
Robert Greenwalt7b816022014-04-18 15:25:25 -07001751 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001752 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001753 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001754 } catch (Exception e) {
1755 // You shall not crash!
1756 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001757 }
1758 }
1759 }
1760
1761 /**
1762 * Remove data activity tracking when network disconnects.
1763 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001764 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1765 final String iface = networkAgent.linkProperties.getInterfaceName();
1766 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001767
Robert Greenwalt7b816022014-04-18 15:25:25 -07001768 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1769 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001770 try {
1771 // the call fails silently if no idletimer setup for this interface
1772 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001773 } catch (Exception e) {
1774 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001775 }
1776 }
1777 }
1778
1779 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001780 * Reads the network specific MTU size from reources.
1781 * and set it on it's iface.
1782 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001783 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1784 final String iface = newLp.getInterfaceName();
1785 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001786 if (oldLp == null && mtu == 0) {
1787 // Silently ignore unset MTU value.
1788 return;
1789 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001790 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1791 if (VDBG) log("identical MTU - not setting");
1792 return;
1793 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001794 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001795 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001796 return;
1797 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001798
w1997615afd812014-08-05 15:18:11 -07001799 // Cannot set MTU without interface name
1800 if (TextUtils.isEmpty(iface)) {
1801 loge("Setting MTU size with null iface.");
1802 return;
1803 }
1804
Robert Greenwalt7b816022014-04-18 15:25:25 -07001805 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001806 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001807 mNetd.setMtu(iface, mtu);
1808 } catch (Exception e) {
1809 Slog.e(TAG, "exception in setMtu()" + e);
1810 }
1811 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001812
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001813 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001814 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1815
1816 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001817 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001818 protected int getDefaultTcpRwnd() {
1819 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1820 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001821
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001822 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1823 if (isDefaultNetwork(nai) == false) {
1824 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001825 }
1826
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001827 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1828 String[] values = null;
1829 if (tcpBufferSizes != null) {
1830 values = tcpBufferSizes.split(",");
1831 }
1832
1833 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001834 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001835 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1836 values = tcpBufferSizes.split(",");
1837 }
1838
1839 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1840
1841 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001842 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001843
1844 final String prefix = "/sys/kernel/ipv4/tcp_";
1845 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1846 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1847 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1848 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1849 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1850 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1851 mCurrentTcpBufferSizes = tcpBufferSizes;
1852 } catch (IOException e) {
1853 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001854 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001855
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001856 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001857 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001858 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1859 if (rwndValue != 0) {
1860 SystemProperties.set(sysctlKey, rwndValue.toString());
1861 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001862 }
1863
Mattias Falk8b47b362011-08-23 14:15:13 +02001864 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001865 /*
1866 * Tell the VMs to toss their DNS caches
1867 */
1868 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1869 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001870 /*
1871 * Connectivity events can happen before boot has completed ...
1872 */
1873 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001874 final long ident = Binder.clearCallingIdentity();
1875 try {
1876 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1877 } finally {
1878 Binder.restoreCallingIdentity(ident);
1879 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001880 }
1881
Robert Greenwalt562cc542014-05-15 18:07:26 -07001882 @Override
1883 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001884 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1885 NETWORK_RESTORE_DELAY_PROP_NAME);
1886 if(restoreDefaultNetworkDelayStr != null &&
1887 restoreDefaultNetworkDelayStr.length() != 0) {
1888 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001889 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001890 } catch (NumberFormatException e) {
1891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001893 // if the system property isn't set, use the value for the apn type
1894 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1895
1896 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1897 (mNetConfigs[networkType] != null)) {
1898 ret = mNetConfigs[networkType].restoreTime;
1899 }
1900 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 }
1902
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001903 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001904 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001905 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001906 }
1907 return false;
1908 }
1909
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001910 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1911 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1912 final long DIAG_TIME_MS = 5000;
1913 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1914 // Start gathering diagnostic information.
1915 netDiags.add(new NetworkDiagnostics(
1916 nai.network,
1917 new LinkProperties(nai.linkProperties), // Must be a copy.
1918 DIAG_TIME_MS));
1919 }
1920
1921 for (NetworkDiagnostics netDiag : netDiags) {
1922 pw.println();
1923 netDiag.waitForMeasurements();
1924 netDiag.dump(pw);
1925 }
1926 }
1927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001929 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1930 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001931 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001932
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001933 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001934 dumpNetworkDiagnostics(pw);
1935 return;
1936 }
Erik Kline379747a2015-06-05 17:47:34 +09001937
Lorenzo Colittie3805462015-06-03 11:18:24 +09001938 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001939 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001940 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001941 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001942 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001943 pw.println();
1944
Paul Jensen85cf78e2015-06-25 13:25:07 -04001945 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001946 pw.print("Active default network: ");
1947 if (defaultNai == null) {
1948 pw.println("none");
1949 } else {
1950 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001952 pw.println();
1953
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001954 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001955 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001956 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1957 pw.println(nai.toString());
1958 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001959 pw.println(String.format(
1960 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1961 nai.numForegroundNetworkRequests(),
1962 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1963 nai.numBackgroundNetworkRequests(),
1964 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001965 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001966 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1967 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001968 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001969 pw.decreaseIndent();
1970 pw.println("Lingered:");
1971 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001972 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001973 pw.decreaseIndent();
1974 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001975 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001976 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001977 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001978
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001979 pw.println("Metered Interfaces:");
1980 pw.increaseIndent();
1981 for (String value : mMeteredIfaces) {
1982 pw.println(value);
1983 }
1984 pw.decreaseIndent();
1985 pw.println();
1986
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001987 pw.print("Restrict background: ");
1988 pw.println(mRestrictBackground);
1989 pw.println();
1990
Felipe Leme46c4fc32016-05-04 09:21:43 -07001991 pw.println("Status for known UIDs:");
1992 pw.increaseIndent();
1993 final int size = mUidRules.size();
1994 for (int i = 0; i < size; i++) {
1995 final int uid = mUidRules.keyAt(i);
1996 pw.print("UID=");
1997 pw.print(uid);
1998 final int uidRules = mUidRules.get(uid, RULE_NONE);
1999 pw.print(" rules=");
2000 pw.print(uidRulesToString(uidRules));
2001 pw.println();
2002 }
2003 pw.println();
2004 pw.decreaseIndent();
2005
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002006 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002007 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002008 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2009 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002010 }
2011 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002012 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002013
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002014 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002015
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002016 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002017 pw.print("mNetTransitionWakeLock: currently " +
2018 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
2019 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
2020 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
2021 } else {
2022 pw.println(", last requested never");
2023 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002024 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002025
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002026 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002027 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002028
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002029 pw.println();
2030 mKeepaliveTracker.dump(pw);
2031
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002032 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002033 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002034
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002035 pw.println();
Lorenzo Colittie3805462015-06-03 11:18:24 +09002036 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002037 pw.println();
2038 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002039 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002040 for(int i = 0; i < mInetLog.size(); i++) {
2041 pw.println(mInetLog.get(i));
2042 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002043 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002044 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002045
2046 if (argsContain(args, "--short") == false) {
2047 pw.println();
2048 synchronized (mValidationLogs) {
2049 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002050 for (ValidationLog p : mValidationLogs) {
2051 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002052 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002053 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002054 pw.decreaseIndent();
2055 }
2056 }
Erik Kline7523eb32015-07-09 18:24:03 +09002057
2058 pw.println();
2059 pw.println("mNetworkRequestInfoLogs (most recent first):");
2060 pw.increaseIndent();
2061 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2062 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002063
2064 pw.println();
2065 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2066 pw.increaseIndent();
2067 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2068 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 }
2071
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002072 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002073 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002074 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002075 if (officialNai != null && officialNai.equals(nai)) return true;
2076 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002077 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002078 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002079 " - " + nai);
2080 }
2081 return false;
2082 }
2083
Robert Greenwalt42acef32009-08-12 16:08:25 -07002084 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002085 private class NetworkStateTrackerHandler extends Handler {
2086 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002087 super(looper);
2088 }
2089
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002090 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002092 default:
2093 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002094 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002095 handleAsyncChannelHalfConnect(msg);
2096 break;
2097 }
2098 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2099 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2100 if (nai != null) nai.asyncChannel.disconnect();
2101 break;
2102 }
2103 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2104 handleAsyncChannelDisconnected(msg);
2105 break;
2106 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002107 }
2108 return true;
2109 }
2110
2111 private void maybeHandleNetworkAgentMessage(Message msg) {
2112 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2113 if (nai == null) {
2114 if (VDBG) {
2115 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2116 log(String.format("%s from unknown NetworkAgent", what));
2117 }
2118 return;
2119 }
2120
2121 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002122 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002123 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2124 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002125 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2126 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002127 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002128 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002129 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002130 break;
2131 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002132 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002133 if (VDBG) {
2134 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002135 "; created=" + nai.created +
2136 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002137 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002138 LinkProperties oldLp = nai.linkProperties;
2139 synchronized (nai) {
2140 nai.linkProperties = (LinkProperties)msg.obj;
2141 }
Robin Lee585e2482016-05-01 23:00:00 +01002142 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002143 break;
2144 }
2145 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002146 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002147 updateNetworkInfo(nai, info);
2148 break;
2149 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002150 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002151 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002152 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002153 break;
2154 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002155 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002156 try {
2157 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002158 } catch (Exception e) {
2159 // Never crash!
2160 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002161 }
2162 break;
2163 }
2164 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002165 try {
2166 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002167 } catch (Exception e) {
2168 // Never crash!
2169 loge("Exception in removeVpnUidRanges: " + e);
2170 }
2171 break;
2172 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002173 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002174 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2175 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002176 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002177 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002178 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002179 break;
2180 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002181 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002182 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2183 break;
2184 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002185 }
2186 }
2187
2188 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2189 switch (msg.what) {
2190 default:
2191 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002192 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002193 final NetworkAgentInfo nai;
2194 synchronized (mNetworkForNetId) {
2195 nai = mNetworkForNetId.get(msg.arg2);
2196 }
2197 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002198 final boolean valid =
2199 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002200 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002201 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2202 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002203 if (valid != nai.lastValidated) {
2204 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002205 nai.lastValidated = valid;
2206 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002207 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002208 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2209 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002210 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002211 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002212 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002213 Bundle redirectUrlBundle = new Bundle();
2214 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002215 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002216 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002217 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002218 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002219 if (wasValidated && !nai.lastValidated) {
2220 handleNetworkUnvalidated(nai);
2221 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002222 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002223 break;
2224 }
Paul Jensen869868be2014-05-15 10:33:05 -04002225 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002226 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002227 final boolean visible = (msg.arg1 != 0);
2228 final NetworkAgentInfo nai;
2229 synchronized (mNetworkForNetId) {
2230 nai = mNetworkForNetId.get(netId);
2231 }
Calvin Onbe96da12016-10-11 15:10:46 -07002232 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002233 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002234 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002235 nai.lastCaptivePortalDetected = visible;
2236 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002237 if (nai.lastCaptivePortalDetected &&
2238 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2239 if (DBG) log("Avoiding captive portal network: " + nai.name());
2240 nai.asyncChannel.sendMessage(
2241 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2242 teardownUnneededNetwork(nai);
2243 break;
2244 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002245 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002246 }
2247 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002248 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002249 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002250 if (nai == null) {
2251 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2252 break;
2253 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002254 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002255 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002256 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002257 }
Paul Jensen869868be2014-05-15 10:33:05 -04002258 }
Paul Jensen869868be2014-05-15 10:33:05 -04002259 break;
2260 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002261 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002262 return true;
2263 }
2264
Calvin Onbe96da12016-10-11 15:10:46 -07002265 private int getCaptivePortalMode() {
2266 return Settings.Global.getInt(mContext.getContentResolver(),
2267 Settings.Global.CAPTIVE_PORTAL_MODE,
2268 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2269 }
2270
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002271 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2272 switch (msg.what) {
2273 default:
2274 return false;
2275 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2276 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2277 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2278 handleLingerComplete(nai);
2279 }
2280 break;
2281 }
2282 }
2283 return true;
2284 }
2285
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002286 @Override
2287 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002288 if (!maybeHandleAsyncChannelMessage(msg) &&
2289 !maybeHandleNetworkMonitorMessage(msg) &&
2290 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002291 maybeHandleNetworkAgentMessage(msg);
2292 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002293 }
2294 }
2295
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002296 private void updateLingerState(NetworkAgentInfo nai, long now) {
2297 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2298 // 2. If the network was lingering and there are now requests, unlinger it.
2299 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2300 // one lingered request, start lingering.
2301 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002302 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002303 if (DBG) log("Unlingering " + nai.name());
2304 nai.unlinger();
2305 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002306 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002307 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002308 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002309 nai.linger();
2310 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2311 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2312 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002313 }
2314
Robert Greenwalt7b816022014-04-18 15:25:25 -07002315 private void handleAsyncChannelHalfConnect(Message msg) {
2316 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002317 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002318 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2319 if (VDBG) log("NetworkFactory connected");
2320 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002321 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002322 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002323 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002324 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002325 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002326 }
2327 } else {
2328 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002329 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002330 }
2331 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2332 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2333 if (VDBG) log("NetworkAgent connected");
2334 // A network agent has requested a connection. Establish the connection.
2335 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2336 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2337 } else {
2338 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002339 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002340 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002341 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002342 synchronized (mNetworkForNetId) {
2343 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002344 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002345 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002346 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002347 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002348 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002349 }
2350 }
2351 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002352
Robert Greenwalt7b816022014-04-18 15:25:25 -07002353 private void handleAsyncChannelDisconnected(Message msg) {
2354 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2355 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002356 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002357 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002358 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002359 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002360 // TODO - if we move the logic to the network agent (have them disconnect
2361 // because they lost all their requests or because their score isn't good)
2362 // then they would disconnect organically, report their new state and then
2363 // disconnect the channel.
2364 if (nai.networkInfo.isConnected()) {
2365 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2366 null, null);
2367 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002368 final boolean wasDefault = isDefaultNetwork(nai);
2369 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002370 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002371 // Log default network disconnection before required book-keeping.
2372 // Let rematchAllNetworksAndRequests() below record a new default network event
2373 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2374 // whose timestamps tell how long it takes to recover a default network.
2375 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002376 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002377 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002378 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2379 // by other networks that are already connected. Perhaps that can be done by
2380 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2381 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002382 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002383 mKeepaliveTracker.handleStopAllKeepalives(nai,
2384 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002385 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002386 mNetworkAgentInfos.remove(msg.replyTo);
2387 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002388 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002389 // Remove the NetworkAgent, but don't mark the netId as
2390 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002391 mNetworkForNetId.remove(nai.network.netId);
2392 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002393 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002394 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2395 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002396 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2397 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2398 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002399 sendUpdatedScoreToFactories(request, 0);
2400 }
2401 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002402 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002403 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002404 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002405 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002406 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002407 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002408 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002409 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002410 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002411 if (nai.created) {
2412 // Tell netd to clean up the configuration for this network
2413 // (routing rules, DNS, etc).
2414 // This may be slow as it requires a lot of netd shelling out to ip and
2415 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2416 // after we've rematched networks with requests which should make a potential
2417 // fallback network the default or requested a new network from the
2418 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2419 // long time.
2420 try {
2421 mNetd.removeNetwork(nai.network.netId);
2422 } catch (Exception e) {
2423 loge("Exception removing network: " + e);
2424 }
2425 }
2426 synchronized (mNetworkForNetId) {
2427 mNetIdInUse.delete(nai.network.netId);
2428 }
2429 } else {
2430 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2431 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002432 }
2433 }
2434
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002435 // If this method proves to be too slow then we can maintain a separate
2436 // pendingIntent => NetworkRequestInfo map.
2437 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2438 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2439 Intent intent = pendingIntent.getIntent();
2440 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2441 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2442 if (existingPendingIntent != null &&
2443 existingPendingIntent.getIntent().filterEquals(intent)) {
2444 return entry.getValue();
2445 }
2446 }
2447 return null;
2448 }
2449
2450 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2451 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2452
2453 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2454 if (existingRequest != null) { // remove the existing request.
2455 if (DBG) log("Replacing " + existingRequest.request + " with "
2456 + nri.request + " because their intents matched.");
2457 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2458 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002459 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002460 }
2461
Erik Klineda4bfa82015-04-30 12:58:40 +09002462 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002463 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002464 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002465 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002466 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002467 if (nri.request.networkCapabilities.hasSignalStrength() &&
2468 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2469 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002470 }
2471 }
2472 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002473 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002474 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002475 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002476 }
2477 }
2478
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002479 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2480 int callingUid) {
2481 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2482 if (nri != null) {
2483 handleReleaseNetworkRequest(nri.request, callingUid);
2484 }
2485 }
2486
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002487 // Determines whether the network is the best (or could become the best, if it validated), for
2488 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2489 // on the value of reason:
2490 //
2491 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2492 // then it should be torn down.
2493 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2494 // then it should be lingered.
2495 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2496 final int numRequests;
2497 switch (reason) {
2498 case TEARDOWN:
2499 numRequests = nai.numRequestNetworkRequests();
2500 break;
2501 case LINGER:
2502 numRequests = nai.numForegroundNetworkRequests();
2503 break;
2504 default:
2505 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2506 return true;
2507 }
2508
2509 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002510 return false;
2511 }
Paul Jensene0988542015-06-25 15:30:08 -04002512 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002513 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2514 // Background requests don't affect lingering.
2515 continue;
2516 }
2517
Paul Jensene0988542015-06-25 15:30:08 -04002518 // If this Network is already the highest scoring Network for a request, or if
2519 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002520 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002521 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002522 // Note that this catches two important cases:
2523 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2524 // is currently satisfying the request. This is desirable when
2525 // cellular ends up validating but WiFi does not.
2526 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002527 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002528 // WiFi ends up validating and out scoring cellular.
2529 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2530 nai.getCurrentScoreAsValidated())) {
2531 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002532 }
2533 }
Paul Jensene0988542015-06-25 15:30:08 -04002534 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002535 }
2536
Erik Klineacdd6392016-07-07 16:50:58 +09002537 private NetworkRequestInfo getNriForAppRequest(
2538 NetworkRequest request, int callingUid, String requestedOperation) {
2539 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2540
Robert Greenwalt9258c642014-03-26 16:47:06 -07002541 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002542 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002543 log(String.format("UID %d attempted to %s for unowned request %s",
2544 callingUid, requestedOperation, nri));
2545 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002546 }
Erik Klineacdd6392016-07-07 16:50:58 +09002547 }
2548
2549 return nri;
2550 }
2551
Erik Kline57faba92015-11-25 12:49:38 +09002552 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
2553 if (mNetworkRequests.get(nri.request) != null && mNetworkForRequestId.get(
2554 nri.request.requestId) == null) {
2555 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_UNAVAIL);
2556 }
2557 }
2558
Erik Klineacdd6392016-07-07 16:50:58 +09002559 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2560 final NetworkRequestInfo nri = getNriForAppRequest(
2561 request, callingUid, "release NetworkRequest");
Erik Kline57faba92015-11-25 12:49:38 +09002562 if (nri != null) {
2563 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_RELEASED);
2564 }
2565 }
Erik Klineacdd6392016-07-07 16:50:58 +09002566
Erik Kline57faba92015-11-25 12:49:38 +09002567 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri, final int whichCallback) {
2568 final String logCallbackType = ConnectivityManager.getCallbackName(whichCallback);
2569 if (VDBG || (DBG && nri.request.isRequest())) {
2570 log("releasing " + nri.request + " (" + logCallbackType + ")");
2571 }
Erik Klineacdd6392016-07-07 16:50:58 +09002572 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002573 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002574 synchronized (mUidToNetworkRequestCount) {
2575 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2576 if (requests < 1) {
2577 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2578 nri.mUid);
2579 } else if (requests == 1) {
2580 mUidToNetworkRequestCount.removeAt(
2581 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2582 } else {
2583 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2584 }
2585 }
2586 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2587 if (nri.request.isRequest()) {
2588 boolean wasKept = false;
2589 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2590 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002591 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002592 nai.removeRequest(nri.request.requestId);
2593 if (VDBG) {
2594 log(" Removing from current network " + nai.name() +
2595 ", leaving " + nai.numNetworkRequests() + " requests.");
2596 }
2597 // If there are still lingered requests on this network, don't tear it down,
2598 // but resume lingering instead.
2599 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002600 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002601 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2602 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002603 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002604 wasKept = true;
2605 }
2606 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002607 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2608 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002609 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002610 }
Erik Klineacdd6392016-07-07 16:50:58 +09002611 }
2612
2613 // TODO: remove this code once we know that the Slog.wtf is never hit.
2614 //
2615 // Find all networks that are satisfying this request and remove the request
2616 // from their request lists.
2617 // TODO - it's my understanding that for a request there is only a single
2618 // network satisfying it, so this loop is wasteful
2619 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2620 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2621 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2622 otherNai.name() + ", but mNetworkAgentInfos says " +
2623 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002624 }
2625 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002626
Erik Klineacdd6392016-07-07 16:50:58 +09002627 // Maintain the illusion. When this request arrived, we might have pretended
2628 // that a network connected to serve it, even though the network was already
2629 // connected. Now that this request has gone away, we might have to pretend
2630 // that the network disconnected. LegacyTypeTracker will generate that
2631 // phantom disconnect for this type.
2632 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2633 boolean doRemove = true;
2634 if (wasKept) {
2635 // check if any of the remaining requests for this network are for the
2636 // same legacy type - if so, don't remove the nai
2637 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2638 NetworkRequest otherRequest = nai.requestAt(i);
2639 if (otherRequest.legacyType == nri.request.legacyType &&
2640 otherRequest.isRequest()) {
2641 if (DBG) log(" still have other legacy request - leaving");
2642 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002643 }
2644 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002645 }
2646
Erik Klineacdd6392016-07-07 16:50:58 +09002647 if (doRemove) {
2648 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002649 }
2650 }
Erik Klineacdd6392016-07-07 16:50:58 +09002651
2652 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2653 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2654 nri.request);
2655 }
2656 } else {
2657 // listens don't have a singular affectedNetwork. Check all networks to see
2658 // if this listen request applies and remove it.
2659 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2660 nai.removeRequest(nri.request.requestId);
2661 if (nri.request.networkCapabilities.hasSignalStrength() &&
2662 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2663 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2664 }
2665 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002666 }
Erik Kline57faba92015-11-25 12:49:38 +09002667 callCallbackForRequest(nri, null, whichCallback, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002668 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002669
Lorenzo Colitti18660282016-07-04 12:55:44 +09002670 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002671 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2672 enforceConnectivityInternalPermission();
2673 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2674 accept ? 1 : 0, always ? 1: 0, network));
2675 }
2676
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002677 @Override
2678 public void setAvoidUnvalidated(Network network) {
2679 enforceConnectivityInternalPermission();
2680 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2681 }
2682
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002683 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2684 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2685 " accept=" + accept + " always=" + always);
2686
2687 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2688 if (nai == null) {
2689 // Nothing to do.
2690 return;
2691 }
2692
2693 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002694 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002695 return;
2696 }
2697
2698 if (!nai.networkMisc.explicitlySelected) {
2699 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2700 }
2701
2702 if (accept != nai.networkMisc.acceptUnvalidated) {
2703 int oldScore = nai.getCurrentScore();
2704 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002705 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002706 sendUpdatedScoreToFactories(nai);
2707 }
2708
2709 if (always) {
2710 nai.asyncChannel.sendMessage(
2711 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2712 }
2713
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002714 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002715 // Tell the NetworkAgent to not automatically reconnect to the network.
2716 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2717 // Teardown the nework.
2718 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002719 }
2720
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002721 }
2722
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002723 private void handleSetAvoidUnvalidated(Network network) {
2724 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2725 if (nai == null || nai.lastValidated) {
2726 // Nothing to do. The network either disconnected or revalidated.
2727 return;
2728 }
2729 if (!nai.avoidUnvalidated) {
2730 int oldScore = nai.getCurrentScore();
2731 nai.avoidUnvalidated = true;
2732 rematchAllNetworksAndRequests(nai, oldScore);
2733 sendUpdatedScoreToFactories(nai);
2734 }
2735 }
2736
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002737 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002738 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002739 mHandler.sendMessageDelayed(
2740 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2741 PROMPT_UNVALIDATED_DELAY_MS);
2742 }
2743
Hugo Benichic8e9e122016-09-14 23:23:08 +00002744 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002745 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002746 }
2747
Erik Kline065ab6e2016-10-02 18:02:14 +09002748 private void rematchForAvoidBadWifiUpdate() {
2749 rematchAllNetworksAndRequests(null, 0);
2750 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2751 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2752 sendUpdatedScoreToFactories(nai);
2753 }
2754 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002755 }
2756
Erik Kline065ab6e2016-10-02 18:02:14 +09002757 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002758 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002759 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002760 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002761 if (!configRestrict) {
2762 pw.println("Bad Wi-Fi avoidance: unrestricted");
2763 return;
2764 }
2765
2766 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2767 pw.increaseIndent();
2768 pw.println("Config restrict: " + configRestrict);
2769
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002770 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002771 String description;
2772 // Can't use a switch statement because strings are legal case labels, but null is not.
2773 if ("0".equals(value)) {
2774 description = "get stuck";
2775 } else if (value == null) {
2776 description = "prompt";
2777 } else if ("1".equals(value)) {
2778 description = "avoid";
2779 } else {
2780 description = value + " (?)";
2781 }
2782 pw.println("User setting: " + description);
2783 pw.println("Network overrides:");
2784 pw.increaseIndent();
2785 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2786 if (nai.avoidUnvalidated) {
2787 pw.println(nai.name());
2788 }
2789 }
2790 pw.decreaseIndent();
2791 pw.decreaseIndent();
2792 }
2793
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002794 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2795 final String action;
2796 switch (type) {
2797 case NO_INTERNET:
2798 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2799 break;
2800 case LOST_INTERNET:
2801 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2802 break;
2803 default:
2804 Slog.wtf(TAG, "Unknown notification type " + type);
2805 return;
2806 }
2807
2808 Intent intent = new Intent(action);
2809 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2810 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2811 intent.setClassName("com.android.settings",
2812 "com.android.settings.wifi.WifiNoInternetDialog");
2813
2814 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2815 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2816 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2817 }
2818
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002819 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002820 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002821 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2822
2823 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2824 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002825 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002826 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002827 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2828 return;
2829 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002830 showValidationNotification(nai, NotificationType.NO_INTERNET);
2831 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002832
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002833 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2834 NetworkCapabilities nc = nai.networkCapabilities;
2835 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002836
Erik Kline065ab6e2016-10-02 18:02:14 +09002837 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002838 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002839 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2840 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002841 }
2842
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002843 @Override
2844 public int getMultipathPreference(Network network) {
2845 enforceAccessPermission();
2846
2847 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2848 if (nai != null && !nai.networkInfo.isMetered()) {
2849 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2850 }
2851
2852 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2853 }
2854
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002855 private class InternalHandler extends Handler {
2856 public InternalHandler(Looper looper) {
2857 super(looper);
2858 }
2859
2860 @Override
2861 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002862 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002863 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002864 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002865 String causedBy = null;
2866 synchronized (ConnectivityService.this) {
2867 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2868 mNetTransitionWakeLock.isHeld()) {
2869 mNetTransitionWakeLock.release();
2870 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002871 } else {
2872 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002873 }
2874 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002875 if (VDBG) {
2876 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2877 log("Failed to find a new network - expiring NetTransition Wakelock");
2878 } else {
2879 log("NetTransition Wakelock (" +
2880 (causedBy == null ? "unknown" : causedBy) +
2881 " cleared because we found a replacement network");
2882 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002883 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002884 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002885 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002886 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002887 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002888 break;
2889 }
Jason Monkdecd2952013-10-10 14:02:51 -04002890 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002891 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002892 break;
2893 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002894 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002895 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2896 break;
2897 }
2898 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2899 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002900 break;
2901 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002902 case EVENT_REGISTER_NETWORK_AGENT: {
2903 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2904 break;
2905 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002906 case EVENT_REGISTER_NETWORK_REQUEST:
2907 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002908 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002909 break;
2910 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002911 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2912 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002913 handleRegisterNetworkRequestWithIntent(msg);
2914 break;
2915 }
Erik Kline57faba92015-11-25 12:49:38 +09002916 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2917 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2918 handleTimedOutNetworkRequest(nri);
2919 break;
2920 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002921 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2922 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2923 break;
2924 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002925 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002926 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002927 break;
2928 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002929 case EVENT_SET_ACCEPT_UNVALIDATED: {
2930 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2931 break;
2932 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002933 case EVENT_SET_AVOID_UNVALIDATED: {
2934 handleSetAvoidUnvalidated((Network) msg.obj);
2935 break;
2936 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002937 case EVENT_PROMPT_UNVALIDATED: {
2938 handlePromptUnvalidated((Network) msg.obj);
2939 break;
2940 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002941 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2942 handleMobileDataAlwaysOn();
2943 break;
2944 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002945 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2946 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2947 mKeepaliveTracker.handleStartKeepalive(msg);
2948 break;
2949 }
2950 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2951 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2952 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2953 int slot = msg.arg1;
2954 int reason = msg.arg2;
2955 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2956 break;
2957 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002958 case EVENT_SYSTEM_READY: {
2959 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2960 nai.networkMonitor.systemReady = true;
2961 }
2962 break;
2963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002964 }
2965 }
2966 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002967
2968 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002969 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002970 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002971 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002972 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002973 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002974 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002975 } else {
2976 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2977 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002978 }
2979
2980 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002981 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002982 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002983 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002984
2985 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002986 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002987 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002988 } else {
2989 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2990 }
2991 }
2992
2993 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002994 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002995 public int getLastTetherError(String iface) {
2996 enforceTetherAccessPermission();
2997
2998 if (isTetheringSupported()) {
2999 return mTethering.getLastTetherError(iface);
3000 } else {
3001 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3002 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003003 }
3004
3005 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003006 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003007 public String[] getTetherableUsbRegexs() {
3008 enforceTetherAccessPermission();
3009 if (isTetheringSupported()) {
3010 return mTethering.getTetherableUsbRegexs();
3011 } else {
3012 return new String[0];
3013 }
3014 }
3015
Lorenzo Colitti18660282016-07-04 12:55:44 +09003016 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003017 public String[] getTetherableWifiRegexs() {
3018 enforceTetherAccessPermission();
3019 if (isTetheringSupported()) {
3020 return mTethering.getTetherableWifiRegexs();
3021 } else {
3022 return new String[0];
3023 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003024 }
3025
Lorenzo Colitti18660282016-07-04 12:55:44 +09003026 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003027 public String[] getTetherableBluetoothRegexs() {
3028 enforceTetherAccessPermission();
3029 if (isTetheringSupported()) {
3030 return mTethering.getTetherableBluetoothRegexs();
3031 } else {
3032 return new String[0];
3033 }
3034 }
3035
Lorenzo Colitti18660282016-07-04 12:55:44 +09003036 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003037 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003038 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003039 if (isTetheringSupported()) {
3040 return mTethering.setUsbTethering(enable);
3041 } else {
3042 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3043 }
3044 }
3045
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003046 // TODO - move iface listing, queries, etc to new module
3047 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003048 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003049 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003050 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003051 return mTethering.getTetherableIfaces();
3052 }
3053
Lorenzo Colitti18660282016-07-04 12:55:44 +09003054 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003055 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003056 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003057 return mTethering.getTetheredIfaces();
3058 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003059
Lorenzo Colitti18660282016-07-04 12:55:44 +09003060 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003061 public String[] getTetheringErroredIfaces() {
3062 enforceTetherAccessPermission();
3063 return mTethering.getErroredIfaces();
3064 }
3065
Lorenzo Colitti18660282016-07-04 12:55:44 +09003066 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003067 public String[] getTetheredDhcpRanges() {
3068 enforceConnectivityInternalPermission();
3069 return mTethering.getTetheredDhcpRanges();
3070 }
3071
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003072 // if ro.tether.denied = true we default to no tethering
3073 // gservices could set the secure setting to 1 though to enable it on a build where it
3074 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003075 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003076 public boolean isTetheringSupported() {
3077 enforceTetherAccessPermission();
3078 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003079 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003080 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
3081 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003082
3083 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3084 boolean adminUser = false;
3085 final long token = Binder.clearCallingIdentity();
3086 try {
3087 adminUser = mUserManager.isAdminUser();
3088 } finally {
3089 Binder.restoreCallingIdentity(token);
3090 }
3091
3092 return tetherEnabledInSettings && adminUser &&
Erik Klined781fba2017-01-23 13:01:58 +09003093 mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003094 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003095
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003096 @Override
Hugo Benichib55fb222017-03-10 14:20:57 +09003097 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi) {
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003098 ConnectivityManager.enforceTetherChangePermission(mContext);
3099 if (!isTetheringSupported()) {
3100 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3101 return;
3102 }
3103 mTethering.startTethering(type, receiver, showProvisioningUi);
3104 }
3105
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003106 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003107 public void stopTethering(int type) {
3108 ConnectivityManager.enforceTetherChangePermission(mContext);
3109 mTethering.stopTethering(type);
3110 }
3111
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003112 // Called when we lose the default network and have no replacement yet.
3113 // This will automatically be cleared after X seconds or a new default network
3114 // becomes CONNECTED, whichever happens first. The timer is started by the
3115 // first caller and not restarted by subsequent callers.
3116 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003117 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003118 synchronized (this) {
3119 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07003120 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003121 mNetTransitionWakeLock.acquire();
3122 mNetTransitionWakeLockCausedBy = forWhom;
3123 }
3124 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07003125 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003126 mNetTransitionWakeLockTimeout);
3127 return;
3128 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003129
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003130 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003131 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003132 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003133 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003134 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003135 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003136 }
3137
Lorenzo Colitti18660282016-07-04 12:55:44 +09003138 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003139 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003140 enforceAccessPermission();
3141 enforceInternetPermission();
3142
Paul Jensenbfd17b72015-04-07 12:43:13 -04003143 NetworkAgentInfo nai;
3144 if (network == null) {
3145 nai = getDefaultNetwork();
3146 } else {
3147 nai = getNetworkAgentInfoForNetwork(network);
3148 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003149 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3150 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3151 return;
3152 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003153 // Revalidate if the app report does not match our current validated state.
3154 if (hasConnectivity == nai.lastValidated) return;
3155 final int uid = Binder.getCallingUid();
3156 if (DBG) {
3157 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3158 ") by " + uid);
3159 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003160 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003161 // Validating a network that has not yet connected could result in a call to
3162 // rematchNetworkAndRequests() which is not meant to work on such networks.
3163 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003164
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003165 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003166
3167 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3168 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003169 }
3170
Paul Jensencee9b512015-05-06 07:32:40 -04003171 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003172 // this information is already available as a world read/writable jvm property
3173 // so this API change wouldn't have a benifit. It also breaks the passing
3174 // of proxy info to all the JVMs.
3175 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003176 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003177 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003178 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3179 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003180 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003181 }
3182
Lorenzo Colitti18660282016-07-04 12:55:44 +09003183 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003184 public ProxyInfo getProxyForNetwork(Network network) {
3185 if (network == null) return getDefaultProxy();
3186 final ProxyInfo globalProxy = getGlobalProxy();
3187 if (globalProxy != null) return globalProxy;
3188 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3189 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3190 // caller may not have.
3191 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3192 if (nai == null) return null;
3193 synchronized (nai) {
3194 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3195 if (proxyInfo == null) return null;
3196 return new ProxyInfo(proxyInfo);
3197 }
3198 }
3199
Paul Jensene0bef712014-12-10 15:12:18 -05003200 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3201 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3202 // proxy is null then there is no proxy in place).
3203 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3204 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3205 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3206 proxy = null;
3207 }
3208 return proxy;
3209 }
3210
3211 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3212 // better for determining if a new proxy broadcast is necessary:
3213 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3214 // avoid unnecessary broadcasts.
3215 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3216 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3217 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3218 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3219 // all set.
3220 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3221 a = canonicalizeProxyInfo(a);
3222 b = canonicalizeProxyInfo(b);
3223 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3224 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3225 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3226 }
3227
Jason Monk207900c2014-04-25 15:00:09 -04003228 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003229 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003230
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003231 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003232 if (proxyProperties == mGlobalProxy) return;
3233 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3234 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3235
3236 String host = "";
3237 int port = 0;
3238 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003239 String pacFileUrl = "";
3240 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003241 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003242 if (!proxyProperties.isValid()) {
3243 if (DBG)
3244 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3245 return;
3246 }
Jason Monk207900c2014-04-25 15:00:09 -04003247 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003248 host = mGlobalProxy.getHost();
3249 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003250 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003251 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003252 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003253 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003254 } else {
3255 mGlobalProxy = null;
3256 }
3257 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003258 final long token = Binder.clearCallingIdentity();
3259 try {
3260 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3261 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3262 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3263 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003264 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003265 } finally {
3266 Binder.restoreCallingIdentity(token);
3267 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003268
Jason Monkcf0f97a2014-10-02 15:39:38 -04003269 if (mGlobalProxy == null) {
3270 proxyProperties = mDefaultProxy;
3271 }
3272 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003273 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003274 }
3275
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003276 private void loadGlobalProxy() {
3277 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003278 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3279 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3280 String exclList = Settings.Global.getString(res,
3281 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003282 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3283 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003284 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003285 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003286 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003287 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003288 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003289 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003290 if (!proxyProperties.isValid()) {
3291 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3292 return;
3293 }
3294
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003295 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003296 mGlobalProxy = proxyProperties;
3297 }
3298 }
3299 }
3300
Jason Monk207900c2014-04-25 15:00:09 -04003301 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003302 // this information is already available as a world read/writable jvm property
3303 // so this API change wouldn't have a benifit. It also breaks the passing
3304 // of proxy info to all the JVMs.
3305 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003306 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003307 return mGlobalProxy;
3308 }
3309 }
3310
Jason Monk207900c2014-04-25 15:00:09 -04003311 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003312 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003313 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003314 proxy = null;
3315 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003316 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003317 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003318 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003319 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003320 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3321 return;
3322 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003323
3324 // This call could be coming from the PacManager, containing the port of the local
3325 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3326 // global (to get the correct local port), and send a broadcast.
3327 // TODO: Switch PacManager to have its own message to send back rather than
3328 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003329 if ((mGlobalProxy != null) && (proxy != null)
3330 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003331 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3332 mGlobalProxy = proxy;
3333 sendProxyBroadcast(mGlobalProxy);
3334 return;
3335 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003336 mDefaultProxy = proxy;
3337
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003338 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003339 if (!mDefaultProxyDisabled) {
3340 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003341 }
3342 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003343 }
3344
Paul Jensene0bef712014-12-10 15:12:18 -05003345 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3346 // This method gets called when any network changes proxy, but the broadcast only ever contains
3347 // the default proxy (even if it hasn't changed).
3348 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3349 // world where an app might be bound to a non-default network.
3350 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3351 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3352 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3353
3354 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3355 sendProxyBroadcast(getDefaultProxy());
3356 }
3357 }
3358
Robert Greenwalt434203a2010-10-11 16:00:27 -07003359 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003360 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3361 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003362 if (!TextUtils.isEmpty(proxy)) {
3363 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003364 if (data.length == 0) {
3365 return;
3366 }
3367
Robert Greenwalt434203a2010-10-11 16:00:27 -07003368 String proxyHost = data[0];
3369 int proxyPort = 8080;
3370 if (data.length > 1) {
3371 try {
3372 proxyPort = Integer.parseInt(data[1]);
3373 } catch (NumberFormatException e) {
3374 return;
3375 }
3376 }
Jason Monk207900c2014-04-25 15:00:09 -04003377 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003378 setGlobalProxy(p);
3379 }
3380 }
3381
Jason Monk207900c2014-04-25 15:00:09 -04003382 private void sendProxyBroadcast(ProxyInfo proxy) {
3383 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003384 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003385 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003386 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003387 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3388 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003389 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003390 final long ident = Binder.clearCallingIdentity();
3391 try {
3392 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3393 } finally {
3394 Binder.restoreCallingIdentity(ident);
3395 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003396 }
3397
3398 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003399 final private HashMap<Uri, Integer> mUriEventMap;
3400 final private Context mContext;
3401 final private Handler mHandler;
3402
3403 SettingsObserver(Context context, Handler handler) {
3404 super(null);
3405 mUriEventMap = new HashMap<Uri, Integer>();
3406 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003407 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003408 }
3409
Erik Klineda4bfa82015-04-30 12:58:40 +09003410 void observe(Uri uri, int what) {
3411 mUriEventMap.put(uri, what);
3412 final ContentResolver resolver = mContext.getContentResolver();
3413 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003414 }
3415
3416 @Override
3417 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003418 Slog.wtf(TAG, "Should never be reached.");
3419 }
3420
3421 @Override
3422 public void onChange(boolean selfChange, Uri uri) {
3423 final Integer what = mUriEventMap.get(uri);
3424 if (what != null) {
3425 mHandler.obtainMessage(what.intValue()).sendToTarget();
3426 } else {
3427 loge("No matching event to send for URI=" + uri);
3428 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003429 }
3430 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003431
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003432 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003433 Slog.d(TAG, s);
3434 }
3435
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003436 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003437 Slog.e(TAG, s);
3438 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003439
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003440 private static <T> T checkNotNull(T value, String message) {
3441 if (value == null) {
3442 throw new NullPointerException(message);
3443 }
3444 return value;
3445 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003446
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003447 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003448 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003449 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3450 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3451 *
3452 * @param oldPackage Package name of the application which currently controls VPN, which will
3453 * be replaced. If there is no such application, this should should either be
3454 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3455 * @param newPackage Package name of the application which should gain control of VPN, or
3456 * {@code null} to disable.
3457 * @param userId User for whom to prepare the new VPN.
3458 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003459 * @hide
3460 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003461 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003462 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3463 int userId) {
3464 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003465 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003466
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003467 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003468 Vpn vpn = mVpns.get(userId);
3469 if (vpn != null) {
3470 return vpn.prepare(oldPackage, newPackage);
3471 } else {
3472 return false;
3473 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003474 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003475 }
3476
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003477 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003478 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3479 * This method is used by system-privileged apps.
3480 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3481 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3482 *
3483 * @param packageName The package for which authorization state should change.
3484 * @param userId User for whom {@code packageName} is installed.
3485 * @param authorized {@code true} if this app should be able to start a VPN connection without
3486 * explicit user approval, {@code false} if not.
3487 *
Jeff Davidson05542602014-08-11 14:07:27 -07003488 * @hide
3489 */
3490 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003491 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3492 enforceCrossUserPermission(userId);
3493
Jeff Davidson05542602014-08-11 14:07:27 -07003494 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003495 Vpn vpn = mVpns.get(userId);
3496 if (vpn != null) {
3497 vpn.setPackageAuthorization(packageName, authorized);
3498 }
Jeff Davidson05542602014-08-11 14:07:27 -07003499 }
3500 }
3501
3502 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003503 * Configure a TUN interface and return its file descriptor. Parameters
3504 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003505 * and not available in ConnectivityManager. Permissions are checked in
3506 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003507 * @hide
3508 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003509 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003510 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003511 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003512 int user = UserHandle.getUserId(Binder.getCallingUid());
3513 synchronized(mVpns) {
3514 return mVpns.get(user).establish(config);
3515 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003516 }
3517
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003518 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003519 * Start legacy VPN, controlling native daemons as needed. Creates a
3520 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003521 */
3522 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003523 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003524 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003525 final LinkProperties egress = getActiveLinkProperties();
3526 if (egress == null) {
3527 throw new IllegalStateException("Missing active network connection");
3528 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003529 int user = UserHandle.getUserId(Binder.getCallingUid());
3530 synchronized(mVpns) {
3531 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3532 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003533 }
3534
3535 /**
3536 * Return the information of the ongoing legacy VPN. This method is used
3537 * by VpnSettings and not available in ConnectivityManager. Permissions
3538 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003539 */
3540 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003541 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3542 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003543
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003544 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003545 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003546 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003547 }
3548
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003549 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003550 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3551 * and not available in ConnectivityManager.
3552 */
3553 @Override
3554 public VpnInfo[] getAllVpnInfo() {
3555 enforceConnectivityInternalPermission();
3556 if (mLockdownEnabled) {
3557 return new VpnInfo[0];
3558 }
3559
3560 synchronized(mVpns) {
3561 List<VpnInfo> infoList = new ArrayList<>();
3562 for (int i = 0; i < mVpns.size(); i++) {
3563 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3564 if (info != null) {
3565 infoList.add(info);
3566 }
3567 }
3568 return infoList.toArray(new VpnInfo[infoList.size()]);
3569 }
3570 }
3571
3572 /**
3573 * @return VPN information for accounting, or null if we can't retrieve all required
3574 * information, e.g primary underlying iface.
3575 */
3576 @Nullable
3577 private VpnInfo createVpnInfo(Vpn vpn) {
3578 VpnInfo info = vpn.getVpnInfo();
3579 if (info == null) {
3580 return null;
3581 }
3582 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3583 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3584 // the underlyingNetworks list.
3585 if (underlyingNetworks == null) {
3586 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3587 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3588 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3589 }
3590 } else if (underlyingNetworks.length > 0) {
3591 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3592 if (linkProperties != null) {
3593 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3594 }
3595 }
3596 return info.primaryUnderlyingIface == null ? null : info;
3597 }
3598
3599 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003600 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3601 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003602 * Permissions are checked in Vpn class.
3603 * @hide
3604 */
3605 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003606 public VpnConfig getVpnConfig(int userId) {
3607 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003608 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003609 Vpn vpn = mVpns.get(userId);
3610 if (vpn != null) {
3611 return vpn.getVpnConfig();
3612 } else {
3613 return null;
3614 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003615 }
3616 }
3617
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003618 @Override
3619 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003620 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3621 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3622 return false;
3623 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003624
3625 // Tear down existing lockdown if profile was removed
3626 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3627 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003628 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3629 if (profileTag == null) {
3630 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3631 return false;
3632 }
3633 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003634 final VpnProfile profile = VpnProfile.decode(
3635 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003636 if (profile == null) {
3637 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3638 setLockdownTracker(null);
3639 return true;
3640 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003641 int user = UserHandle.getUserId(Binder.getCallingUid());
3642 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003643 Vpn vpn = mVpns.get(user);
3644 if (vpn == null) {
3645 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3646 return false;
3647 }
3648 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003649 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003650 } else {
3651 setLockdownTracker(null);
3652 }
3653
3654 return true;
3655 }
3656
3657 /**
3658 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3659 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3660 */
3661 private void setLockdownTracker(LockdownVpnTracker tracker) {
3662 // Shutdown any existing tracker
3663 final LockdownVpnTracker existing = mLockdownTracker;
3664 mLockdownTracker = null;
3665 if (existing != null) {
3666 existing.shutdown();
3667 }
3668
3669 try {
3670 if (tracker != null) {
3671 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003672 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003673 mLockdownTracker = tracker;
3674 mLockdownTracker.init();
3675 } else {
3676 mNetd.setFirewallEnabled(false);
3677 }
3678 } catch (RemoteException e) {
3679 // ignored; NMS lives inside system_server
3680 }
3681 }
3682
3683 private void throwIfLockdownEnabled() {
3684 if (mLockdownEnabled) {
3685 throw new IllegalStateException("Unavailable in lockdown mode");
3686 }
3687 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003688
Robin Lee244ce8e2016-01-05 18:03:46 +00003689 /**
Robin Lee17e61832016-05-09 13:46:28 +01003690 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3691 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003692 *
Robin Lee17e61832016-05-09 13:46:28 +01003693 * @return {@code true} if the service was started, the service was already connected, or there
3694 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003695 */
Robin Lee17e61832016-05-09 13:46:28 +01003696 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003697 synchronized (mVpns) {
3698 Vpn vpn = mVpns.get(userId);
3699 if (vpn == null) {
3700 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3701 // exists already.
3702 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3703 return false;
3704 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003705
Robin Lee812800c2016-05-13 15:38:08 +01003706 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003707 }
3708 }
3709
3710 @Override
Robin Leedc679712016-05-03 13:23:03 +01003711 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003712 enforceConnectivityInternalPermission();
3713 enforceCrossUserPermission(userId);
3714
3715 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3716 if (LockdownVpnTracker.isEnabled()) {
3717 return false;
3718 }
3719
Robin Lee244ce8e2016-01-05 18:03:46 +00003720 synchronized (mVpns) {
3721 Vpn vpn = mVpns.get(userId);
3722 if (vpn == null) {
3723 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3724 return false;
3725 }
Robin Lee17e61832016-05-09 13:46:28 +01003726 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003727 return false;
3728 }
Robin Lee17e61832016-05-09 13:46:28 +01003729 if (!startAlwaysOnVpn(userId)) {
3730 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003731 return false;
3732 }
Robin Lee17e61832016-05-09 13:46:28 +01003733
Robin Lee812800c2016-05-13 15:38:08 +01003734 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003735 }
3736 return true;
3737 }
3738
3739 @Override
3740 public String getAlwaysOnVpnPackage(int userId) {
3741 enforceConnectivityInternalPermission();
3742 enforceCrossUserPermission(userId);
3743
3744 synchronized (mVpns) {
3745 Vpn vpn = mVpns.get(userId);
3746 if (vpn == null) {
3747 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3748 return null;
3749 }
3750 return vpn.getAlwaysOnPackage();
3751 }
3752 }
3753
Wink Savilleab9321d2013-06-29 21:10:57 -07003754 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003755 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003756 // TODO: Remove? Any reason to trigger a provisioning check?
3757 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003758 }
3759
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003760 /** Location to an updatable file listing carrier provisioning urls.
3761 * An example:
3762 *
3763 * <?xml version="1.0" encoding="utf-8"?>
3764 * <provisioningUrls>
3765 * <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 -07003766 * </provisioningUrls>
3767 */
3768 private static final String PROVISIONING_URL_PATH =
3769 "/data/misc/radio/provisioning_urls.xml";
3770 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003771
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003772 /** XML tag for root element. */
3773 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3774 /** XML tag for individual url */
3775 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003776 /** XML attribute for mcc */
3777 private static final String ATTR_MCC = "mcc";
3778 /** XML attribute for mnc */
3779 private static final String ATTR_MNC = "mnc";
3780
Paul Jensen434dde82015-06-11 09:43:30 -04003781 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003782 FileReader fileReader = null;
3783 XmlPullParser parser = null;
3784 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003785
3786 try {
3787 fileReader = new FileReader(mProvisioningUrlFile);
3788 parser = Xml.newPullParser();
3789 parser.setInput(fileReader);
3790 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3791
3792 while (true) {
3793 XmlUtils.nextElement(parser);
3794
3795 String element = parser.getName();
3796 if (element == null) break;
3797
Paul Jensen434dde82015-06-11 09:43:30 -04003798 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003799 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3800 try {
3801 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3802 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3803 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3804 parser.next();
3805 if (parser.getEventType() == XmlPullParser.TEXT) {
3806 return parser.getText();
3807 }
3808 }
3809 }
3810 } catch (NumberFormatException e) {
3811 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3812 }
3813 }
3814 }
3815 return null;
3816 } catch (FileNotFoundException e) {
3817 loge("Carrier Provisioning Urls file not found");
3818 } catch (XmlPullParserException e) {
3819 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3820 } catch (IOException e) {
3821 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3822 } finally {
3823 if (fileReader != null) {
3824 try {
3825 fileReader.close();
3826 } catch (IOException e) {}
3827 }
3828 }
3829 return null;
3830 }
3831
Wink Saville42d4f082013-07-20 20:31:59 -07003832 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003833 public String getMobileProvisioningUrl() {
3834 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003835 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003836 if (TextUtils.isEmpty(url)) {
3837 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003838 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003839 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003840 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003841 }
Wink Saville8cf35602013-07-10 23:00:07 -07003842 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003843 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003844 String phoneNumber = mTelephonyManager.getLine1Number();
3845 if (TextUtils.isEmpty(phoneNumber)) {
3846 phoneNumber = "0000000000";
3847 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003848 url = String.format(url,
3849 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3850 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003851 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003852 }
3853
Wink Savilleab9321d2013-06-29 21:10:57 -07003854 return url;
3855 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003856
Wink Saville948282b2013-08-29 08:55:16 -07003857 @Override
3858 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003859 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003860 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003861 final long ident = Binder.clearCallingIdentity();
3862 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003863 // Concatenate the range of types onto the range of NetIDs.
3864 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3865 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003866 } finally {
3867 Binder.restoreCallingIdentity(ident);
3868 }
Wink Saville948282b2013-08-29 08:55:16 -07003869 }
Wink Saville7788c612013-08-29 14:57:08 -07003870
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003871 @Override
3872 public void setAirplaneMode(boolean enable) {
3873 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003874 final long ident = Binder.clearCallingIdentity();
3875 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003876 final ContentResolver cr = mContext.getContentResolver();
3877 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3878 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3879 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003880 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003881 } finally {
3882 Binder.restoreCallingIdentity(ident);
3883 }
3884 }
3885
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003886 private void onUserStart(int userId) {
3887 synchronized(mVpns) {
3888 Vpn userVpn = mVpns.get(userId);
3889 if (userVpn != null) {
3890 loge("Starting user already has a VPN");
3891 return;
3892 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003893 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003894 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003895
3896 final ContentResolver cr = mContext.getContentResolver();
3897 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3898 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3899 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3900 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3901 if (alwaysOnPackage != null) {
3902 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3903 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003904 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003905 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3906 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003907 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003908 }
3909
3910 private void onUserStop(int userId) {
3911 synchronized(mVpns) {
3912 Vpn userVpn = mVpns.get(userId);
3913 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003914 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003915 return;
3916 }
Robin Lee17e61832016-05-09 13:46:28 +01003917 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003918 mVpns.delete(userId);
3919 }
3920 }
3921
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003922 private void onUserAdded(int userId) {
3923 synchronized(mVpns) {
3924 final int vpnsSize = mVpns.size();
3925 for (int i = 0; i < vpnsSize; i++) {
3926 Vpn vpn = mVpns.valueAt(i);
3927 vpn.onUserAdded(userId);
3928 }
3929 }
3930 }
3931
3932 private void onUserRemoved(int userId) {
3933 synchronized(mVpns) {
3934 final int vpnsSize = mVpns.size();
3935 for (int i = 0; i < vpnsSize; i++) {
3936 Vpn vpn = mVpns.valueAt(i);
3937 vpn.onUserRemoved(userId);
3938 }
3939 }
3940 }
3941
Robin Lee89e7a692016-02-29 14:38:17 +00003942 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003943 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3944 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3945 updateLockdownVpn();
3946 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003947 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003948 }
3949 }
3950
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003951 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3952 @Override
3953 public void onReceive(Context context, Intent intent) {
3954 final String action = intent.getAction();
3955 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3956 if (userId == UserHandle.USER_NULL) return;
3957
Robin Lee323f29d2016-05-04 16:38:06 +01003958 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003959 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003960 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003961 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003962 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3963 onUserAdded(userId);
3964 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3965 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003966 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3967 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003968 }
3969 }
3970 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003971
Robin Lee95204e02017-01-27 11:59:22 +00003972 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3973 @Override
3974 public void onReceive(Context context, Intent intent) {
3975 // Try creating lockdown tracker, since user present usually means
3976 // unlocked keystore.
3977 updateLockdownVpn();
3978 mContext.unregisterReceiver(this);
3979 }
3980 };
3981
Robert Greenwalta67be032014-05-16 15:49:14 -07003982 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3983 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003984 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3985 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003986
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003987 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3988 // Map from UID to number of NetworkRequests that UID has filed.
3989 @GuardedBy("mUidToNetworkRequestCount")
3990 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3991
Robert Greenwalta67be032014-05-16 15:49:14 -07003992 private static class NetworkFactoryInfo {
3993 public final String name;
3994 public final Messenger messenger;
3995 public final AsyncChannel asyncChannel;
3996
3997 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3998 this.name = name;
3999 this.messenger = messenger;
4000 this.asyncChannel = asyncChannel;
4001 }
4002 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004003
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004004 private void ensureNetworkRequestHasType(NetworkRequest request) {
4005 if (request.type == NetworkRequest.Type.NONE) {
4006 throw new IllegalArgumentException(
4007 "All NetworkRequests in ConnectivityService must have a type");
4008 }
4009 }
4010
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004011 /**
4012 * Tracks info about the requester.
4013 * Also used to notice when the calling process dies so we can self-expire
4014 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004015 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004016 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004017 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004018 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004019 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004020 final int mPid;
4021 final int mUid;
4022 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004023
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004024 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004025 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004026 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004027 mPendingIntent = pi;
4028 messenger = null;
4029 mBinder = null;
4030 mPid = getCallingPid();
4031 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004032 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004033 }
4034
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004035 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004036 super();
4037 messenger = m;
4038 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004039 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004040 mBinder = binder;
4041 mPid = getCallingPid();
4042 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004043 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004044 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004045
4046 try {
4047 mBinder.linkToDeath(this, 0);
4048 } catch (RemoteException e) {
4049 binderDied();
4050 }
4051 }
4052
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004053 private void enforceRequestCountLimit() {
4054 synchronized (mUidToNetworkRequestCount) {
4055 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4056 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
4057 throw new IllegalArgumentException("Too many NetworkRequests filed");
4058 }
4059 mUidToNetworkRequestCount.put(mUid, networkRequests);
4060 }
4061 }
4062
Robert Greenwalt9258c642014-03-26 16:47:06 -07004063 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004064 if (mBinder != null) {
4065 mBinder.unlinkToDeath(this, 0);
4066 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004067 }
4068
4069 public void binderDied() {
4070 log("ConnectivityService NetworkRequestInfo binderDied(" +
4071 request + ", " + mBinder + ")");
4072 releaseNetworkRequest(request);
4073 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004074
4075 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004076 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004077 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004078 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004079 }
4080
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004081 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4082 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4083 if (badCapability != null) {
4084 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004085 }
4086 }
4087
Erik Kline9d598e12015-07-13 16:37:51 +09004088 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004089 final SortedSet<Integer> thresholds = new TreeSet();
4090 synchronized (nai) {
4091 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4092 if (nri.request.networkCapabilities.hasSignalStrength() &&
4093 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4094 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4095 }
4096 }
4097 }
Erik Kline9d598e12015-07-13 16:37:51 +09004098 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004099 }
4100
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004101 private void updateSignalStrengthThresholds(
4102 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4103 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004104 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004105 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4106
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004107 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004108 String detail;
4109 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4110 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4111 } else {
4112 detail = reason;
4113 }
4114 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4115 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4116 }
4117
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004118 nai.asyncChannel.sendMessage(
4119 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004120 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004121 }
4122
Robert Greenwalt9258c642014-03-26 16:47:06 -07004123 @Override
4124 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004125 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004126 final NetworkRequest.Type type = (networkCapabilities == null)
4127 ? NetworkRequest.Type.TRACK_DEFAULT
4128 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004129 // If the requested networkCapabilities is null, take them instead from
4130 // the default network request. This allows callers to keep track of
4131 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004132 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004133 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4134 enforceAccessPermission();
4135 } else {
4136 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4137 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004138 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4139 // of the app when the request is filed, but we never change the request if the app
4140 // changes network state. http://b/29964605
4141 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004142 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004143 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004144
Etan Cohenba07c8c2017-02-05 10:42:27 -08004145 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004146 throw new IllegalArgumentException("Bad timeout specified");
4147 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004148
Etan Cohenddb9ef02015-11-18 10:56:15 -08004149 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4150 .equals(networkCapabilities.getNetworkSpecifier())) {
4151 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4152 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4153 }
4154
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004155 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004156 nextNetworkRequestId(), type);
4157 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004158 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004159
4160 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004161 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004162 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004163 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004164 }
4165 return networkRequest;
4166 }
4167
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004168 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004169 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004170 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004171 } else {
4172 enforceChangePermission();
4173 }
4174 }
4175
fenglub15e72b2015-03-20 11:29:56 -07004176 @Override
fengludb571472015-04-21 17:12:05 -07004177 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004178 enforceAccessPermission();
4179 NetworkAgentInfo nai = null;
4180 if (network == null) {
4181 return false;
4182 }
4183 synchronized (mNetworkForNetId) {
4184 nai = mNetworkForNetId.get(network.netId);
4185 }
4186 if (nai != null) {
4187 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4188 return true;
4189 }
4190 return false;
4191 }
4192
Felipe Lemeee27cab2016-06-20 16:36:29 -07004193 private boolean isSystem(int uid) {
4194 return uid < Process.FIRST_APPLICATION_UID;
4195 }
fenglub15e72b2015-03-20 11:29:56 -07004196
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004197 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004198 final int uid = Binder.getCallingUid();
4199 if (isSystem(uid)) {
4200 return;
4201 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004202 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004203 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004204 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004205 synchronized(mRulesLock) {
4206 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4207 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004208 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4209 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004210 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004211 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004212 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004213 }
4214 }
4215 }
4216
Robert Greenwalt9258c642014-03-26 16:47:06 -07004217 @Override
4218 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4219 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004220 checkNotNull(operation, "PendingIntent cannot be null.");
4221 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4222 enforceNetworkRequestPermissions(networkCapabilities);
4223 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004224 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004225
4226 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004227 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4228 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004229 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004230 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4231 nri));
4232 return networkRequest;
4233 }
4234
Jeremy Joslin79294842014-12-03 17:15:28 -08004235 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4236 mHandler.sendMessageDelayed(
4237 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4238 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4239 }
4240
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004241 @Override
4242 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004243 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004244 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4245 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004246 }
4247
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004248 // In order to implement the compatibility measure for pre-M apps that call
4249 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4250 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4251 // This ensures it has permission to do so.
4252 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4253 if (nc == null) {
4254 return false;
4255 }
4256 int[] transportTypes = nc.getTransportTypes();
4257 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4258 return false;
4259 }
4260 try {
4261 mContext.enforceCallingOrSelfPermission(
4262 android.Manifest.permission.ACCESS_WIFI_STATE,
4263 "ConnectivityService");
4264 } catch (SecurityException e) {
4265 return false;
4266 }
4267 return true;
4268 }
4269
Robert Greenwalt9258c642014-03-26 16:47:06 -07004270 @Override
4271 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4272 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004273 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4274 enforceAccessPermission();
4275 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004276
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004277 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4278 if (!ConnectivityManager.checkChangePermission(mContext)) {
4279 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4280 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4281 // onLost and onAvailable callbacks when networks move in and out of the background.
4282 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4283 // can't request networks.
4284 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4285 }
4286
4287 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004288 NetworkRequest.Type.LISTEN);
4289 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004290 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004291
4292 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4293 return networkRequest;
4294 }
4295
4296 @Override
4297 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4298 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004299 checkNotNull(operation, "PendingIntent cannot be null.");
4300 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4301 enforceAccessPermission();
4302 }
4303
Erik Kline7523eb32015-07-09 18:24:03 +09004304 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004305 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4306 NetworkRequest.Type.LISTEN);
4307 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004308 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004309
4310 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004311 }
4312
Erik Klineacdd6392016-07-07 16:50:58 +09004313 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004314 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004315 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004316 mHandler.sendMessage(mHandler.obtainMessage(
4317 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004318 }
4319
4320 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004321 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004322 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004323 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4324 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004325 }
4326
Robert Greenwalta67be032014-05-16 15:49:14 -07004327 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004328 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004329 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4330 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4331 }
4332
4333 @Override
4334 public void unregisterNetworkFactory(Messenger messenger) {
4335 enforceConnectivityInternalPermission();
4336 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4337 }
4338
4339 private void handleUnregisterNetworkFactory(Messenger messenger) {
4340 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4341 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004342 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004343 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004344 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004345 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004346 }
4347
Robert Greenwalt7b816022014-04-18 15:25:25 -07004348 /**
4349 * NetworkAgentInfo supporting a request by requestId.
4350 * These have already been vetted (their Capabilities satisfy the request)
4351 * and the are the highest scored network available.
4352 * the are keyed off the Requests requestId.
4353 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004354 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004355 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4356 new SparseArray<NetworkAgentInfo>();
4357
Paul Jensen31a94f42015-02-13 14:18:39 -05004358 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4359 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004360 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4361 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004362 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4363 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4364 // there may not be a strict 1:1 correlation between the two.
4365 @GuardedBy("mNetworkForNetId")
4366 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004367
Robert Greenwalt7b816022014-04-18 15:25:25 -07004368 // NetworkAgentInfo keyed off its connecting messenger
4369 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004370 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004371 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4372 new HashMap<Messenger, NetworkAgentInfo>();
4373
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004374 @GuardedBy("mBlockedAppUids")
4375 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4376
Paul Jensen2c311d62014-11-17 12:34:51 -05004377 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004378 private final NetworkRequest mDefaultRequest;
4379
Erik Klineda4bfa82015-04-30 12:58:40 +09004380 // Request used to optionally keep mobile data active even when higher
4381 // priority networks like Wi-Fi are active.
4382 private final NetworkRequest mDefaultMobileDataRequest;
4383
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004384 private NetworkAgentInfo getDefaultNetwork() {
4385 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4386 }
4387
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004388 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004389 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004390 }
4391
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004392 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4393 return nri.request.requestId == mDefaultRequest.requestId;
4394 }
4395
Paul Jensen31a94f42015-02-13 14:18:39 -05004396 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004397 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004398 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004399 enforceConnectivityInternalPermission();
4400
Paul Jensen2c311d62014-11-17 12:34:51 -05004401 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4402 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004403 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004404 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4405 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004406 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004407 synchronized (this) {
4408 nai.networkMonitor.systemReady = mSystemReady;
4409 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004410 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4411 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004412 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004413 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004414 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004415 }
4416
4417 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4418 if (VDBG) log("Got NetworkAgent Messenger");
4419 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004420 synchronized (mNetworkForNetId) {
4421 mNetworkForNetId.put(na.network.netId, na);
4422 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004423 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4424 NetworkInfo networkInfo = na.networkInfo;
4425 na.networkInfo = null;
4426 updateNetworkInfo(na, networkInfo);
4427 }
4428
4429 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4430 LinkProperties newLp = networkAgent.linkProperties;
4431 int netId = networkAgent.network.netId;
4432
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004433 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4434 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004435 if (networkAgent.clatd != null) {
4436 networkAgent.clatd.fixupLinkProperties(oldLp);
4437 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004438
Paul Jensen992f2522014-04-28 10:33:11 -04004439 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004440 updateMtu(newLp, oldLp);
4441 // TODO - figure out what to do for clat
4442// for (LinkProperties lp : newLp.getStackedLinks()) {
4443// updateMtu(lp, null);
4444// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004445 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004446
Erik Kline94887872016-04-05 13:30:49 +09004447 updateRoutes(newLp, oldLp, netId);
4448 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004449
Paul Jensen3b759822014-05-13 11:44:01 -04004450 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004451 if (isDefaultNetwork(networkAgent)) {
4452 handleApplyDefaultProxy(newLp.getHttpProxy());
4453 } else {
4454 updateProxy(newLp, oldLp, networkAgent);
4455 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004456 // TODO - move this check to cover the whole function
4457 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004458 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004459 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4460 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004461
4462 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004463 }
4464
Lorenzo Colitti95439462014-10-09 13:44:48 +09004465 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4466 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4467 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004468
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004469 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004470 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4471 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004472 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004473 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004474 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004475 }
Paul Jensen992f2522014-04-28 10:33:11 -04004476
4477 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4478 CompareResult<String> interfaceDiff = new CompareResult<String>();
4479 if (oldLp != null) {
4480 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4481 } else if (newLp != null) {
4482 interfaceDiff.added = newLp.getAllInterfaceNames();
4483 }
4484 for (String iface : interfaceDiff.added) {
4485 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004486 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004487 mNetd.addInterfaceToNetwork(iface, netId);
4488 } catch (Exception e) {
4489 loge("Exception adding interface: " + e);
4490 }
4491 }
4492 for (String iface : interfaceDiff.removed) {
4493 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004494 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004495 mNetd.removeInterfaceFromNetwork(iface, netId);
4496 } catch (Exception e) {
4497 loge("Exception removing interface: " + e);
4498 }
4499 }
4500 }
4501
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004502 /**
4503 * Have netd update routes from oldLp to newLp.
4504 * @return true if routes changed between oldLp and newLp
4505 */
4506 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004507 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4508 if (oldLp != null) {
4509 routeDiff = oldLp.compareAllRoutes(newLp);
4510 } else if (newLp != null) {
4511 routeDiff.added = newLp.getAllRoutes();
4512 }
4513
4514 // add routes before removing old in case it helps with continuous connectivity
4515
4516 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4517 for (RouteInfo route : routeDiff.added) {
4518 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004519 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004520 try {
4521 mNetd.addRoute(netId, route);
4522 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004523 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4524 loge("Exception in addRoute for non-gateway: " + e);
4525 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004526 }
4527 }
4528 for (RouteInfo route : routeDiff.added) {
4529 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004530 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004531 try {
4532 mNetd.addRoute(netId, route);
4533 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004534 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4535 loge("Exception in addRoute for gateway: " + e);
4536 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004537 }
4538 }
4539
4540 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004541 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004542 try {
4543 mNetd.removeRoute(netId, route);
4544 } catch (Exception e) {
4545 loge("Exception in removeRoute: " + e);
4546 }
4547 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004548 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004549 }
Erik Kline41368502015-06-17 13:19:54 +09004550
Erik Kline94887872016-04-05 13:30:49 +09004551 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4552 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4553 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004554 }
Erik Kline94887872016-04-05 13:30:49 +09004555
4556 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004557 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004558 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004559 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004560 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4561 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004562 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004563 }
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004564 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4565 if (defaultNai != null && defaultNai.network.netId == netId) {
4566 setDefaultDnsSystemProperties(dnses);
4567 }
Erik Kline94887872016-04-05 13:30:49 +09004568 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004569 }
4570
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004571 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4572 int last = 0;
4573 for (InetAddress dns : dnses) {
4574 ++last;
4575 String key = "net.dns" + last;
4576 String value = dns.getHostAddress();
4577 SystemProperties.set(key, value);
4578 }
4579 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4580 String key = "net.dns" + i;
4581 SystemProperties.set(key, "");
4582 }
4583 mNumDnsEntries = last;
4584 }
4585
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004586 private String getNetworkPermission(NetworkCapabilities nc) {
4587 // TODO: make these permission strings AIDL constants instead.
4588 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4589 return NetworkManagementService.PERMISSION_SYSTEM;
4590 }
4591 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4592 return NetworkManagementService.PERMISSION_NETWORK;
4593 }
4594 return null;
4595 }
4596
Paul Jensen3d194ea2015-06-16 14:27:36 -04004597 /**
4598 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4599 * augmented with any stateful capabilities implied from {@code networkAgent}
4600 * (e.g., validated status and captive portal status).
4601 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004602 * @param oldScore score of the network before any of the changes that prompted us
4603 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004604 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004605 * @param networkCapabilities the new network capabilities.
4606 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004607 private void updateCapabilities(
4608 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004609 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4610 networkCapabilities)) {
4611 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4612 + nai.networkCapabilities + " -> " + networkCapabilities);
4613 }
4614
Paul Jensen3d194ea2015-06-16 14:27:36 -04004615 // Don't modify caller's NetworkCapabilities.
4616 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004617 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004618 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4619 } else {
4620 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4621 }
Paul Jensene0988542015-06-25 15:30:08 -04004622 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004623 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4624 } else {
4625 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4626 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004627 if (nai.isBackgroundNetwork()) {
4628 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4629 } else {
4630 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4631 }
4632
4633 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4634
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004635 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4636 final String newPermission = getNetworkPermission(networkCapabilities);
4637 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004638 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004639 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004640 } catch (RemoteException e) {
4641 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004642 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004643 }
4644
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004645 final NetworkCapabilities prevNc = nai.networkCapabilities;
4646 synchronized (nai) {
4647 nai.networkCapabilities = networkCapabilities;
4648 }
4649 if (nai.getCurrentScore() == oldScore &&
4650 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4651 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4652 // the change we're processing can't affect any requests, it can only affect the listens
4653 // on this network. We might have been called by rematchNetworkAndRequests when a
4654 // network changed foreground state.
4655 processListenRequests(nai, true);
4656 } else {
4657 // If the requestable capabilities have changed or the score changed, we can't have been
4658 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004659 rematchAllNetworksAndRequests(nai, oldScore);
4660 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004661 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004662 }
4663
Paul Jensenc8b9a742014-09-30 15:37:41 -04004664 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004665 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4666 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004667 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004668 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004669 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4670 }
4671 }
4672
Robert Greenwalt7b816022014-04-18 15:25:25 -07004673 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4674 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004675 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004676 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4677 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004678 }
4679 }
4680
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004681 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4682 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004683 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004684 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004685 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4686 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004687 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004688 sendIntent(nri.mPendingIntent, intent);
4689 }
4690 // else not handled
4691 }
4692
4693 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4694 mPendingIntentWakeLock.acquire();
4695 try {
4696 if (DBG) log("Sending " + pendingIntent);
4697 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4698 } catch (PendingIntent.CanceledException e) {
4699 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4700 mPendingIntentWakeLock.release();
4701 releasePendingNetworkRequest(pendingIntent);
4702 }
4703 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4704 }
4705
4706 @Override
4707 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4708 String resultData, Bundle resultExtras) {
4709 if (DBG) log("Finished sending " + pendingIntent);
4710 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004711 // Release with a delay so the receiving client has an opportunity to put in its
4712 // own request.
4713 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004714 }
4715
Robert Greenwalt9258c642014-03-26 16:47:06 -07004716 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004717 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004718 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004719 Bundle bundle = new Bundle();
4720 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4721 new NetworkRequest(nri.request));
4722 Message msg = Message.obtain();
4723 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4724 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4725 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4726 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004727 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004728 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004729 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004730 break;
4731 }
4732 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4733 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4734 new NetworkCapabilities(networkAgent.networkCapabilities));
4735 break;
4736 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004737 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004738 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4739 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004740 break;
4741 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004742 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004743 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004744 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004745 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004746 if (VDBG) {
4747 log("sending notification " + notifyTypeToName(notificationType) +
4748 " for " + nri.request);
4749 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004750 nri.messenger.send(msg);
4751 } catch (RemoteException e) {
4752 // may occur naturally in the race of binder death.
4753 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4754 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004755 }
4756
Paul Jensenc8b9a742014-09-30 15:37:41 -04004757 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004758 if (nai.numRequestNetworkRequests() != 0) {
4759 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4760 NetworkRequest nr = nai.requestAt(i);
4761 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004762 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004763 loge("Dead network still had at least " + nr);
4764 break;
4765 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004766 }
4767 nai.asyncChannel.disconnect();
4768 }
4769
Robert Greenwalt7b816022014-04-18 15:25:25 -07004770 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4771 if (oldNetwork == null) {
4772 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4773 return;
4774 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004775 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004776
4777 // If we get here it means that the last linger timeout for this network expired. So there
4778 // must be no other active linger timers, and we must stop lingering.
4779 oldNetwork.clearLingerState();
4780
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004781 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004782 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004783 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004784 } else {
4785 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004786 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4787 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004788 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004789 }
4790
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004791 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004792 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004793 setupDataActivityTracking(newNetwork);
4794 try {
4795 mNetd.setDefaultNetId(newNetwork.network.netId);
4796 } catch (Exception e) {
4797 loge("Exception setting default network :" + e);
4798 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004799 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004800 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004801 updateTcpBufferSizes(newNetwork);
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004802 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004803 }
4804
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004805 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004806 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4807 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4808 NetworkRequest nr = nri.request;
4809 if (!nr.isListen()) continue;
4810 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4811 nai.removeRequest(nri.request.requestId);
4812 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4813 }
4814 }
4815
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004816 if (capabilitiesChanged) {
4817 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4818 }
4819
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004820 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4821 NetworkRequest nr = nri.request;
4822 if (!nr.isListen()) continue;
4823 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4824 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004825 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004826 }
4827 }
4828 }
4829
Paul Jensen2161a8e2014-09-11 11:00:39 -04004830 // Handles a network appearing or improving its score.
4831 //
4832 // - Evaluates all current NetworkRequests that can be
4833 // satisfied by newNetwork, and reassigns to newNetwork
4834 // any such requests for which newNetwork is the best.
4835 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004836 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004837 // needed. A network is needed if it is the best network for
4838 // one or more NetworkRequests, or if it is a VPN.
4839 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004840 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004841 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004842 //
4843 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4844 // networks that have no chance (i.e. even if validated)
4845 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004846 //
4847 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4848 // it does not remove NetworkRequests that other Networks could better satisfy.
4849 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4850 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4851 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004852 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004853 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004854 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4855 // performed to tear down unvalidated networks that have no chance (i.e. even if
4856 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004857 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004858 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004859 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004860 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004861 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004862 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004863
4864 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4865 final int score = newNetwork.getCurrentScore();
4866
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004867 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004868
Paul Jensen2161a8e2014-09-11 11:00:39 -04004869 // Find and migrate to this Network any NetworkRequests for
4870 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004871 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004872 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004873 NetworkCapabilities nc = newNetwork.networkCapabilities;
4874 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004875 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004876 // Process requests in the first pass and listens in the second pass. This allows us to
4877 // change a network's capabilities depending on which requests it has. This is only
4878 // correct if the change in capabilities doesn't affect whether the network satisfies
4879 // requests or not, and doesn't affect the network's score.
4880 if (nri.request.isListen()) continue;
4881
Paul Jensencf4c2c62015-07-01 14:16:32 -04004882 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4883 final boolean satisfies = newNetwork.satisfies(nri.request);
4884 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004885 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004886 log("Network " + newNetwork.name() + " was already satisfying" +
4887 " request " + nri.request.requestId + ". No change.");
4888 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004889 keep = true;
4890 continue;
4891 }
4892
4893 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004894 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004895 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004896 // next check if it's better than any current network we're using for
4897 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004898 if (VDBG) {
4899 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004900 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004901 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004902 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004903 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004904 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004905 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004906 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004907 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004908 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004909 affectedNetworks.add(currentNetwork);
4910 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004911 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004912 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004913 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004914 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004915 if (!newNetwork.addRequest(nri.request)) {
4916 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4917 }
4918 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004919 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004920 // Tell NetworkFactories about the new score, so they can stop
4921 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004922 // TODO - this could get expensive if we have alot of requests for this
4923 // network. Think about if there is a way to reduce this. Push
4924 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004925 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004926 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004927 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004928 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004929 if (currentNetwork != null) {
4930 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4931 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004932 }
4933 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004934 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004935 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4936 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004937 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004938 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4939 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4940 // This means this code doesn't have to handle the case where "currentNetwork" no
4941 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4942 if (DBG) {
4943 log("Network " + newNetwork.name() + " stopped satisfying" +
4944 " request " + nri.request.requestId);
4945 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004946 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004947 if (currentNetwork == newNetwork) {
4948 mNetworkForRequestId.remove(nri.request.requestId);
4949 sendUpdatedScoreToFactories(nri.request, 0);
4950 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004951 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4952 newNetwork.name() +
4953 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004954 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004955 // TODO: Technically, sending CALLBACK_LOST here is
4956 // incorrect if there is a replacement network currently
4957 // connected that can satisfy nri, which is a request
4958 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004959 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4960 // so this code is only incorrect for a network that loses
4961 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004962 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004963 }
4964 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004965 if (isNewDefault) {
4966 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004967 makeDefault(newNetwork);
4968 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4969 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004970 synchronized (ConnectivityService.this) {
4971 // have a new default network, release the transition wakelock in
4972 // a second if it's held. The second pause is to allow apps
4973 // to reconnect over the new network
4974 if (mNetTransitionWakeLock.isHeld()) {
4975 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4976 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4977 mNetTransitionWakeLockSerialNumber, 0),
4978 1000);
4979 }
4980 }
4981 }
4982
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004983 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
4984 Slog.wtf(TAG, String.format(
4985 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
4986 nc, newNetwork.networkCapabilities));
4987 }
4988 if (newNetwork.getCurrentScore() != score) {
4989 Slog.wtf(TAG, String.format(
4990 "BUG: %s changed score during rematch: %d -> %d",
4991 score, newNetwork.getCurrentScore()));
4992 }
4993
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004994 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004995 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
4996 // If the network went from background to foreground or vice versa, we need to update
4997 // its foreground state. It is safe to do this after rematching the requests because
4998 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
4999 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005000 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005001 } else {
5002 processListenRequests(newNetwork, false);
5003 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005004
Paul Jensencf4c2c62015-07-01 14:16:32 -04005005 // do this after the default net is switched, but
5006 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005007 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005008
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005009 // Linger any networks that are no longer needed. This should be done after sending the
5010 // available callback for newNetwork.
5011 for (NetworkAgentInfo nai : affectedNetworks) {
5012 updateLingerState(nai, now);
5013 }
5014 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5015 // does not need to be done in any particular order.
5016 updateLingerState(newNetwork, now);
5017
Paul Jensencf4c2c62015-07-01 14:16:32 -04005018 if (isNewDefault) {
5019 // Maintain the illusion: since the legacy API only
5020 // understands one network at a time, we must pretend
5021 // that the current default network disconnected before
5022 // the new one connected.
5023 if (oldDefaultNetwork != null) {
5024 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5025 oldDefaultNetwork, true);
5026 }
5027 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5028 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5029 notifyLockdownVpn(newNetwork);
5030 }
5031
Robert Greenwalt7b816022014-04-18 15:25:25 -07005032 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005033 // Notify battery stats service about this network, both the normal
5034 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005035 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005036 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005037 final IBatteryStats bs = BatteryStatsService.getService();
5038 final int type = newNetwork.networkInfo.getType();
5039
5040 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5041 bs.noteNetworkInterfaceType(baseIface, type);
5042 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5043 final String stackedIface = stacked.getInterfaceName();
5044 bs.noteNetworkInterfaceType(stackedIface, type);
5045 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5046 }
5047 } catch (RemoteException ignored) {
5048 }
5049
Robert Greenwalt152ed372014-12-17 17:19:53 -08005050 // This has to happen after the notifyNetworkCallbacks as that tickles each
5051 // ConnectivityManager instance so that legacy requests correctly bind dns
5052 // requests to this network. The legacy users are listening for this bcast
5053 // and will generally do a dns request so they can ensureRouteToHost and if
5054 // they do that before the callbacks happen they'll use the default network.
5055 //
5056 // TODO: Is there still a race here? We send the broadcast
5057 // after sending the callback, but if the app can receive the
5058 // broadcast before the callback, it might still break.
5059 //
5060 // This *does* introduce a race where if the user uses the new api
5061 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5062 // they may get old info. Reverse this after the old startUsing api is removed.
5063 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005064 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5065 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005066 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005067 // legacy type tracker filters out repeat adds
5068 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5069 }
5070 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005071
5072 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5073 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5074 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5075 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5076 if (newNetwork.isVPN()) {
5077 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5078 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005079 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005080 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5081 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005082 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005083 if (nai.getLingerExpiry() > 0) {
5084 // This network has active linger timers and no requests, but is not
5085 // lingering. Linger it.
5086 //
5087 // One way (the only way?) this can happen if this network is unvalidated
5088 // and became unneeded due to another network improving its score to the
5089 // point where this network will no longer be able to satisfy any requests
5090 // even if it validates.
5091 updateLingerState(nai, now);
5092 } else {
5093 if (DBG) log("Reaping " + nai.name());
5094 teardownUnneededNetwork(nai);
5095 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005096 }
5097 }
5098 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005099 }
5100
Paul Jensen1c7ba022015-06-16 14:27:36 -04005101 /**
5102 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5103 * being disconnected.
5104 * @param changed If only one Network's score or capabilities have been modified since the last
5105 * time this function was called, pass this Network in this argument, otherwise pass
5106 * null.
5107 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5108 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5109 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5110 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5111 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005112 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005113 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005114 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5115 // to avoid the slowness. It is not simply enough to process just "changed", for
5116 // example in the case where "changed"'s score decreases and another network should begin
5117 // satifying a NetworkRequest that "changed" currently satisfies.
5118
5119 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5120 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5121 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005122 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005123 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005124 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005125 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005126 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5127 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5128 // Rematch higher scoring networks first to prevent requests first matching a lower
5129 // scoring network and then a higher scoring network, which could produce multiple
5130 // callbacks and inadvertently unlinger networks.
5131 Arrays.sort(nais);
5132 for (NetworkAgentInfo nai : nais) {
5133 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005134 // Only reap the last time through the loop. Reaping before all rematching
5135 // is complete could incorrectly teardown a network that hasn't yet been
5136 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005137 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005138 : ReapUnvalidatedNetworks.REAP,
5139 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005140 }
5141 }
5142 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005143
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005144 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005145 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005146 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005147 // For now only update icons for default connection.
5148 // TODO: Update WiFi and cellular icons separately. b/17237507
5149 if (!isDefaultNetwork(nai)) return;
5150
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005151 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005152 // Don't repeat publish.
5153 if (newInetCondition == mDefaultInetConditionPublished) return;
5154
5155 mDefaultInetConditionPublished = newInetCondition;
5156 sendInetConditionBroadcast(nai.networkInfo);
5157 }
5158
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005159 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5160 if (mLockdownTracker != null) {
5161 if (nai != null && nai.isVPN()) {
5162 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5163 } else {
5164 mLockdownTracker.onNetworkInfoChanged();
5165 }
5166 }
5167 }
5168
Robert Greenwalt7b816022014-04-18 15:25:25 -07005169 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005170 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005171 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005172 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005173 synchronized (networkAgent) {
5174 oldInfo = networkAgent.networkInfo;
5175 networkAgent.networkInfo = newInfo;
5176 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005177 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005178
5179 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005180 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5181 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5182 notifyIfacesChangedForNetworkStats();
5183 } else if (VDBG) log("ignoring duplicate network state non-change");
5184 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005185 return;
5186 }
5187 if (DBG) {
5188 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5189 (oldInfo == null ? "null" : oldInfo.getState()) +
5190 " to " + state);
5191 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005192
Robin Lee585e2482016-05-01 23:00:00 +01005193 if (!networkAgent.created
5194 && (state == NetworkInfo.State.CONNECTED
5195 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005196
5197 // A network that has just connected has zero requests and is thus a foreground network.
5198 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5199
Robert Greenwalt7b816022014-04-18 15:25:25 -07005200 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005201 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005202 if (networkAgent.isVPN()) {
5203 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005204 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5205 (networkAgent.networkMisc == null ||
5206 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005207 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005208 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005209 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005210 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005211 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005212 loge("Error creating network " + networkAgent.network.netId + ": "
5213 + e.getMessage());
5214 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005215 }
Paul Jenseneec75412014-08-04 12:21:19 -04005216 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005217 }
5218
5219 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5220 networkAgent.everConnected = true;
5221
Robert Greenwalt7b816022014-04-18 15:25:25 -07005222 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005223 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005224
Paul Jensenca8f16a2014-05-09 12:47:55 -04005225 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005226 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005227
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005228 if (networkAgent.isVPN()) {
5229 // Temporarily disable the default proxy (not global).
5230 synchronized (mProxyLock) {
5231 if (!mDefaultProxyDisabled) {
5232 mDefaultProxyDisabled = true;
5233 if (mGlobalProxy == null && mDefaultProxy != null) {
5234 sendProxyBroadcast(null);
5235 }
5236 }
5237 }
5238 // TODO: support proxy per network.
5239 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005240
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005241 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5242 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5243 // capabilities, so it only needs to be done once on initial connect, not every time the
5244 // network's capabilities change. Note that we do this before rematching the network,
5245 // so we could decide to tear it down immediately afterwards. That's fine though - on
5246 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5247 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005248 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005249
Paul Jensen2161a8e2014-09-11 11:00:39 -04005250 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005251 final long now = SystemClock.elapsedRealtime();
5252 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005253
5254 // This has to happen after matching the requests, because callbacks are just requests.
5255 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005256 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005257 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005258 if (networkAgent.isVPN()) {
5259 synchronized (mProxyLock) {
5260 if (mDefaultProxyDisabled) {
5261 mDefaultProxyDisabled = false;
5262 if (mGlobalProxy == null && mDefaultProxy != null) {
5263 sendProxyBroadcast(mDefaultProxy);
5264 }
5265 }
5266 }
5267 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005268 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5269 state == NetworkInfo.State.SUSPENDED) {
5270 // going into or coming out of SUSPEND: rescore and notify
5271 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005272 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005273 }
5274 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5275 ConnectivityManager.CALLBACK_SUSPENDED :
5276 ConnectivityManager.CALLBACK_RESUMED));
5277 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005278 }
5279 }
5280
Robert Greenwaltac96c522014-06-03 16:43:57 -07005281 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005282 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005283 if (score < 0) {
5284 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5285 "). Bumping score to min of 0");
5286 score = 0;
5287 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005288
Paul Jensen2161a8e2014-09-11 11:00:39 -04005289 final int oldScore = nai.getCurrentScore();
5290 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005291
Paul Jensen85cf78e2015-06-25 13:25:07 -04005292 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005293
Paul Jensenc8b9a742014-09-30 15:37:41 -04005294 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005295 }
5296
Erik Klinec75d4fa2017-02-15 19:59:17 +09005297 // Notify only this one new request of the current state. Transfer all the
5298 // current state by calling NetworkCapabilities and LinkProperties callbacks
5299 // so that callers can be guaranteed to have as close to atomicity in state
5300 // transfer as can be supported by this current API.
5301 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005302 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005303 if (nri.mPendingIntent != null) {
5304 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5305 // Attempt no subsequent state pushes where intents are involved.
5306 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005307 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005308
5309 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5310 // Whether a network is currently suspended is also an important
5311 // element of state to be transferred (it would not otherwise be
5312 // delivered by any currently available mechanism).
5313 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5314 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5315 }
5316 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5317 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005318 }
5319
Robert Greenwalt8d482522015-06-24 13:23:42 -07005320 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005321 // The NetworkInfo we actually send out has no bearing on the real
5322 // state of affairs. For example, if the default connection is mobile,
5323 // and a request for HIPRI has just gone away, we need to pretend that
5324 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5325 // the state to DISCONNECTED, even though the network is of type MOBILE
5326 // and is still connected.
5327 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5328 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005329 if (state != DetailedState.DISCONNECTED) {
5330 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005331 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005332 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005333 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005334 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5335 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5336 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5337 if (info.isFailover()) {
5338 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5339 nai.networkInfo.setFailover(false);
5340 }
5341 if (info.getReason() != null) {
5342 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5343 }
5344 if (info.getExtraInfo() != null) {
5345 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5346 }
5347 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005348 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005349 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005350 if (newDefaultAgent != null) {
5351 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5352 newDefaultAgent.networkInfo);
5353 } else {
5354 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5355 }
5356 }
5357 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5358 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005359 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005360 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005361 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005362 }
5363 }
5364 }
5365
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005366 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005367 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005368 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5369 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005370 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5371 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005372 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5373 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005374 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005375 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005376 } else {
5377 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5378 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005379 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005380 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005381
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005382 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5383 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5384 }
5385
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005386 private String notifyTypeToName(int notifyType) {
5387 switch (notifyType) {
5388 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5389 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5390 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5391 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5392 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5393 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5394 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5395 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5396 }
5397 return "UNKNOWN";
5398 }
5399
Jeff Sharkey69736342014-12-08 14:50:12 -08005400 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005401 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5402 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005403 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005404 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005405 try {
5406 mStatsService.forceUpdateIfaces();
5407 } catch (Exception ignored) {
5408 }
5409 }
5410
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005411 @Override
5412 public boolean addVpnAddress(String address, int prefixLength) {
5413 throwIfLockdownEnabled();
5414 int user = UserHandle.getUserId(Binder.getCallingUid());
5415 synchronized (mVpns) {
5416 return mVpns.get(user).addAddress(address, prefixLength);
5417 }
5418 }
5419
5420 @Override
5421 public boolean removeVpnAddress(String address, int prefixLength) {
5422 throwIfLockdownEnabled();
5423 int user = UserHandle.getUserId(Binder.getCallingUid());
5424 synchronized (mVpns) {
5425 return mVpns.get(user).removeAddress(address, prefixLength);
5426 }
5427 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005428
5429 @Override
5430 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5431 throwIfLockdownEnabled();
5432 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005433 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005434 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005435 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005436 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005437 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005438 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005439 }
5440 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005441 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005442
5443 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005444 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005445 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005446 }
5447
5448 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005449 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5450 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5451 enforceKeepalivePermission();
5452 mKeepaliveTracker.startNattKeepalive(
5453 getNetworkAgentInfoForNetwork(network),
5454 intervalSeconds, messenger, binder,
5455 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5456 }
5457
5458 @Override
5459 public void stopKeepalive(Network network, int slot) {
5460 mHandler.sendMessage(mHandler.obtainMessage(
5461 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5462 }
5463
5464 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005465 public void factoryReset() {
5466 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005467
5468 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5469 return;
5470 }
5471
Robin Lee3b3dd942015-05-12 18:14:58 +01005472 final int userId = UserHandle.getCallingUserId();
5473
Stuart Scottf1fb3972015-04-02 18:00:02 -07005474 // Turn airplane mode off
5475 setAirplaneMode(false);
5476
Stuart Scotte3e314d2015-04-20 14:07:45 -07005477 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5478 // Untether
5479 for (String tether : getTetheredIfaces()) {
5480 untether(tether);
5481 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005482 }
5483
Stuart Scotte3e314d2015-04-20 14:07:45 -07005484 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005485 // Remove always-on package
5486 synchronized (mVpns) {
5487 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5488 if (alwaysOnPackage != null) {
5489 setAlwaysOnVpnPackage(userId, null, false);
5490 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5491 }
5492 }
5493
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005494 // Turn Always-on VPN off
5495 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5496 final long ident = Binder.clearCallingIdentity();
5497 try {
5498 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5499 mLockdownEnabled = false;
5500 setLockdownTracker(null);
5501 } finally {
5502 Binder.restoreCallingIdentity(ident);
5503 }
5504 }
5505
Stuart Scotte3e314d2015-04-20 14:07:45 -07005506 // Turn VPN off
5507 VpnConfig vpnConfig = getVpnConfig(userId);
5508 if (vpnConfig != null) {
5509 if (vpnConfig.legacy) {
5510 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5511 } else {
5512 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5513 // in the future without user intervention.
5514 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005515
Victor Changb04a5ea2016-05-30 20:36:30 +01005516 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005517 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005518 }
5519 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005520
5521 Settings.Global.putString(mContext.getContentResolver(),
5522 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005523 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005524
5525 @VisibleForTesting
5526 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5527 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5528 return new NetworkMonitor(context, handler, nai, defaultRequest);
5529 }
Erik Kline48f12f22016-04-14 17:30:59 +09005530
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005531 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005532 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5533 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005534 }
5535
5536 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005537 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5538 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5539 }
5540
Hugo Benichicfddd682016-05-31 16:28:06 +09005541 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005542 int newNetid = NETID_UNSET;
5543 int prevNetid = NETID_UNSET;
5544 int[] transports = new int[0];
5545 boolean hadIPv4 = false;
5546 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005547
Hugo Benichi5f16f762016-04-20 12:09:33 +09005548 if (newNai != null) {
5549 newNetid = newNai.network.netId;
5550 transports = newNai.networkCapabilities.getTransportTypes();
5551 }
5552 if (prevNai != null) {
5553 prevNetid = prevNai.network.netId;
5554 final LinkProperties lp = prevNai.linkProperties;
5555 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5556 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5557 }
5558
Hugo Benichicfddd682016-05-31 16:28:06 +09005559 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5560 }
5561
5562 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5563 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005564 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565}