blob: 5030dce7cbf97247dadf5c6fded3e19dbc521bca [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;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090022import static android.net.ConnectivityManager.TYPE_ETHERNET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070023import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070024import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070025import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070026import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040027import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090028import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090029import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060032import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090033import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060034import static android.net.NetworkCapabilities.TRANSPORT_VPN;
35
Hugo Benichia0385682017-03-22 17:07:57 +090036import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060037
Wenchao Tongf5ea3402015-03-04 13:26:38 -080038import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080039import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090040import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070041import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070042import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.ContentResolver;
44import android.content.Context;
45import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070046import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070047import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070048import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090050import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070052import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070053import android.net.INetworkPolicyListener;
54import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070055import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080056import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070057import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010058import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070059import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070060import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070061import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070062import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070064import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070065import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090066import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070067import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070068import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070069import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070070import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070071import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +000072import android.net.NetworkWatchlistManager;
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;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060078import android.net.VpnService;
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;
Hugo Benichidba33db2017-03-23 22:40:44 +090094import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070095import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070096import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070097import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080098import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090099import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900100import android.os.ServiceSpecificException;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900101import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700102import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400103import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700105import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700106import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700107import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700108import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700109import android.util.LocalLog;
110import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600111import android.util.Log;
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;
Erik Kline1742fe12017-12-13 19:40:49 +0900135import com.android.server.connectivity.DnsManager;
Erik Klinea24d4592018-01-11 21:07:29 +0900136import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
Hugo Benichi64901e52017-10-19 14:42:40 +0900137import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900138import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100139import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700140import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700141import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600142import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400143import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900144import com.android.server.connectivity.NetworkNotificationManager;
145import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400146import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700147import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800148import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700149import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100150import com.android.server.connectivity.tethering.TetheringDependencies;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700151import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700152import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900153import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700154import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600155
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700156import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700157
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700158import org.xmlpull.v1.XmlPullParser;
159import org.xmlpull.v1.XmlPullParserException;
160
161import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700163import java.io.FileNotFoundException;
164import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700165import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700167import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700168import java.net.InetAddress;
169import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700170import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700171import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700172import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700173import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700174import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700175import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700176import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700177import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700178import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600179import java.util.SortedSet;
180import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181
182/**
183 * @hide
184 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800185public class ConnectivityService extends IConnectivityManager.Stub
186 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900187 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
Erik Kline7747fd42017-05-12 16:52:48 +0900189 public static final String DIAG_ARG = "--diag";
190 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900191 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900192
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900193 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700194 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195
Jake Hamby786e71a2014-02-06 14:43:50 -0800196 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900197 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700198
Jeff Sharkey899223b2012-08-04 15:24:58 -0700199 // TODO: create better separation between radio types and network types
200
Robert Greenwalt42acef32009-08-12 16:08:25 -0700201 // how long to wait before switching back to a radio's default network
202 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
203 // system property that can override the above value
204 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
205 "android.telephony.apn-restore";
206
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900207 // How long to wait before putting up a "This network doesn't have an Internet connection,
208 // connect anyway?" dialog after the user selects a network that doesn't validate.
209 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
210
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900211 // Default to 30s linger time-out. Modifiable only for testing.
212 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
213 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
214 @VisibleForTesting
215 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
216
Jeremy Joslin79294842014-12-03 17:15:28 -0800217 // How long to delay to removal of a pending intent based request.
218 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
219 private final int mReleasePendingIntentDelayMs;
220
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900221 private MockableSystemProperties mSystemProperties;
222
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800223 private Tethering mTethering;
224
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700225 private final PermissionMonitor mPermissionMonitor;
226
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700227 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700228
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700229 @GuardedBy("mVpns")
230 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700231
Hugo Benichi69744342017-11-27 10:57:16 +0900232 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
233 // a direct call to LockdownVpnTracker.isEnabled().
234 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700235 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900236 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700237 private LockdownVpnTracker mLockdownTracker;
238
Erik Klineda4bfa82015-04-30 12:58:40 +0900239 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700241 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700242 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700245 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700247 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800248 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700249 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900250 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700251
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700252 private String mCurrentTcpBufferSizes;
253
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700254 private static final int ENABLED = 1;
255 private static final int DISABLED = 0;
256
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900257 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900258 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
259 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900260
Paul Jensenb10e37f2014-11-25 12:33:08 -0500261 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400262 // Tear down networks that have no chance (e.g. even if validated) of becoming
263 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500264 // all networks have been rematched against all NetworkRequests.
265 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400266 // Don't reap networks. This should be passed when some networks have not yet been
267 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500268 DONT_REAP
269 };
270
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900271 private enum UnneededFor {
272 LINGER, // Determine whether this network is unneeded and should be lingered.
273 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
274 }
275
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700276 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700277 * used internally to change our mobile data enabled flag
278 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700279 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700280
281 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700282 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700283 * from one net to another. Clear happens when we get a new
284 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
285 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700286 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700287 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700288
Robert Greenwalt434203a2010-10-11 16:00:27 -0700289 /**
290 * used internally to reload global proxy settings
291 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700292 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700293
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700294 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400295 * PAC manager has received new port.
296 */
297 private static final int EVENT_PROXY_HAS_CHANGED = 16;
298
Robert Greenwalte049c232014-04-11 15:53:27 -0700299 /**
300 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700301 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700302 */
303 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
304
Robert Greenwalt7b816022014-04-18 15:25:25 -0700305 /**
306 * used internally when registering NetworkAgents
307 * obj = Messenger
308 */
309 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
310
Robert Greenwalt9258c642014-03-26 16:47:06 -0700311 /**
312 * used to add a network request
313 * includes a NetworkRequestInfo
314 */
315 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
316
317 /**
318 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900319 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700320 * cancel it.
321 * includes a NetworkRequestInfo
322 */
323 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
324
325 /**
326 * used to add a network listener - no request
327 * includes a NetworkRequestInfo
328 */
329 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
330
331 /**
332 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400333 * arg1 = UID of caller
334 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700335 */
336 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
337
Robert Greenwalta67be032014-05-16 15:49:14 -0700338 /**
339 * used internally when registering NetworkFactories
340 * obj = Messenger
341 */
342 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
343
Robert Greenwalt27711812014-06-25 16:45:57 -0700344 /**
345 * used internally to expire a wakelock when transitioning
346 * from one net to another. Expire happens when we fail to find
347 * a new network (typically after 1 minute) -
348 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
349 * a replacement network.
350 */
351 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
352
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700353 /**
354 * Used internally to indicate the system is ready.
355 */
356 private static final int EVENT_SYSTEM_READY = 25;
357
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800358 /**
359 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400360 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800361 */
362 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
363
364 /**
365 * used to remove a pending intent and its associated network request.
366 * arg1 = UID of caller
367 * obj = PendingIntent
368 */
369 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
370
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900371 /**
372 * used to specify whether a network should be used even if unvalidated.
373 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
374 * arg2 = whether to remember this choice in the future (1 or 0)
375 * obj = network
376 */
377 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
378
379 /**
380 * used to ask the user to confirm a connection to an unvalidated network.
381 * obj = network
382 */
383 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700384
Erik Klineda4bfa82015-04-30 12:58:40 +0900385 /**
386 * used internally to (re)configure mobile data always-on settings.
387 */
388 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
389
Paul Jensen694f2b82015-06-17 14:15:39 -0400390 /**
391 * used to add a network listener with a pending intent
392 * obj = NetworkRequestInfo
393 */
394 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
395
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900396 /**
397 * used to specify whether a network should not be penalized when it becomes unvalidated.
398 */
399 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
400
401 /**
402 * used to trigger revalidation of a network.
403 */
404 private static final int EVENT_REVALIDATE_NETWORK = 36;
405
Erik Klinea24d4592018-01-11 21:07:29 +0900406 // Handle changes in Private DNS settings.
407 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
408
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900409 private static String eventName(int what) {
410 return sMagicDecoderRing.get(what, Integer.toString(what));
411 }
412
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900413 /** Handler thread used for both of the handlers below. */
414 @VisibleForTesting
415 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700416 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700417 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700418 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700419 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900420 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700421
Mike Lockwood0f79b542009-08-14 14:18:49 -0400422 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800423 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400424
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700425 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700426 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800427 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700428
Robert Greenwalt434203a2010-10-11 16:00:27 -0700429 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400430 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700431 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700432 private boolean mDefaultProxyDisabled = false;
433
Robert Greenwalt434203a2010-10-11 16:00:27 -0700434 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400435 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700436
Jason Monk602b2322013-07-03 17:04:33 -0400437 private PacManager mPacManager = null;
438
Erik Klineda4bfa82015-04-30 12:58:40 +0900439 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700440
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400441 private UserManager mUserManager;
442
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700443 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700444 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700445
Robert Greenwalt50393202011-06-21 17:26:14 -0700446 // the set of network types that can only be enabled by system/sig apps
447 List mProtectedNetworks;
448
John Spurlockbf991a82013-06-24 14:20:23 -0400449 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700450
Wink Savilleab9321d2013-06-29 21:10:57 -0700451 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400452
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900453 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900454 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900455 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900456
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700457 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
458 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700459 private final static int MAX_NET_ID = 65535;
460 private int mNextNetId = MIN_NET_ID;
461
Robert Greenwalt34524f02014-05-18 16:22:10 -0700462 // sequence number of NetworkRequests
463 private int mNextNetworkRequestId = 1;
464
Erik Kline7523eb32015-07-09 18:24:03 +0900465 // NetworkRequest activity String log entries.
466 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
467 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
468
Hugo Benichic2ae2872016-07-11 11:05:12 +0900469 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900470 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900471 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
472
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900473 private static final int MAX_WAKELOCK_LOGS = 20;
474 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900475 private int mTotalWakelockAcquisitions = 0;
476 private int mTotalWakelockReleases = 0;
477 private long mTotalWakelockDurationMs = 0;
478 private long mMaxWakelockDurationMs = 0;
479 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900480
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700481 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
482 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400483 private static class ValidationLog {
484 final Network mNetwork;
485 final String mNetworkExtraInfo;
486 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700487
Paul Jensen0808eb82016-06-03 13:51:21 -0400488 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
489 mNetwork = network;
490 mNetworkExtraInfo = networkExtraInfo;
491 mLog = log;
492 }
493 }
494 private final ArrayDeque<ValidationLog> mValidationLogs =
495 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
496
497 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900498 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700499 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
500 mValidationLogs.removeLast();
501 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400502 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700503 }
504 }
505
Hugo Benichif9fdf872016-07-28 17:53:06 +0900506 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900507
Erik Kline065ab6e2016-10-02 18:02:14 +0900508 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900509 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900510
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700511 /**
512 * Implements support for the legacy "one network per network type" model.
513 *
514 * We used to have a static array of NetworkStateTrackers, one for each
515 * network type, but that doesn't work any more now that we can have,
516 * for example, more that one wifi network. This class stores all the
517 * NetworkAgentInfo objects that support a given type, but the legacy
518 * API will only see the first one.
519 *
520 * It serves two main purposes:
521 *
522 * 1. Provide information about "the network for a given type" (since this
523 * API only supports one).
524 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
525 * the first network for a given type changes, or if the default network
526 * changes.
527 */
528 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900529
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900530 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900531 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900532
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700533 /**
534 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
535 * Each list holds references to all NetworkAgentInfos that are used to
536 * satisfy requests for that network type.
537 *
538 * This array is built out at startup such that an unsupported network
539 * doesn't get an ArrayList instance, making this a tristate:
540 * unsupported, supported but not active and active.
541 *
542 * The actual lists are populated when we scan the network types that
543 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900544 *
545 * Threading model:
546 * - addSupportedType() is only called in the constructor
547 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
548 * They are therefore not thread-safe with respect to each other.
549 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
550 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
551 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700552 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900553 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700554
555 public LegacyTypeTracker() {
556 mTypeLists = (ArrayList<NetworkAgentInfo>[])
557 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
558 }
559
560 public void addSupportedType(int type) {
561 if (mTypeLists[type] != null) {
562 throw new IllegalStateException(
563 "legacy list for type " + type + "already initialized");
564 }
565 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
566 }
567
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700568 public boolean isTypeSupported(int type) {
569 return isNetworkTypeValid(type) && mTypeLists[type] != null;
570 }
571
572 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900573 synchronized (mTypeLists) {
574 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
575 return mTypeLists[type].get(0);
576 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700577 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900578 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700579 }
580
Robert Greenwalt8d482522015-06-24 13:23:42 -0700581 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900582 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900583 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700584 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900585 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900586 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900587 }
588 }
589
590 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700591 public void add(int type, NetworkAgentInfo nai) {
592 if (!isTypeSupported(type)) {
593 return; // Invalid network type.
594 }
595 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
596
597 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
598 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700599 return;
600 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900601 synchronized (mTypeLists) {
602 list.add(nai);
603 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900604
605 // 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 +0900606 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900607 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700608 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
609 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700610 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700611 }
612
Lorenzo Colittia793a672014-07-31 23:20:17 +0900613 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900614 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900615 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
616 if (list == null || list.isEmpty()) {
617 return;
618 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900619 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900620
Hugo Benichi78caa2582016-06-21 09:48:07 +0900621 synchronized (mTypeLists) {
622 if (!list.remove(nai)) {
623 return;
624 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900625 }
626
Robert Greenwalt8d482522015-06-24 13:23:42 -0700627 final DetailedState state = DetailedState.DISCONNECTED;
628
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900629 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700630 maybeLogBroadcast(nai, state, type, wasDefault);
631 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900632 }
633
634 if (!list.isEmpty() && wasFirstNetwork) {
635 if (DBG) log("Other network available for type " + type +
636 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900637 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700638 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
639 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900640 }
641 }
642
643 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900644 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
645 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700646 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900647 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700648 }
649 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700650
Robert Greenwalt8d482522015-06-24 13:23:42 -0700651 // send out another legacy broadcast - currently only used for suspend/unsuspend
652 // toggle
653 public void update(NetworkAgentInfo nai) {
654 final boolean isDefault = isDefaultNetwork(nai);
655 final DetailedState state = nai.networkInfo.getDetailedState();
656 for (int type = 0; type < mTypeLists.length; type++) {
657 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700658 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900659 final boolean isFirst = contains && (nai == list.get(0));
660 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700661 maybeLogBroadcast(nai, state, type, isDefault);
662 sendLegacyNetworkBroadcast(nai, state, type);
663 }
664 }
665 }
666
Lorenzo Colittia793a672014-07-31 23:20:17 +0900667 private String naiToString(NetworkAgentInfo nai) {
668 String name = (nai != null) ? nai.name() : "null";
669 String state = (nai.networkInfo != null) ?
670 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
671 "???/???";
672 return name + " " + state;
673 }
674
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700675 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900676 pw.println("mLegacyTypeTracker:");
677 pw.increaseIndent();
678 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700679 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900680 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700681 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900682 pw.println();
683 pw.println("Current state:");
684 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900685 synchronized (mTypeLists) {
686 for (int type = 0; type < mTypeLists.length; type++) {
687 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
688 for (NetworkAgentInfo nai : mTypeLists[type]) {
689 pw.println(type + " " + naiToString(nai));
690 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900691 }
692 }
693 pw.decreaseIndent();
694 pw.decreaseIndent();
695 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700696 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700697 }
698 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
699
Vishnu Nair5c010902017-10-26 10:08:50 -0700700 /**
701 * Helper class which parses out priority arguments and dumps sections according to their
702 * priority. If priority arguments are omitted, function calls the legacy dump command.
703 */
704 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
705 @Override
706 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
707 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
708 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
709 }
710
711 @Override
712 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
713 doDump(fd, pw, args, asProto);
714 }
715
716 @Override
717 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
718 doDump(fd, pw, args, asProto);
719 }
720 };
721
Jeff Sharkey899223b2012-08-04 15:24:58 -0700722 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700723 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900724 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
725 }
726
727 @VisibleForTesting
728 protected ConnectivityService(Context context, INetworkManagementService netManager,
729 INetworkStatsService statsService, INetworkPolicyManager policyManager,
730 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800731 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800732
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900733 mSystemProperties = getSystemProperties();
734
Hugo Benichif9fdf872016-07-28 17:53:06 +0900735 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900736 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900737 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900738 mNetworkRequests.put(mDefaultRequest, defaultNRI);
739 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900740
741 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900742 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700743
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900744 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900745 mHandlerThread.start();
746 mHandler = new InternalHandler(mHandlerThread.getLooper());
747 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700748
Jeremy Joslin79294842014-12-03 17:15:28 -0800749 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
750 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
751
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900752 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900753
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700754 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700755 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800756 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700757 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900758 mPolicyManagerInternal = checkNotNull(
759 LocalServices.getService(NetworkPolicyManagerInternal.class),
760 "missing NetworkPolicyManagerInternal");
761
Jeff Sharkey82f85212012-08-24 11:17:25 -0700762 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700763 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700764
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700765 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900766 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700767 } catch (RemoteException e) {
768 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700769 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700770 }
771
772 final PowerManager powerManager = (PowerManager) context.getSystemService(
773 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700774 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
775 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
776 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800777 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700778
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700779 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700780
Wink Saville51f456f2013-04-23 14:26:51 -0700781 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900782 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700783 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700784 String[] naStrings = context.getResources().getStringArray(
785 com.android.internal.R.array.networkAttributes);
786 for (String naString : naStrings) {
787 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700788 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700789 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700790 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800791 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700792 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700793 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700794 }
Wink Saville51f456f2013-04-23 14:26:51 -0700795 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
796 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
797 n.type);
798 continue;
799 }
Wink Saville975c8482011-04-07 14:23:45 -0700800 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800801 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700802 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700803 continue;
804 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700805 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700806
Wink Saville975c8482011-04-07 14:23:45 -0700807 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700808 mNetworksDefined++;
809 } catch(Exception e) {
810 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700811 }
812 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700813
814 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
815 if (mNetConfigs[TYPE_VPN] == null) {
816 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
817 // don't need to add TYPE_VPN to mNetConfigs.
818 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
819 mNetworksDefined++; // used only in the log() statement below.
820 }
821
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900822 // Do the same for Ethernet, since it's often not specified in the configs, although many
823 // devices can use it via USB host adapters.
824 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
825 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
826 mNetworksDefined++;
827 }
828
Wink Saville5e56bc52013-07-29 15:00:57 -0700829 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700830
Robert Greenwalt50393202011-06-21 17:26:14 -0700831 mProtectedNetworks = new ArrayList<Integer>();
832 int[] protectedNetworks = context.getResources().getIntArray(
833 com.android.internal.R.array.config_protectedNetworks);
834 for (int p : protectedNetworks) {
835 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
836 mProtectedNetworks.add(p);
837 } else {
838 if (DBG) loge("Ignoring protectedNetwork " + p);
839 }
840 }
841
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900842 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
843 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700844
Erik Kline47222fc2017-04-30 19:36:15 +0900845 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800846
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700847 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
848
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700849 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700850 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100851 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700852 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700853 intentFilter.addAction(Intent.ACTION_USER_ADDED);
854 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000855 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700856 mContext.registerReceiverAsUser(
857 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000858 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
859 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900860
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700861 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700862 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700863 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700864 } catch (RemoteException e) {
865 loge("Error registering observer :" + e);
866 }
867
Erik Klineda4bfa82015-04-30 12:58:40 +0900868 mSettingsObserver = new SettingsObserver(mContext, mHandler);
869 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800870
John Spurlockbf991a82013-06-24 14:20:23 -0400871 mDataConnectionStats = new DataConnectionStats(mContext);
872 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400873
Jason Monkdecd2952013-10-10 14:02:51 -0400874 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700875
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400876 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900877
878 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900879 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
880 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900881
882 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
883 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
884 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
885 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
886 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
887 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
888 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900889
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900890 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900891 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900892 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900893
894 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900895 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700897
Erik Kline47222fc2017-04-30 19:36:15 +0900898 private Tethering makeTethering() {
899 // TODO: Move other elements into @Overridden getters.
900 final TetheringDependencies deps = new TetheringDependencies();
901 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
902 IoThread.get().getLooper(), new MockableSystemProperties(),
903 deps);
904 }
905
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900906 private NetworkRequest createInternetRequestForTransport(
907 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900908 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900909 netCap.addCapability(NET_CAPABILITY_INTERNET);
910 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900911 if (transportType > -1) {
912 netCap.addTransportType(transportType);
913 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900914 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900915 }
916
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900917 // Used only for testing.
918 // TODO: Delete this and either:
919 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
920 // changing ContentResolver to make registerContentObserver non-final).
921 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
922 // by subclassing SettingsObserver.
923 @VisibleForTesting
924 void updateMobileDataAlwaysOn() {
925 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
926 }
927
Erik Klineda4bfa82015-04-30 12:58:40 +0900928 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900929 final boolean enable = toBool(Settings.Global.getInt(
930 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900931 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
932 if (enable == isEnabled) {
933 return; // Nothing to do.
934 }
935
936 if (enable) {
937 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900938 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900939 } else {
940 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
941 }
942 }
943
944 private void registerSettingsCallbacks() {
945 // Watch for global HTTP proxy changes.
946 mSettingsObserver.observe(
947 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
948 EVENT_APPLY_GLOBAL_HTTP_PROXY);
949
950 // Watch for whether or not to keep mobile data always on.
951 mSettingsObserver.observe(
952 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
953 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
954 }
955
Erik Klinea24d4592018-01-11 21:07:29 +0900956 private void registerPrivateDnsSettingsCallbacks() {
957 for (Uri u : DnsManager.getPrivateDnsSettingsUris()) {
958 mSettingsObserver.observe(u, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
959 }
960 }
961
Robert Greenwalt34524f02014-05-18 16:22:10 -0700962 private synchronized int nextNetworkRequestId() {
963 return mNextNetworkRequestId++;
964 }
965
Paul Jensen67b0b072015-06-10 11:22:17 -0400966 @VisibleForTesting
967 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400968 synchronized (mNetworkForNetId) {
969 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
970 int netId = mNextNetId;
971 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
972 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500973 if (!mNetIdInUse.get(netId)) {
974 mNetIdInUse.put(netId, true);
975 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400976 }
977 }
978 }
979 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700980 }
981
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600982 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800983 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600984 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
985 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800986 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600987 state = nai.getNetworkState();
988 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800989 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600990 final NetworkInfo info = new NetworkInfo(networkType, 0,
991 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800992 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
993 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -0700994 final NetworkCapabilities capabilities = new NetworkCapabilities();
995 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
996 !info.isRoaming());
997 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600998 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800999 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001000 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001001 return state;
1002 } else {
1003 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001004 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001005 }
1006
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001007 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
1008 if (network == null) {
1009 return null;
1010 }
1011 synchronized (mNetworkForNetId) {
1012 return mNetworkForNetId.get(network.netId);
1013 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001014 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001015
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001016 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001017 synchronized (mVpns) {
1018 if (!mLockdownEnabled) {
1019 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001020 Vpn vpn = mVpns.get(user);
1021 if (vpn != null && vpn.appliesToUid(uid)) {
1022 return vpn.getUnderlyingNetworks();
1023 }
1024 }
1025 }
1026 return null;
1027 }
1028
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001029 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001030 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001031
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001032 final Network[] networks = getVpnUnderlyingNetworks(uid);
1033 if (networks != null) {
1034 // getUnderlyingNetworks() returns:
1035 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1036 // empty array => the VPN explicitly said "no default network".
1037 // non-empty array => the VPN specified one or more default networks; we use the
1038 // first one.
1039 if (networks.length > 0) {
1040 nai = getNetworkAgentInfoForNetwork(networks[0]);
1041 } else {
1042 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001043 }
1044 }
1045
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001046 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001047 return nai.getNetworkState();
1048 } else {
1049 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001050 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001051 }
1052
1053 /**
1054 * Check if UID should be blocked from using the network with the given LinkProperties.
1055 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001056 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1057 boolean ignoreBlocked) {
1058 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001059 if (ignoreBlocked) {
1060 return false;
1061 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001062 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001063 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1064 if (isSystem(uid)) {
1065 return false;
1066 }
Robin Lee17e61832016-05-09 13:46:28 +01001067 synchronized (mVpns) {
1068 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1069 if (vpn != null && vpn.isBlockingUid(uid)) {
1070 return true;
1071 }
1072 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001073 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001074 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001075 }
1076
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001077 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001078 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1079 return;
1080 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001081 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001082 synchronized (mBlockedAppUids) {
1083 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001084 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001085 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001086 blocked = false;
1087 } else {
1088 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001089 }
1090 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001091 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1092 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1093 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001094 }
1095
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001096 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001097 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1098 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001099 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001100 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001101 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001102 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1103
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001104 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001105 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001106 }
Hugo Benichi69744342017-11-27 10:57:16 +09001107 synchronized (mVpns) {
1108 if (mLockdownTracker != null) {
1109 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1110 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001111 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001112 }
1113
1114 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 * Return NetworkInfo for the active (i.e., connected) network interface.
1116 * It is assumed that at most one network is active at a time. If more
1117 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001118 * @return the info for the active network, or {@code null} if none is
1119 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001121 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001123 enforceAccessPermission();
1124 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001125 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001126 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001127 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1128 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 }
1130
Paul Jensen31a94f42015-02-13 14:18:39 -05001131 @Override
1132 public Network getActiveNetwork() {
1133 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001134 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001135 }
1136
1137 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001138 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001139 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001140 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001141 }
1142
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001143 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001144 final int user = UserHandle.getUserId(uid);
1145 int vpnNetId = NETID_UNSET;
1146 synchronized (mVpns) {
1147 final Vpn vpn = mVpns.get(user);
1148 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1149 }
1150 NetworkAgentInfo nai;
1151 if (vpnNetId != NETID_UNSET) {
1152 synchronized (mNetworkForNetId) {
1153 nai = mNetworkForNetId.get(vpnNetId);
1154 }
1155 if (nai != null) return nai.network;
1156 }
1157 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001158 if (nai != null
1159 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1160 nai = null;
1161 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001162 return nai != null ? nai.network : null;
1163 }
1164
Lorenzo Colitti18660282016-07-04 12:55:44 +09001165 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001166 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1167 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001168 final int uid = Binder.getCallingUid();
1169 NetworkState state = getUnfilteredActiveNetworkState(uid);
1170 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001171 }
1172
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001173 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001174 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001175 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001176 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001177 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001178 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001179 }
1180
1181 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 public NetworkInfo getNetworkInfo(int networkType) {
1183 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001184 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001185 if (getVpnUnderlyingNetworks(uid) != null) {
1186 // A VPN is active, so we may need to return one of its underlying networks. This
1187 // information is not available in LegacyTypeTracker, so we have to get it from
1188 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001189 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001190 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001191 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001192 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001193 }
1194 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001195 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001196 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 }
1198
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001199 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001200 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001201 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001202 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001203 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001204 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001205 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001206 return state.networkInfo;
1207 } else {
1208 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001209 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001210 }
1211
1212 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 public NetworkInfo[] getAllNetworkInfo() {
1214 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001215 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001216 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1217 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001218 NetworkInfo info = getNetworkInfo(networkType);
1219 if (info != null) {
1220 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001223 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 }
1225
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001226 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001227 public Network getNetworkForType(int networkType) {
1228 enforceAccessPermission();
1229 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001230 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1231 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001232 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001233 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001234 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001235 }
1236
1237 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001238 public Network[] getAllNetworks() {
1239 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001240 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001241 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001242 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001243 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001244 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001245 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001246 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001247 }
1248
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001249 @Override
1250 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1251 // The basic principle is: if an app's traffic could possibly go over a
1252 // network, without the app doing anything multinetwork-specific,
1253 // (hence, by "default"), then include that network's capabilities in
1254 // the array.
1255 //
1256 // In the normal case, app traffic only goes over the system's default
1257 // network connection, so that's the only network returned.
1258 //
1259 // With a VPN in force, some app traffic may go into the VPN, and thus
1260 // over whatever underlying networks the VPN specifies, while other app
1261 // traffic may go over the system default network (e.g.: a split-tunnel
1262 // VPN, or an app disallowed by the VPN), so the set of networks
1263 // returned includes the VPN's underlying networks and the system
1264 // default.
1265 enforceAccessPermission();
1266
1267 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1268
1269 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001270 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001271 if (nc != null) {
1272 result.put(nai.network, nc);
1273 }
1274
Hugo Benichi69744342017-11-27 10:57:16 +09001275 synchronized (mVpns) {
1276 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001277 Vpn vpn = mVpns.get(userId);
1278 if (vpn != null) {
1279 Network[] networks = vpn.getUnderlyingNetworks();
1280 if (networks != null) {
1281 for (Network network : networks) {
1282 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001283 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001284 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001285 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001286 }
1287 }
1288 }
1289 }
1290 }
1291 }
1292
1293 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1294 out = result.values().toArray(out);
1295 return out;
1296 }
1297
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001298 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001299 public boolean isNetworkSupported(int networkType) {
1300 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001301 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001302 }
1303
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001304 /**
1305 * Return LinkProperties for the active (i.e., connected) default
1306 * network interface. It is assumed that at most one default network
1307 * is active at a time. If more than one is active, it is indeterminate
1308 * which will be returned.
1309 * @return the ip properties for the active network, or {@code null} if
1310 * none is active
1311 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001312 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001313 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001314 enforceAccessPermission();
1315 final int uid = Binder.getCallingUid();
1316 NetworkState state = getUnfilteredActiveNetworkState(uid);
1317 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001318 }
1319
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001320 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001321 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001322 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001323 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1324 if (nai != null) {
1325 synchronized (nai) {
1326 return new LinkProperties(nai.linkProperties);
1327 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001328 }
1329 return null;
1330 }
1331
Robert Greenwalt12e67352014-05-13 21:41:06 -07001332 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001333 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001334 public LinkProperties getLinkProperties(Network network) {
1335 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001336 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1337 }
1338
1339 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1340 if (nai == null) {
1341 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001342 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001343 synchronized (nai) {
1344 return new LinkProperties(nai.linkProperties);
1345 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001346 }
1347
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001348 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001349 if (nai != null) {
1350 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001351 if (nai.networkCapabilities != null) {
1352 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001353 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001354 }
1355 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001356 return null;
1357 }
1358
1359 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001360 public NetworkCapabilities getNetworkCapabilities(Network network) {
1361 enforceAccessPermission();
1362 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1363 }
1364
1365 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001366 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001367 // Require internal since we're handing out IMSI details
1368 enforceConnectivityInternalPermission();
1369
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001370 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001371 for (Network network : getAllNetworks()) {
1372 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1373 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001374 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001375 }
1376 }
1377 return result.toArray(new NetworkState[result.size()]);
1378 }
1379
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001380 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001381 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001382 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001383 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1384 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1385 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001386 }
1387
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001388 @Override
1389 public boolean isActiveNetworkMetered() {
1390 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001391
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001392 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
1393 if (caps != null) {
1394 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1395 } else {
1396 // Always return the most conservative value
1397 return true;
1398 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001399 }
1400
Jeff Sharkey216c1812012-08-05 14:29:23 -07001401 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1402 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001403 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001404 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001405 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001406 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001407 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001408
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001409 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 * Ensure that a network route exists to deliver traffic to the specified
1411 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001412 * @param networkType the type of the network over which traffic to the
1413 * specified host is to be routed
1414 * @param hostAddress the IP address of the host to which the route is
1415 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 * @return {@code true} on success, {@code false} on failure
1417 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001418 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001419 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001421 if (mProtectedNetworks.contains(networkType)) {
1422 enforceConnectivityInternalPermission();
1423 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001424
Chad Brubakerc0234532014-02-14 13:24:29 -08001425 InetAddress addr;
1426 try {
1427 addr = InetAddress.getByAddress(hostAddress);
1428 } catch (UnknownHostException e) {
1429 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1430 return false;
1431 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001434 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 return false;
1436 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001437
1438 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1439 if (nai == null) {
1440 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1441 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1442 } else {
1443 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1444 }
1445 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001446 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001447
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001448 DetailedState netState;
1449 synchronized (nai) {
1450 netState = nai.networkInfo.getDetailedState();
1451 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001452
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001453 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001454 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001455 log("requestRouteToHostAddress on down network "
1456 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001457 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001458 }
1459 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001461
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001462 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001463 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001464 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001465 LinkProperties lp;
1466 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001467 synchronized (nai) {
1468 lp = nai.linkProperties;
1469 netId = nai.network.netId;
1470 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001471 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001472 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1473 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001474 } finally {
1475 Binder.restoreCallingIdentity(token);
1476 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001477 }
1478
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001479 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001480 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001481 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001482 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001483 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001484 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001485 if (bestRoute.getGateway().equals(addr)) {
1486 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001487 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001488 } else {
1489 // if we will connect to this through another route, add a direct route
1490 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001491 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001492 }
1493 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001494 if (DBG) log("Adding legacy route " + bestRoute +
1495 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001496 try {
1497 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1498 } catch (Exception e) {
1499 // never crash - catch them all
1500 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001501 return false;
1502 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001503 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 }
1505
Jeff Sharkey75d31892018-01-18 22:01:59 +09001506 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001507 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001508 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001509 // TODO: notify UID when it has requested targeted updates
1510 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001511 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001512 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001513 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001514 if (restrictBackground) {
1515 log("onRestrictBackgroundChanged(true): disabling tethering");
1516 mTethering.untetherAll();
1517 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001518 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001519 };
1520
Robin Lee3b3dd942015-05-12 18:14:58 +01001521 /**
1522 * Require that the caller is either in the same user or has appropriate permission to interact
1523 * across users.
1524 *
1525 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1526 */
1527 private void enforceCrossUserPermission(int userId) {
1528 if (userId == UserHandle.getCallingUserId()) {
1529 // Not a cross-user call.
1530 return;
1531 }
1532 mContext.enforceCallingOrSelfPermission(
1533 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1534 "ConnectivityService");
1535 }
1536
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001537 private void enforceInternetPermission() {
1538 mContext.enforceCallingOrSelfPermission(
1539 android.Manifest.permission.INTERNET,
1540 "ConnectivityService");
1541 }
1542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001544 mContext.enforceCallingOrSelfPermission(
1545 android.Manifest.permission.ACCESS_NETWORK_STATE,
1546 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 }
1548
1549 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001550 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 }
1552
Charles He36738632017-05-15 17:07:18 +01001553 private void enforceSettingsPermission() {
1554 mContext.enforceCallingOrSelfPermission(
1555 android.Manifest.permission.NETWORK_SETTINGS,
1556 "ConnectivityService");
1557 }
1558
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001559 private void enforceTetherAccessPermission() {
1560 mContext.enforceCallingOrSelfPermission(
1561 android.Manifest.permission.ACCESS_NETWORK_STATE,
1562 "ConnectivityService");
1563 }
1564
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001565 private void enforceConnectivityInternalPermission() {
1566 mContext.enforceCallingOrSelfPermission(
1567 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1568 "ConnectivityService");
1569 }
1570
Hugo Benichi514da602016-07-19 15:59:27 +09001571 private void enforceConnectivityRestrictedNetworksPermission() {
1572 try {
1573 mContext.enforceCallingOrSelfPermission(
1574 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1575 "ConnectivityService");
1576 return;
1577 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1578 enforceConnectivityInternalPermission();
1579 }
1580
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001581 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001582 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001583 }
1584
Lorenzo Colitti18660282016-07-04 12:55:44 +09001585 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001586 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001587 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001588 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001589 }
1590
1591 private void sendInetConditionBroadcast(NetworkInfo info) {
1592 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1593 }
1594
Wink Saville628b0852011-08-04 15:01:58 -07001595 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001596 synchronized (mVpns) {
1597 if (mLockdownTracker != null) {
1598 info = new NetworkInfo(info);
1599 mLockdownTracker.augmentNetworkInfo(info);
1600 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001601 }
1602
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001603 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001604 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001605 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 if (info.isFailover()) {
1607 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1608 info.setFailover(false);
1609 }
1610 if (info.getReason() != null) {
1611 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1612 }
1613 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001614 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1615 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001617 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001618 return intent;
1619 }
1620
1621 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1622 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1623 }
1624
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001625 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001626 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1627 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1628 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001629 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001630 final long ident = Binder.clearCallingIdentity();
1631 try {
1632 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1633 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1634 } finally {
1635 Binder.restoreCallingIdentity(ident);
1636 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001637 }
1638
Mike Lockwood0f79b542009-08-14 14:18:49 -04001639 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001640 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001641 if (!mSystemReady) {
1642 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001643 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001644 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001645 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001646 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001647 }
1648
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001649 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001650 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001651 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001652 final NetworkInfo ni = intent.getParcelableExtra(
1653 ConnectivityManager.EXTRA_NETWORK_INFO);
1654 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1655 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1656 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001657 } else {
1658 BroadcastOptions opts = BroadcastOptions.makeBasic();
1659 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1660 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001661 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001662 final IBatteryStats bs = BatteryStatsService.getService();
1663 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001664 bs.noteConnectivityChanged(intent.getIntExtra(
1665 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1666 ni != null ? ni.getState().toString() : "?");
1667 } catch (RemoteException e) {
1668 }
1669 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001670 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001671 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001672 } finally {
1673 Binder.restoreCallingIdentity(ident);
1674 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001675 }
1676 }
1677
1678 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001679 loadGlobalProxy();
1680
Hugo Benichi20035e02017-04-26 14:53:28 +09001681 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001682 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001683 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001684 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001685 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001686 }
1687 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001688 // load the global proxy at startup
1689 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001690
Robin Lee244ce8e2016-01-05 18:03:46 +00001691 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1692 // for user to unlock device too.
1693 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001694
Erik Klineda4bfa82015-04-30 12:58:40 +09001695 // Configure whether mobile data is always on.
1696 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1697
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001698 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001699
1700 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 }
1702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001704 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001705 *
1706 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001707 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001708 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001709 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1710 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001711
1712 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001713 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001714
Robert Greenwalt7b816022014-04-18 15:25:25 -07001715 if (networkAgent.networkCapabilities.hasTransport(
1716 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001717 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1718 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001719 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001720 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001721 } else if (networkAgent.networkCapabilities.hasTransport(
1722 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001723 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1724 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001725 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001726 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001727 } else {
1728 // do not track any other networks
1729 timeout = 0;
1730 }
1731
Robert Greenwalt7b816022014-04-18 15:25:25 -07001732 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001733 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001734 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001735 } catch (Exception e) {
1736 // You shall not crash!
1737 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001738 }
1739 }
1740 }
1741
1742 /**
1743 * Remove data activity tracking when network disconnects.
1744 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001745 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1746 final String iface = networkAgent.linkProperties.getInterfaceName();
1747 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001748
Robert Greenwalt7b816022014-04-18 15:25:25 -07001749 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1750 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001751 try {
1752 // the call fails silently if no idletimer setup for this interface
1753 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001754 } catch (Exception e) {
1755 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001756 }
1757 }
1758 }
1759
1760 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001761 * Reads the network specific MTU size from reources.
1762 * and set it on it's iface.
1763 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001764 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1765 final String iface = newLp.getInterfaceName();
1766 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001767 if (oldLp == null && mtu == 0) {
1768 // Silently ignore unset MTU value.
1769 return;
1770 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001771 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1772 if (VDBG) log("identical MTU - not setting");
1773 return;
1774 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001775 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001776 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001777 return;
1778 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001779
w1997615afd812014-08-05 15:18:11 -07001780 // Cannot set MTU without interface name
1781 if (TextUtils.isEmpty(iface)) {
1782 loge("Setting MTU size with null iface.");
1783 return;
1784 }
1785
Robert Greenwalt7b816022014-04-18 15:25:25 -07001786 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001787 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001788 mNetd.setMtu(iface, mtu);
1789 } catch (Exception e) {
1790 Slog.e(TAG, "exception in setMtu()" + e);
1791 }
1792 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001793
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001794 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001795 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1796
1797 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001798 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001799 protected MockableSystemProperties getSystemProperties() {
1800 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001801 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001802
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001803 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1804 if (isDefaultNetwork(nai) == false) {
1805 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001806 }
1807
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001808 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1809 String[] values = null;
1810 if (tcpBufferSizes != null) {
1811 values = tcpBufferSizes.split(",");
1812 }
1813
1814 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001815 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001816 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1817 values = tcpBufferSizes.split(",");
1818 }
1819
1820 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1821
1822 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001823 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001824
1825 final String prefix = "/sys/kernel/ipv4/tcp_";
1826 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1827 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1828 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1829 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1830 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1831 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1832 mCurrentTcpBufferSizes = tcpBufferSizes;
1833 } catch (IOException e) {
1834 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001835 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001836
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001837 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001838 Settings.Global.TCP_DEFAULT_INIT_RWND,
1839 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001840 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1841 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001842 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001843 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001844 }
1845
Robert Greenwalt562cc542014-05-15 18:07:26 -07001846 @Override
1847 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001848 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001849 NETWORK_RESTORE_DELAY_PROP_NAME);
1850 if(restoreDefaultNetworkDelayStr != null &&
1851 restoreDefaultNetworkDelayStr.length() != 0) {
1852 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001853 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001854 } catch (NumberFormatException e) {
1855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001857 // if the system property isn't set, use the value for the apn type
1858 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1859
1860 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1861 (mNetConfigs[networkType] != null)) {
1862 ret = mNetConfigs[networkType].restoreTime;
1863 }
1864 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 }
1866
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001867 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001868 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001869 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001870 }
1871 return false;
1872 }
1873
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001874 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1875 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1876 final long DIAG_TIME_MS = 5000;
1877 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1878 // Start gathering diagnostic information.
1879 netDiags.add(new NetworkDiagnostics(
1880 nai.network,
1881 new LinkProperties(nai.linkProperties), // Must be a copy.
1882 DIAG_TIME_MS));
1883 }
1884
1885 for (NetworkDiagnostics netDiag : netDiags) {
1886 pw.println();
1887 netDiag.waitForMeasurements();
1888 netDiag.dump(pw);
1889 }
1890 }
1891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001893 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07001894 PriorityDump.dump(mPriorityDumper, fd, writer, args);
1895 }
1896
1897 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001898 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001899 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07001900 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001901
Erik Kline7747fd42017-05-12 16:52:48 +09001902 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001903 dumpNetworkDiagnostics(pw);
1904 return;
Erik Klineee363c42017-05-29 09:11:03 +09001905 } else if (argsContain(args, TETHERING_ARG)) {
1906 mTethering.dump(fd, pw, args);
1907 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001908 }
Erik Kline379747a2015-06-05 17:47:34 +09001909
Lorenzo Colittie3805462015-06-03 11:18:24 +09001910 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001911 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001912 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001913 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001914 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001915 pw.println();
1916
Paul Jensen85cf78e2015-06-25 13:25:07 -04001917 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001918 pw.print("Active default network: ");
1919 if (defaultNai == null) {
1920 pw.println("none");
1921 } else {
1922 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001924 pw.println();
1925
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001926 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001927 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001928 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1929 pw.println(nai.toString());
1930 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001931 pw.println(String.format(
1932 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1933 nai.numForegroundNetworkRequests(),
1934 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1935 nai.numBackgroundNetworkRequests(),
1936 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001937 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001938 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1939 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001940 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001941 pw.decreaseIndent();
1942 pw.println("Lingered:");
1943 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001944 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001945 pw.decreaseIndent();
1946 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001947 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001948 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001949 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001950
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001951 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001952 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001953 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1954 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001955 }
1956 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001957 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001958
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001959 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001960
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001961 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001962 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001963
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001964 pw.println();
1965 mKeepaliveTracker.dump(pw);
1966
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001967 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001968 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001969
Erik Kline7747fd42017-05-12 16:52:48 +09001970 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001971 pw.println();
1972 synchronized (mValidationLogs) {
1973 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001974 for (ValidationLog p : mValidationLogs) {
1975 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001976 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001977 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001978 pw.decreaseIndent();
1979 }
1980 }
Erik Kline7523eb32015-07-09 18:24:03 +09001981
1982 pw.println();
1983 pw.println("mNetworkRequestInfoLogs (most recent first):");
1984 pw.increaseIndent();
1985 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1986 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09001987
1988 pw.println();
1989 pw.println("mNetworkInfoBlockingLogs (most recent first):");
1990 pw.increaseIndent();
1991 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
1992 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001993
1994 pw.println();
1995 pw.println("NetTransition WakeLock activity (most recent first):");
1996 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09001997 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
1998 pw.println("total releases: " + mTotalWakelockReleases);
1999 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2000 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2001 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2002 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2003 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2004 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002005 mWakelockLogs.reverseDump(fd, pw, args);
2006 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 }
2009
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002010 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002011 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002012 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002013 if (officialNai != null && officialNai.equals(nai)) return true;
2014 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002015 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002016 " - " + nai);
2017 }
2018 return false;
2019 }
2020
Robert Greenwalt42acef32009-08-12 16:08:25 -07002021 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002022 private class NetworkStateTrackerHandler extends Handler {
2023 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002024 super(looper);
2025 }
2026
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002027 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002029 default:
2030 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002031 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002032 handleAsyncChannelHalfConnect(msg);
2033 break;
2034 }
2035 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2036 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2037 if (nai != null) nai.asyncChannel.disconnect();
2038 break;
2039 }
2040 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2041 handleAsyncChannelDisconnected(msg);
2042 break;
2043 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002044 }
2045 return true;
2046 }
2047
2048 private void maybeHandleNetworkAgentMessage(Message msg) {
2049 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2050 if (nai == null) {
2051 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002052 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002053 }
2054 return;
2055 }
2056
2057 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002058 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002059 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2060 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002061 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2062 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002063 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002064 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002065 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002066 break;
2067 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002068 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002069 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002070 break;
2071 }
2072 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002073 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002074 updateNetworkInfo(nai, info);
2075 break;
2076 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002077 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002078 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002079 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002080 break;
2081 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002082 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002083 try {
2084 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002085 } catch (Exception e) {
2086 // Never crash!
2087 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002088 }
2089 break;
2090 }
2091 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002092 try {
2093 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002094 } catch (Exception e) {
2095 // Never crash!
2096 loge("Exception in removeVpnUidRanges: " + e);
2097 }
2098 break;
2099 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002100 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002101 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2102 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002103 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002104 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002105 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002106 break;
2107 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002108 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002109 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2110 break;
2111 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002112 }
2113 }
2114
2115 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2116 switch (msg.what) {
2117 default:
2118 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002119 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002120 final NetworkAgentInfo nai;
2121 synchronized (mNetworkForNetId) {
2122 nai = mNetworkForNetId.get(msg.arg2);
2123 }
Erik Klinea24d4592018-01-11 21:07:29 +09002124 if (nai == null) break;
2125
2126 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2127 final boolean wasValidated = nai.lastValidated;
2128 final boolean wasDefault = isDefaultNetwork(nai);
2129
2130 final PrivateDnsConfig privateDnsCfg = (msg.obj instanceof PrivateDnsConfig)
2131 ? (PrivateDnsConfig) msg.obj : null;
2132 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2133
2134 final boolean reevaluationRequired;
2135 final String logMsg;
2136 if (valid) {
2137 reevaluationRequired = updatePrivateDns(nai, privateDnsCfg);
2138 logMsg = (DBG && (privateDnsCfg != null))
2139 ? " with " + privateDnsCfg.toString() : "";
2140 } else {
2141 reevaluationRequired = false;
2142 logMsg = (DBG && !TextUtils.isEmpty(redirectUrl))
2143 ? " with redirect to " + redirectUrl : "";
2144 }
2145 if (DBG) {
2146 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2147 }
2148 // If there is a change in Private DNS configuration,
2149 // trigger reevaluation of the network to test it.
2150 if (reevaluationRequired) {
2151 nai.networkMonitor.sendMessage(
2152 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2153 break;
2154 }
2155 if (valid != nai.lastValidated) {
2156 if (wasDefault) {
2157 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2158 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002159 }
Erik Klinea24d4592018-01-11 21:07:29 +09002160 final int oldScore = nai.getCurrentScore();
2161 nai.lastValidated = valid;
2162 nai.everValidated |= valid;
2163 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2164 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2165 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2166 }
2167 updateInetCondition(nai);
2168 // Let the NetworkAgent know the state of its network
2169 Bundle redirectUrlBundle = new Bundle();
2170 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2171 nai.asyncChannel.sendMessage(
2172 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2173 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2174 0, redirectUrlBundle);
2175 if (wasValidated && !nai.lastValidated) {
2176 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002177 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002178 break;
2179 }
Paul Jensen869868be2014-05-15 10:33:05 -04002180 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002181 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002182 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002183 final NetworkAgentInfo nai;
2184 synchronized (mNetworkForNetId) {
2185 nai = mNetworkForNetId.get(netId);
2186 }
Calvin Onbe96da12016-10-11 15:10:46 -07002187 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002188 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002189 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002190 nai.lastCaptivePortalDetected = visible;
2191 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002192 if (nai.lastCaptivePortalDetected &&
2193 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2194 if (DBG) log("Avoiding captive portal network: " + nai.name());
2195 nai.asyncChannel.sendMessage(
2196 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2197 teardownUnneededNetwork(nai);
2198 break;
2199 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002200 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002201 }
2202 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002203 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002204 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002205 if (nai == null) {
2206 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2207 break;
2208 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002209 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002210 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002211 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002212 }
Paul Jensen869868be2014-05-15 10:33:05 -04002213 }
Paul Jensen869868be2014-05-15 10:33:05 -04002214 break;
2215 }
Erik Klinea24d4592018-01-11 21:07:29 +09002216 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
2217 final NetworkAgentInfo nai;
2218 synchronized (mNetworkForNetId) {
2219 nai = mNetworkForNetId.get(msg.arg2);
2220 }
2221 if (nai == null) break;
2222
2223 final PrivateDnsConfig cfg = (PrivateDnsConfig) msg.obj;
2224 final boolean reevaluationRequired = updatePrivateDns(nai, cfg);
2225 if (nai.lastValidated && reevaluationRequired) {
2226 nai.networkMonitor.sendMessage(
2227 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2228 }
2229 break;
2230 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002231 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002232 return true;
2233 }
2234
Calvin Onbe96da12016-10-11 15:10:46 -07002235 private int getCaptivePortalMode() {
2236 return Settings.Global.getInt(mContext.getContentResolver(),
2237 Settings.Global.CAPTIVE_PORTAL_MODE,
2238 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2239 }
2240
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002241 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2242 switch (msg.what) {
2243 default:
2244 return false;
2245 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2246 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2247 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2248 handleLingerComplete(nai);
2249 }
2250 break;
2251 }
2252 }
2253 return true;
2254 }
2255
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002256 @Override
2257 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002258 if (!maybeHandleAsyncChannelMessage(msg) &&
2259 !maybeHandleNetworkMonitorMessage(msg) &&
2260 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002261 maybeHandleNetworkAgentMessage(msg);
2262 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002263 }
2264 }
2265
Erik Klinea24d4592018-01-11 21:07:29 +09002266 private void handlePrivateDnsSettingsChanged() {
2267 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2268
2269 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2270 // Private DNS only ever applies to networks that might provide
2271 // Internet access and therefore also require validation.
2272 if (!NetworkMonitor.isValidationRequired(
2273 mDefaultRequest.networkCapabilities, nai.networkCapabilities)) {
2274 continue;
2275 }
2276
2277 // Notify the NetworkMonitor thread in case it needs to cancel or
2278 // schedule DNS resolutions. If a DNS resolution is required the
2279 // result will be sent back to us.
2280 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2281
2282 if (!cfg.inStrictMode()) {
2283 // No strict mode hostname DNS resolution needed, so just update
2284 // DNS settings directly. In opportunistic and "off" modes this
2285 // just reprograms netd with the network-supplied DNS servers
2286 // (and of course the boolean of whether or not to attempt TLS).
2287 //
2288 // TODO: Consider code flow parity with strict mode, i.e. having
2289 // NetworkMonitor relay the PrivateDnsConfig back to us and then
2290 // performing this call at that time.
2291 updatePrivateDns(nai, cfg);
2292 }
2293 }
2294 }
2295
2296 private boolean updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2297 final boolean reevaluationRequired = true;
2298 final boolean dontReevaluate = false;
2299
2300 final PrivateDnsConfig oldCfg = mDnsManager.updatePrivateDns(nai.network, newCfg);
2301 updateDnses(nai.linkProperties, null, nai.network.netId);
2302
2303 if (newCfg == null) {
2304 if (oldCfg == null) return dontReevaluate;
2305 return oldCfg.useTls ? reevaluationRequired : dontReevaluate;
2306 }
2307
2308 if (oldCfg == null) {
2309 return newCfg.useTls ? reevaluationRequired : dontReevaluate;
2310 }
2311
2312 if (oldCfg.useTls != newCfg.useTls) {
2313 return reevaluationRequired;
2314 }
2315
2316 if (newCfg.inStrictMode() && !Objects.equals(oldCfg.hostname, newCfg.hostname)) {
2317 return reevaluationRequired;
2318 }
2319
2320 return dontReevaluate;
2321 }
2322
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002323 private void updateLingerState(NetworkAgentInfo nai, long now) {
2324 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2325 // 2. If the network was lingering and there are now requests, unlinger it.
2326 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2327 // one lingered request, start lingering.
2328 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002329 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002330 if (DBG) log("Unlingering " + nai.name());
2331 nai.unlinger();
2332 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002333 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002334 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002335 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002336 nai.linger();
2337 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2338 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2339 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002340 }
2341
Robert Greenwalt7b816022014-04-18 15:25:25 -07002342 private void handleAsyncChannelHalfConnect(Message msg) {
2343 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002344 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002345 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2346 if (VDBG) log("NetworkFactory connected");
2347 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002348 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002349 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002350 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002351 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002352 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002353 }
2354 } else {
2355 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002356 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002357 }
2358 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2359 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2360 if (VDBG) log("NetworkAgent connected");
2361 // A network agent has requested a connection. Establish the connection.
2362 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2363 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2364 } else {
2365 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002366 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002367 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002368 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002369 synchronized (mNetworkForNetId) {
2370 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002371 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002372 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002373 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002374 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002375 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002376 }
2377 }
2378 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002379
Robert Greenwalt7b816022014-04-18 15:25:25 -07002380 private void handleAsyncChannelDisconnected(Message msg) {
2381 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2382 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002383 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002384 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002385 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002386 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002387 // TODO - if we move the logic to the network agent (have them disconnect
2388 // because they lost all their requests or because their score isn't good)
2389 // then they would disconnect organically, report their new state and then
2390 // disconnect the channel.
2391 if (nai.networkInfo.isConnected()) {
2392 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2393 null, null);
2394 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002395 final boolean wasDefault = isDefaultNetwork(nai);
2396 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002397 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002398 // Log default network disconnection before required book-keeping.
2399 // Let rematchAllNetworksAndRequests() below record a new default network event
2400 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2401 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002402 long now = SystemClock.elapsedRealtime();
2403 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002404 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002405 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002406 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2407 // by other networks that are already connected. Perhaps that can be done by
2408 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2409 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002410 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002411 mKeepaliveTracker.handleStopAllKeepalives(nai,
2412 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002413 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2414 // Disable wakeup packet monitoring for each interface.
2415 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2416 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002417 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002418 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002419 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002420 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002421 // Remove the NetworkAgent, but don't mark the netId as
2422 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002423 mNetworkForNetId.remove(nai.network.netId);
2424 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002425 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002426 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2427 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002428 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002429 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002430 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002431 sendUpdatedScoreToFactories(request, 0);
2432 }
2433 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002434 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002435 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002436 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002437 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002438 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002439 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002440 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002441 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002442 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002443 if (nai.created) {
2444 // Tell netd to clean up the configuration for this network
2445 // (routing rules, DNS, etc).
2446 // This may be slow as it requires a lot of netd shelling out to ip and
2447 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2448 // after we've rematched networks with requests which should make a potential
2449 // fallback network the default or requested a new network from the
2450 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2451 // long time.
2452 try {
2453 mNetd.removeNetwork(nai.network.netId);
2454 } catch (Exception e) {
2455 loge("Exception removing network: " + e);
2456 }
Erik Klinea24d4592018-01-11 21:07:29 +09002457 mDnsManager.removeNetwork(nai.network);
Paul Jensen62d30802015-06-17 14:42:30 -04002458 }
2459 synchronized (mNetworkForNetId) {
2460 mNetIdInUse.delete(nai.network.netId);
2461 }
2462 } else {
2463 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2464 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002465 }
2466 }
2467
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002468 // If this method proves to be too slow then we can maintain a separate
2469 // pendingIntent => NetworkRequestInfo map.
2470 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2471 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2472 Intent intent = pendingIntent.getIntent();
2473 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2474 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2475 if (existingPendingIntent != null &&
2476 existingPendingIntent.getIntent().filterEquals(intent)) {
2477 return entry.getValue();
2478 }
2479 }
2480 return null;
2481 }
2482
2483 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2484 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2485
2486 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2487 if (existingRequest != null) { // remove the existing request.
2488 if (DBG) log("Replacing " + existingRequest.request + " with "
2489 + nri.request + " because their intents matched.");
2490 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2491 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002492 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002493 }
2494
Erik Klineda4bfa82015-04-30 12:58:40 +09002495 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002496 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002497 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002498 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002499 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002500 if (nri.request.networkCapabilities.hasSignalStrength() &&
2501 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2502 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002503 }
2504 }
2505 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002506 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002507 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002508 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002509 }
2510 }
2511
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002512 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2513 int callingUid) {
2514 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2515 if (nri != null) {
2516 handleReleaseNetworkRequest(nri.request, callingUid);
2517 }
2518 }
2519
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002520 // Determines whether the network is the best (or could become the best, if it validated), for
2521 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2522 // on the value of reason:
2523 //
2524 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2525 // then it should be torn down.
2526 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2527 // then it should be lingered.
2528 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2529 final int numRequests;
2530 switch (reason) {
2531 case TEARDOWN:
2532 numRequests = nai.numRequestNetworkRequests();
2533 break;
2534 case LINGER:
2535 numRequests = nai.numForegroundNetworkRequests();
2536 break;
2537 default:
2538 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2539 return true;
2540 }
2541
2542 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002543 return false;
2544 }
Paul Jensene0988542015-06-25 15:30:08 -04002545 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002546 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2547 // Background requests don't affect lingering.
2548 continue;
2549 }
2550
Paul Jensene0988542015-06-25 15:30:08 -04002551 // If this Network is already the highest scoring Network for a request, or if
2552 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002553 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002554 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002555 // Note that this catches two important cases:
2556 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2557 // is currently satisfying the request. This is desirable when
2558 // cellular ends up validating but WiFi does not.
2559 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002560 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002561 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002562 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002563 nai.getCurrentScoreAsValidated())) {
2564 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002565 }
2566 }
Paul Jensene0988542015-06-25 15:30:08 -04002567 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002568 }
2569
Erik Klineacdd6392016-07-07 16:50:58 +09002570 private NetworkRequestInfo getNriForAppRequest(
2571 NetworkRequest request, int callingUid, String requestedOperation) {
2572 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2573
Robert Greenwalt9258c642014-03-26 16:47:06 -07002574 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002575 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002576 log(String.format("UID %d attempted to %s for unowned request %s",
2577 callingUid, requestedOperation, nri));
2578 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002579 }
Erik Klineacdd6392016-07-07 16:50:58 +09002580 }
2581
2582 return nri;
2583 }
2584
Erik Kline57faba92015-11-25 12:49:38 +09002585 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002586 if (mNetworkRequests.get(nri.request) == null) {
2587 return;
Erik Kline57faba92015-11-25 12:49:38 +09002588 }
Hugo Benichicd952782017-09-20 11:20:14 +09002589 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002590 return;
2591 }
2592 if (VDBG || (DBG && nri.request.isRequest())) {
2593 log("releasing " + nri.request + " (timeout)");
2594 }
2595 handleRemoveNetworkRequest(nri);
2596 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002597 }
2598
Erik Klineacdd6392016-07-07 16:50:58 +09002599 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002600 final NetworkRequestInfo nri =
2601 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2602 if (nri == null) {
2603 return;
Erik Kline57faba92015-11-25 12:49:38 +09002604 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002605 if (VDBG || (DBG && nri.request.isRequest())) {
2606 log("releasing " + nri.request + " (release request)");
2607 }
2608 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002609 }
Erik Klineacdd6392016-07-07 16:50:58 +09002610
Hugo Benichidba33db2017-03-23 22:40:44 +09002611 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002612 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002613 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002614
Erik Klineacdd6392016-07-07 16:50:58 +09002615 synchronized (mUidToNetworkRequestCount) {
2616 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2617 if (requests < 1) {
2618 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2619 nri.mUid);
2620 } else if (requests == 1) {
2621 mUidToNetworkRequestCount.removeAt(
2622 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2623 } else {
2624 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2625 }
2626 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002627
Erik Klineacdd6392016-07-07 16:50:58 +09002628 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2629 if (nri.request.isRequest()) {
2630 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002631 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002632 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002633 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002634 nai.removeRequest(nri.request.requestId);
2635 if (VDBG) {
2636 log(" Removing from current network " + nai.name() +
2637 ", leaving " + nai.numNetworkRequests() + " requests.");
2638 }
2639 // If there are still lingered requests on this network, don't tear it down,
2640 // but resume lingering instead.
2641 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002642 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002643 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2644 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002645 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002646 wasKept = true;
2647 }
Hugo Benichicd952782017-09-20 11:20:14 +09002648 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002649 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2650 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002651 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002652 }
Erik Klineacdd6392016-07-07 16:50:58 +09002653 }
2654
2655 // TODO: remove this code once we know that the Slog.wtf is never hit.
2656 //
2657 // Find all networks that are satisfying this request and remove the request
2658 // from their request lists.
2659 // TODO - it's my understanding that for a request there is only a single
2660 // network satisfying it, so this loop is wasteful
2661 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2662 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2663 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2664 otherNai.name() + ", but mNetworkAgentInfos says " +
2665 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002666 }
2667 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002668
Erik Klineacdd6392016-07-07 16:50:58 +09002669 // Maintain the illusion. When this request arrived, we might have pretended
2670 // that a network connected to serve it, even though the network was already
2671 // connected. Now that this request has gone away, we might have to pretend
2672 // that the network disconnected. LegacyTypeTracker will generate that
2673 // phantom disconnect for this type.
2674 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2675 boolean doRemove = true;
2676 if (wasKept) {
2677 // check if any of the remaining requests for this network are for the
2678 // same legacy type - if so, don't remove the nai
2679 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2680 NetworkRequest otherRequest = nai.requestAt(i);
2681 if (otherRequest.legacyType == nri.request.legacyType &&
2682 otherRequest.isRequest()) {
2683 if (DBG) log(" still have other legacy request - leaving");
2684 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002685 }
2686 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002687 }
2688
Erik Klineacdd6392016-07-07 16:50:58 +09002689 if (doRemove) {
2690 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002691 }
2692 }
Erik Klineacdd6392016-07-07 16:50:58 +09002693
2694 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2695 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2696 nri.request);
2697 }
2698 } else {
2699 // listens don't have a singular affectedNetwork. Check all networks to see
2700 // if this listen request applies and remove it.
2701 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2702 nai.removeRequest(nri.request.requestId);
2703 if (nri.request.networkCapabilities.hasSignalStrength() &&
2704 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2705 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2706 }
2707 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002708 }
2709 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002710
Lorenzo Colitti18660282016-07-04 12:55:44 +09002711 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002712 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2713 enforceConnectivityInternalPermission();
2714 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002715 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002716 }
2717
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002718 @Override
2719 public void setAvoidUnvalidated(Network network) {
2720 enforceConnectivityInternalPermission();
2721 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2722 }
2723
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002724 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2725 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2726 " accept=" + accept + " always=" + always);
2727
2728 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2729 if (nai == null) {
2730 // Nothing to do.
2731 return;
2732 }
2733
2734 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002735 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002736 return;
2737 }
2738
2739 if (!nai.networkMisc.explicitlySelected) {
2740 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2741 }
2742
2743 if (accept != nai.networkMisc.acceptUnvalidated) {
2744 int oldScore = nai.getCurrentScore();
2745 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002746 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002747 sendUpdatedScoreToFactories(nai);
2748 }
2749
2750 if (always) {
2751 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002752 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002753 }
2754
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002755 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002756 // Tell the NetworkAgent to not automatically reconnect to the network.
2757 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2758 // Teardown the nework.
2759 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002760 }
2761
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002762 }
2763
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002764 private void handleSetAvoidUnvalidated(Network network) {
2765 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2766 if (nai == null || nai.lastValidated) {
2767 // Nothing to do. The network either disconnected or revalidated.
2768 return;
2769 }
2770 if (!nai.avoidUnvalidated) {
2771 int oldScore = nai.getCurrentScore();
2772 nai.avoidUnvalidated = true;
2773 rematchAllNetworksAndRequests(nai, oldScore);
2774 sendUpdatedScoreToFactories(nai);
2775 }
2776 }
2777
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002778 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002779 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002780 mHandler.sendMessageDelayed(
2781 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2782 PROMPT_UNVALIDATED_DELAY_MS);
2783 }
2784
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002785 @Override
2786 public void startCaptivePortalApp(Network network) {
2787 enforceConnectivityInternalPermission();
2788 mHandler.post(() -> {
2789 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2790 if (nai == null) return;
2791 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2792 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2793 });
2794 }
2795
Hugo Benichic8e9e122016-09-14 23:23:08 +00002796 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002797 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002798 }
2799
Erik Kline065ab6e2016-10-02 18:02:14 +09002800 private void rematchForAvoidBadWifiUpdate() {
2801 rematchAllNetworksAndRequests(null, 0);
2802 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2803 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2804 sendUpdatedScoreToFactories(nai);
2805 }
2806 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002807 }
2808
Erik Kline065ab6e2016-10-02 18:02:14 +09002809 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002810 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002811 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002812 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002813 if (!configRestrict) {
2814 pw.println("Bad Wi-Fi avoidance: unrestricted");
2815 return;
2816 }
2817
2818 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2819 pw.increaseIndent();
2820 pw.println("Config restrict: " + configRestrict);
2821
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002822 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002823 String description;
2824 // Can't use a switch statement because strings are legal case labels, but null is not.
2825 if ("0".equals(value)) {
2826 description = "get stuck";
2827 } else if (value == null) {
2828 description = "prompt";
2829 } else if ("1".equals(value)) {
2830 description = "avoid";
2831 } else {
2832 description = value + " (?)";
2833 }
2834 pw.println("User setting: " + description);
2835 pw.println("Network overrides:");
2836 pw.increaseIndent();
2837 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2838 if (nai.avoidUnvalidated) {
2839 pw.println(nai.name());
2840 }
2841 }
2842 pw.decreaseIndent();
2843 pw.decreaseIndent();
2844 }
2845
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002846 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2847 final String action;
2848 switch (type) {
2849 case NO_INTERNET:
2850 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2851 break;
2852 case LOST_INTERNET:
2853 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2854 break;
2855 default:
2856 Slog.wtf(TAG, "Unknown notification type " + type);
2857 return;
2858 }
2859
2860 Intent intent = new Intent(action);
2861 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2862 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2863 intent.setClassName("com.android.settings",
2864 "com.android.settings.wifi.WifiNoInternetDialog");
2865
2866 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2867 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2868 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2869 }
2870
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002871 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002872 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002873 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2874
2875 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2876 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002877 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002878 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002879 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2880 return;
2881 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002882 showValidationNotification(nai, NotificationType.NO_INTERNET);
2883 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002884
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002885 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2886 NetworkCapabilities nc = nai.networkCapabilities;
2887 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002888
Erik Kline065ab6e2016-10-02 18:02:14 +09002889 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002890 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002891 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2892 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002893 }
2894
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002895 @Override
2896 public int getMultipathPreference(Network network) {
2897 enforceAccessPermission();
2898
2899 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002900 if (nai != null && nai.networkCapabilities
2901 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002902 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2903 }
2904
2905 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2906 }
2907
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002908 private class InternalHandler extends Handler {
2909 public InternalHandler(Looper looper) {
2910 super(looper);
2911 }
2912
2913 @Override
2914 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002915 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002916 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002917 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002918 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002919 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002920 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002921 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002922 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002923 break;
2924 }
Jason Monkdecd2952013-10-10 14:02:51 -04002925 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002926 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002927 break;
2928 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002929 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002930 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2931 break;
2932 }
2933 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2934 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002935 break;
2936 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002937 case EVENT_REGISTER_NETWORK_AGENT: {
2938 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2939 break;
2940 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002941 case EVENT_REGISTER_NETWORK_REQUEST:
2942 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002943 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002944 break;
2945 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002946 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2947 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002948 handleRegisterNetworkRequestWithIntent(msg);
2949 break;
2950 }
Erik Kline57faba92015-11-25 12:49:38 +09002951 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2952 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2953 handleTimedOutNetworkRequest(nri);
2954 break;
2955 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002956 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2957 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2958 break;
2959 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002960 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002961 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002962 break;
2963 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002964 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002965 Network network = (Network) msg.obj;
2966 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002967 break;
2968 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002969 case EVENT_SET_AVOID_UNVALIDATED: {
2970 handleSetAvoidUnvalidated((Network) msg.obj);
2971 break;
2972 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002973 case EVENT_PROMPT_UNVALIDATED: {
2974 handlePromptUnvalidated((Network) msg.obj);
2975 break;
2976 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002977 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2978 handleMobileDataAlwaysOn();
2979 break;
2980 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002981 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2982 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2983 mKeepaliveTracker.handleStartKeepalive(msg);
2984 break;
2985 }
2986 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2987 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2988 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2989 int slot = msg.arg1;
2990 int reason = msg.arg2;
2991 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2992 break;
2993 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002994 case EVENT_SYSTEM_READY: {
2995 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2996 nai.networkMonitor.systemReady = true;
2997 }
2998 break;
2999 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003000 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003001 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003002 break;
3003 }
Erik Klinea24d4592018-01-11 21:07:29 +09003004 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3005 handlePrivateDnsSettingsChanged();
3006 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003007 }
3008 }
3009 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003010
3011 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003012 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003013 public int tether(String iface, String callerPkg) {
3014 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003015 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003016 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003017 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003018 } else {
3019 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3020 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003021 }
3022
3023 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003024 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003025 public int untether(String iface, String callerPkg) {
3026 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003027
3028 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003029 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003030 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003031 } else {
3032 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3033 }
3034 }
3035
3036 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003037 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003038 public int getLastTetherError(String iface) {
3039 enforceTetherAccessPermission();
3040
3041 if (isTetheringSupported()) {
3042 return mTethering.getLastTetherError(iface);
3043 } else {
3044 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3045 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003046 }
3047
3048 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003049 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003050 public String[] getTetherableUsbRegexs() {
3051 enforceTetherAccessPermission();
3052 if (isTetheringSupported()) {
3053 return mTethering.getTetherableUsbRegexs();
3054 } else {
3055 return new String[0];
3056 }
3057 }
3058
Lorenzo Colitti18660282016-07-04 12:55:44 +09003059 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003060 public String[] getTetherableWifiRegexs() {
3061 enforceTetherAccessPermission();
3062 if (isTetheringSupported()) {
3063 return mTethering.getTetherableWifiRegexs();
3064 } else {
3065 return new String[0];
3066 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003067 }
3068
Lorenzo Colitti18660282016-07-04 12:55:44 +09003069 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003070 public String[] getTetherableBluetoothRegexs() {
3071 enforceTetherAccessPermission();
3072 if (isTetheringSupported()) {
3073 return mTethering.getTetherableBluetoothRegexs();
3074 } else {
3075 return new String[0];
3076 }
3077 }
3078
Lorenzo Colitti18660282016-07-04 12:55:44 +09003079 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003080 public int setUsbTethering(boolean enable, String callerPkg) {
3081 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003082 if (isTetheringSupported()) {
3083 return mTethering.setUsbTethering(enable);
3084 } else {
3085 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3086 }
3087 }
3088
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003089 // TODO - move iface listing, queries, etc to new module
3090 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003091 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003092 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003093 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003094 return mTethering.getTetherableIfaces();
3095 }
3096
Lorenzo Colitti18660282016-07-04 12:55:44 +09003097 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003098 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003099 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003100 return mTethering.getTetheredIfaces();
3101 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003102
Lorenzo Colitti18660282016-07-04 12:55:44 +09003103 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003104 public String[] getTetheringErroredIfaces() {
3105 enforceTetherAccessPermission();
3106 return mTethering.getErroredIfaces();
3107 }
3108
Lorenzo Colitti18660282016-07-04 12:55:44 +09003109 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003110 public String[] getTetheredDhcpRanges() {
3111 enforceConnectivityInternalPermission();
3112 return mTethering.getTetheredDhcpRanges();
3113 }
3114
Udam Saini0e94c362017-06-07 12:06:28 -07003115 @Override
3116 public boolean isTetheringSupported(String callerPkg) {
3117 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3118 return isTetheringSupported();
3119 }
3120
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003121 // if ro.tether.denied = true we default to no tethering
3122 // gservices could set the secure setting to 1 though to enable it on a build where it
3123 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003124 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003125 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3126 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3127 Settings.Global.TETHER_SUPPORTED, defaultVal));
3128 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003129 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003130
3131 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3132 boolean adminUser = false;
3133 final long token = Binder.clearCallingIdentity();
3134 try {
3135 adminUser = mUserManager.isAdminUser();
3136 } finally {
3137 Binder.restoreCallingIdentity(token);
3138 }
3139
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003140 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003141 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003142
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003143 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003144 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3145 String callerPkg) {
3146 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003147 if (!isTetheringSupported()) {
3148 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3149 return;
3150 }
3151 mTethering.startTethering(type, receiver, showProvisioningUi);
3152 }
3153
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003154 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003155 public void stopTethering(int type, String callerPkg) {
3156 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003157 mTethering.stopTethering(type);
3158 }
3159
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003160 // Called when we lose the default network and have no replacement yet.
3161 // This will automatically be cleared after X seconds or a new default network
3162 // becomes CONNECTED, whichever happens first. The timer is started by the
3163 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003164 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003165 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003166 if (mNetTransitionWakeLock.isHeld()) {
3167 return;
3168 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003169 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003170 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3171 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003172 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003173 mWakelockLogs.log("ACQUIRE for " + forWhom);
3174 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3175 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003176 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003177
Hugo Benichi4c31b342017-03-30 23:18:10 +09003178 // Called when we gain a new default network to release the network transition wakelock in a
3179 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3180 // message is cancelled.
3181 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003182 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003183 if (!mNetTransitionWakeLock.isHeld()) {
3184 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003185 }
3186 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003187 // Cancel self timeout on wakelock hold.
3188 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3189 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3190 mHandler.sendMessageDelayed(msg, 1000);
3191 }
3192
3193 // Called when either message of ensureNetworkTransitionWakelock or
3194 // scheduleReleaseNetworkTransitionWakelock is processed.
3195 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3196 String event = eventName(eventId);
3197 synchronized (this) {
3198 if (!mNetTransitionWakeLock.isHeld()) {
3199 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3200 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3201 return;
3202 }
3203 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003204 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3205 mTotalWakelockDurationMs += lockDuration;
3206 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3207 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003208 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003209 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003210 }
3211
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003212 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003213 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003214 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003215 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003216 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003217 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003218 }
3219
Lorenzo Colitti18660282016-07-04 12:55:44 +09003220 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003221 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003222 enforceAccessPermission();
3223 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003224 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003225 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003226 mHandler.sendMessage(
3227 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3228 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003229
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003230 private void handleReportNetworkConnectivity(
3231 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003232 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003233 if (network == null) {
3234 nai = getDefaultNetwork();
3235 } else {
3236 nai = getNetworkAgentInfoForNetwork(network);
3237 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003238 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3239 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3240 return;
3241 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003242 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003243 if (hasConnectivity == nai.lastValidated) {
3244 return;
3245 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003246 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003247 int netid = nai.network.netId;
3248 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003249 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003250 // Validating a network that has not yet connected could result in a call to
3251 // rematchNetworkAndRequests() which is not meant to work on such networks.
3252 if (!nai.everConnected) {
3253 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003254 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003255 LinkProperties lp = getLinkProperties(nai);
3256 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3257 return;
3258 }
3259 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003260 }
3261
Paul Jensencee9b512015-05-06 07:32:40 -04003262 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003263 // this information is already available as a world read/writable jvm property
3264 // so this API change wouldn't have a benifit. It also breaks the passing
3265 // of proxy info to all the JVMs.
3266 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003267 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003268 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003269 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3270 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003271 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003272 }
3273
Lorenzo Colitti18660282016-07-04 12:55:44 +09003274 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003275 public ProxyInfo getProxyForNetwork(Network network) {
3276 if (network == null) return getDefaultProxy();
3277 final ProxyInfo globalProxy = getGlobalProxy();
3278 if (globalProxy != null) return globalProxy;
3279 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3280 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3281 // caller may not have.
3282 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3283 if (nai == null) return null;
3284 synchronized (nai) {
3285 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3286 if (proxyInfo == null) return null;
3287 return new ProxyInfo(proxyInfo);
3288 }
3289 }
3290
Paul Jensene0bef712014-12-10 15:12:18 -05003291 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3292 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3293 // proxy is null then there is no proxy in place).
3294 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3295 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3296 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3297 proxy = null;
3298 }
3299 return proxy;
3300 }
3301
3302 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3303 // better for determining if a new proxy broadcast is necessary:
3304 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3305 // avoid unnecessary broadcasts.
3306 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3307 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3308 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3309 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3310 // all set.
3311 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3312 a = canonicalizeProxyInfo(a);
3313 b = canonicalizeProxyInfo(b);
3314 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3315 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3316 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3317 }
3318
Jason Monk207900c2014-04-25 15:00:09 -04003319 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003320 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003321
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003322 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003323 if (proxyProperties == mGlobalProxy) return;
3324 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3325 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3326
3327 String host = "";
3328 int port = 0;
3329 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003330 String pacFileUrl = "";
3331 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003332 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003333 if (!proxyProperties.isValid()) {
3334 if (DBG)
3335 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3336 return;
3337 }
Jason Monk207900c2014-04-25 15:00:09 -04003338 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003339 host = mGlobalProxy.getHost();
3340 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003341 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003342 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003343 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003344 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003345 } else {
3346 mGlobalProxy = null;
3347 }
3348 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003349 final long token = Binder.clearCallingIdentity();
3350 try {
3351 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3352 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3353 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3354 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003355 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003356 } finally {
3357 Binder.restoreCallingIdentity(token);
3358 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003359
Jason Monkcf0f97a2014-10-02 15:39:38 -04003360 if (mGlobalProxy == null) {
3361 proxyProperties = mDefaultProxy;
3362 }
3363 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003364 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003365 }
3366
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003367 private void loadGlobalProxy() {
3368 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003369 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3370 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3371 String exclList = Settings.Global.getString(res,
3372 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003373 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3374 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003375 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003376 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003377 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003378 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003379 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003380 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003381 if (!proxyProperties.isValid()) {
3382 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3383 return;
3384 }
3385
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003386 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003387 mGlobalProxy = proxyProperties;
3388 }
3389 }
3390 }
3391
Jason Monk207900c2014-04-25 15:00:09 -04003392 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003393 // this information is already available as a world read/writable jvm property
3394 // so this API change wouldn't have a benifit. It also breaks the passing
3395 // of proxy info to all the JVMs.
3396 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003397 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003398 return mGlobalProxy;
3399 }
3400 }
3401
Jason Monk207900c2014-04-25 15:00:09 -04003402 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003403 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003404 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003405 proxy = null;
3406 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003407 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003408 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003409 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003410 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003411 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3412 return;
3413 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003414
3415 // This call could be coming from the PacManager, containing the port of the local
3416 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3417 // global (to get the correct local port), and send a broadcast.
3418 // TODO: Switch PacManager to have its own message to send back rather than
3419 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003420 if ((mGlobalProxy != null) && (proxy != null)
3421 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003422 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3423 mGlobalProxy = proxy;
3424 sendProxyBroadcast(mGlobalProxy);
3425 return;
3426 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003427 mDefaultProxy = proxy;
3428
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003429 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003430 if (!mDefaultProxyDisabled) {
3431 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003432 }
3433 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003434 }
3435
Paul Jensene0bef712014-12-10 15:12:18 -05003436 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3437 // This method gets called when any network changes proxy, but the broadcast only ever contains
3438 // the default proxy (even if it hasn't changed).
3439 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3440 // world where an app might be bound to a non-default network.
3441 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3442 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3443 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3444
3445 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3446 sendProxyBroadcast(getDefaultProxy());
3447 }
3448 }
3449
Robert Greenwalt434203a2010-10-11 16:00:27 -07003450 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003451 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3452 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003453 if (!TextUtils.isEmpty(proxy)) {
3454 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003455 if (data.length == 0) {
3456 return;
3457 }
3458
Robert Greenwalt434203a2010-10-11 16:00:27 -07003459 String proxyHost = data[0];
3460 int proxyPort = 8080;
3461 if (data.length > 1) {
3462 try {
3463 proxyPort = Integer.parseInt(data[1]);
3464 } catch (NumberFormatException e) {
3465 return;
3466 }
3467 }
Jason Monk207900c2014-04-25 15:00:09 -04003468 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003469 setGlobalProxy(p);
3470 }
3471 }
3472
Jason Monk207900c2014-04-25 15:00:09 -04003473 private void sendProxyBroadcast(ProxyInfo proxy) {
3474 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003475 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003476 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003477 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003478 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3479 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003480 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003481 final long ident = Binder.clearCallingIdentity();
3482 try {
3483 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3484 } finally {
3485 Binder.restoreCallingIdentity(ident);
3486 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003487 }
3488
3489 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003490 final private HashMap<Uri, Integer> mUriEventMap;
3491 final private Context mContext;
3492 final private Handler mHandler;
3493
3494 SettingsObserver(Context context, Handler handler) {
3495 super(null);
3496 mUriEventMap = new HashMap<Uri, Integer>();
3497 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003498 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003499 }
3500
Erik Klineda4bfa82015-04-30 12:58:40 +09003501 void observe(Uri uri, int what) {
3502 mUriEventMap.put(uri, what);
3503 final ContentResolver resolver = mContext.getContentResolver();
3504 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003505 }
3506
3507 @Override
3508 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003509 Slog.wtf(TAG, "Should never be reached.");
3510 }
3511
3512 @Override
3513 public void onChange(boolean selfChange, Uri uri) {
3514 final Integer what = mUriEventMap.get(uri);
3515 if (what != null) {
3516 mHandler.obtainMessage(what.intValue()).sendToTarget();
3517 } else {
3518 loge("No matching event to send for URI=" + uri);
3519 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003520 }
3521 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003522
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003523 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003524 Slog.d(TAG, s);
3525 }
3526
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003527 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003528 Slog.e(TAG, s);
3529 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003530
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003531 private static void loge(String s, Throwable t) {
3532 Slog.e(TAG, s, t);
3533 }
3534
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003535 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003536 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003537 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3538 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3539 *
3540 * @param oldPackage Package name of the application which currently controls VPN, which will
3541 * be replaced. If there is no such application, this should should either be
3542 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3543 * @param newPackage Package name of the application which should gain control of VPN, or
3544 * {@code null} to disable.
3545 * @param userId User for whom to prepare the new VPN.
3546 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003547 * @hide
3548 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003549 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003550 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3551 int userId) {
3552 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003553
Hugo Benichi20035e02017-04-26 14:53:28 +09003554 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003555 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003556 Vpn vpn = mVpns.get(userId);
3557 if (vpn != null) {
3558 return vpn.prepare(oldPackage, newPackage);
3559 } else {
3560 return false;
3561 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003562 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003563 }
3564
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003565 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003566 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3567 * This method is used by system-privileged apps.
3568 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3569 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3570 *
3571 * @param packageName The package for which authorization state should change.
3572 * @param userId User for whom {@code packageName} is installed.
3573 * @param authorized {@code true} if this app should be able to start a VPN connection without
3574 * explicit user approval, {@code false} if not.
3575 *
Jeff Davidson05542602014-08-11 14:07:27 -07003576 * @hide
3577 */
3578 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003579 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3580 enforceCrossUserPermission(userId);
3581
Hugo Benichi20035e02017-04-26 14:53:28 +09003582 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003583 Vpn vpn = mVpns.get(userId);
3584 if (vpn != null) {
3585 vpn.setPackageAuthorization(packageName, authorized);
3586 }
Jeff Davidson05542602014-08-11 14:07:27 -07003587 }
3588 }
3589
3590 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003591 * Configure a TUN interface and return its file descriptor. Parameters
3592 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003593 * and not available in ConnectivityManager. Permissions are checked in
3594 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003595 * @hide
3596 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003597 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003598 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003599 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003600 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003601 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003602 return mVpns.get(user).establish(config);
3603 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003604 }
3605
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003606 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003607 * Start legacy VPN, controlling native daemons as needed. Creates a
3608 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003609 */
3610 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003611 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003612 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003613 final LinkProperties egress = getActiveLinkProperties();
3614 if (egress == null) {
3615 throw new IllegalStateException("Missing active network connection");
3616 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003617 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003618 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003619 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3620 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003621 }
3622
3623 /**
3624 * Return the information of the ongoing legacy VPN. This method is used
3625 * by VpnSettings and not available in ConnectivityManager. Permissions
3626 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003627 */
3628 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003629 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3630 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003631
Hugo Benichi20035e02017-04-26 14:53:28 +09003632 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003633 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003634 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003635 }
3636
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003637 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003638 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3639 * and not available in ConnectivityManager.
3640 */
3641 @Override
3642 public VpnInfo[] getAllVpnInfo() {
3643 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003644 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003645 if (mLockdownEnabled) {
3646 return new VpnInfo[0];
3647 }
3648
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003649 List<VpnInfo> infoList = new ArrayList<>();
3650 for (int i = 0; i < mVpns.size(); i++) {
3651 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3652 if (info != null) {
3653 infoList.add(info);
3654 }
3655 }
3656 return infoList.toArray(new VpnInfo[infoList.size()]);
3657 }
3658 }
3659
3660 /**
3661 * @return VPN information for accounting, or null if we can't retrieve all required
3662 * information, e.g primary underlying iface.
3663 */
3664 @Nullable
3665 private VpnInfo createVpnInfo(Vpn vpn) {
3666 VpnInfo info = vpn.getVpnInfo();
3667 if (info == null) {
3668 return null;
3669 }
3670 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3671 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3672 // the underlyingNetworks list.
3673 if (underlyingNetworks == null) {
3674 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3675 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3676 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3677 }
3678 } else if (underlyingNetworks.length > 0) {
3679 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3680 if (linkProperties != null) {
3681 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3682 }
3683 }
3684 return info.primaryUnderlyingIface == null ? null : info;
3685 }
3686
3687 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003688 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3689 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003690 * Permissions are checked in Vpn class.
3691 * @hide
3692 */
3693 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003694 public VpnConfig getVpnConfig(int userId) {
3695 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003696 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003697 Vpn vpn = mVpns.get(userId);
3698 if (vpn != null) {
3699 return vpn.getVpnConfig();
3700 } else {
3701 return null;
3702 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003703 }
3704 }
3705
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003706 @Override
3707 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003708 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3709 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3710 return false;
3711 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003712
Hugo Benichi69744342017-11-27 10:57:16 +09003713 synchronized (mVpns) {
3714 // Tear down existing lockdown if profile was removed
3715 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3716 if (mLockdownEnabled) {
3717 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3718 if (profileTag == null) {
3719 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3720 return false;
3721 }
3722 String profileName = new String(profileTag);
3723 final VpnProfile profile = VpnProfile.decode(
3724 profileName, mKeyStore.get(Credentials.VPN + profileName));
3725 if (profile == null) {
3726 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3727 setLockdownTracker(null);
3728 return true;
3729 }
3730 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003731 Vpn vpn = mVpns.get(user);
3732 if (vpn == null) {
3733 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3734 return false;
3735 }
3736 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003737 } else {
3738 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003739 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003740 }
3741
3742 return true;
3743 }
3744
3745 /**
3746 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3747 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3748 */
Hugo Benichi69744342017-11-27 10:57:16 +09003749 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003750 private void setLockdownTracker(LockdownVpnTracker tracker) {
3751 // Shutdown any existing tracker
3752 final LockdownVpnTracker existing = mLockdownTracker;
3753 mLockdownTracker = null;
3754 if (existing != null) {
3755 existing.shutdown();
3756 }
3757
Robin Leec3736bc2017-03-10 16:19:54 +00003758 if (tracker != null) {
3759 mLockdownTracker = tracker;
3760 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003761 }
3762 }
3763
Hugo Benichi69744342017-11-27 10:57:16 +09003764 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003765 private void throwIfLockdownEnabled() {
3766 if (mLockdownEnabled) {
3767 throw new IllegalStateException("Unavailable in lockdown mode");
3768 }
3769 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003770
Robin Lee244ce8e2016-01-05 18:03:46 +00003771 /**
Robin Lee17e61832016-05-09 13:46:28 +01003772 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3773 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003774 *
Robin Lee17e61832016-05-09 13:46:28 +01003775 * @return {@code true} if the service was started, the service was already connected, or there
3776 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003777 */
Robin Lee17e61832016-05-09 13:46:28 +01003778 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003779 synchronized (mVpns) {
3780 Vpn vpn = mVpns.get(userId);
3781 if (vpn == null) {
3782 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3783 // exists already.
3784 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3785 return false;
3786 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003787
Robin Lee812800c2016-05-13 15:38:08 +01003788 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003789 }
3790 }
3791
3792 @Override
Charles He36738632017-05-15 17:07:18 +01003793 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3794 enforceSettingsPermission();
3795 enforceCrossUserPermission(userId);
3796
3797 synchronized (mVpns) {
3798 Vpn vpn = mVpns.get(userId);
3799 if (vpn == null) {
3800 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3801 return false;
3802 }
3803 return vpn.isAlwaysOnPackageSupported(packageName);
3804 }
3805 }
3806
3807 @Override
Robin Leedc679712016-05-03 13:23:03 +01003808 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003809 enforceConnectivityInternalPermission();
3810 enforceCrossUserPermission(userId);
3811
Robin Lee244ce8e2016-01-05 18:03:46 +00003812 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003813 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3814 if (LockdownVpnTracker.isEnabled()) {
3815 return false;
3816 }
3817
Robin Lee244ce8e2016-01-05 18:03:46 +00003818 Vpn vpn = mVpns.get(userId);
3819 if (vpn == null) {
3820 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3821 return false;
3822 }
Robin Lee17e61832016-05-09 13:46:28 +01003823 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003824 return false;
3825 }
Robin Lee17e61832016-05-09 13:46:28 +01003826 if (!startAlwaysOnVpn(userId)) {
3827 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003828 return false;
3829 }
3830 }
3831 return true;
3832 }
3833
3834 @Override
3835 public String getAlwaysOnVpnPackage(int userId) {
3836 enforceConnectivityInternalPermission();
3837 enforceCrossUserPermission(userId);
3838
3839 synchronized (mVpns) {
3840 Vpn vpn = mVpns.get(userId);
3841 if (vpn == null) {
3842 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3843 return null;
3844 }
3845 return vpn.getAlwaysOnPackage();
3846 }
3847 }
3848
Wink Savilleab9321d2013-06-29 21:10:57 -07003849 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003850 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003851 // TODO: Remove? Any reason to trigger a provisioning check?
3852 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003853 }
3854
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003855 /** Location to an updatable file listing carrier provisioning urls.
3856 * An example:
3857 *
3858 * <?xml version="1.0" encoding="utf-8"?>
3859 * <provisioningUrls>
3860 * <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 -07003861 * </provisioningUrls>
3862 */
3863 private static final String PROVISIONING_URL_PATH =
3864 "/data/misc/radio/provisioning_urls.xml";
3865 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003866
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003867 /** XML tag for root element. */
3868 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3869 /** XML tag for individual url */
3870 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003871 /** XML attribute for mcc */
3872 private static final String ATTR_MCC = "mcc";
3873 /** XML attribute for mnc */
3874 private static final String ATTR_MNC = "mnc";
3875
Paul Jensen434dde82015-06-11 09:43:30 -04003876 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003877 FileReader fileReader = null;
3878 XmlPullParser parser = null;
3879 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003880
3881 try {
3882 fileReader = new FileReader(mProvisioningUrlFile);
3883 parser = Xml.newPullParser();
3884 parser.setInput(fileReader);
3885 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3886
3887 while (true) {
3888 XmlUtils.nextElement(parser);
3889
3890 String element = parser.getName();
3891 if (element == null) break;
3892
Paul Jensen434dde82015-06-11 09:43:30 -04003893 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003894 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3895 try {
3896 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3897 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3898 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3899 parser.next();
3900 if (parser.getEventType() == XmlPullParser.TEXT) {
3901 return parser.getText();
3902 }
3903 }
3904 }
3905 } catch (NumberFormatException e) {
3906 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3907 }
3908 }
3909 }
3910 return null;
3911 } catch (FileNotFoundException e) {
3912 loge("Carrier Provisioning Urls file not found");
3913 } catch (XmlPullParserException e) {
3914 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3915 } catch (IOException e) {
3916 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3917 } finally {
3918 if (fileReader != null) {
3919 try {
3920 fileReader.close();
3921 } catch (IOException e) {}
3922 }
3923 }
3924 return null;
3925 }
3926
Wink Saville42d4f082013-07-20 20:31:59 -07003927 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003928 public String getMobileProvisioningUrl() {
3929 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003930 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003931 if (TextUtils.isEmpty(url)) {
3932 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003933 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003934 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003935 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003936 }
Wink Saville8cf35602013-07-10 23:00:07 -07003937 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003938 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003939 String phoneNumber = mTelephonyManager.getLine1Number();
3940 if (TextUtils.isEmpty(phoneNumber)) {
3941 phoneNumber = "0000000000";
3942 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003943 url = String.format(url,
3944 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3945 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003946 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003947 }
3948
Wink Savilleab9321d2013-06-29 21:10:57 -07003949 return url;
3950 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003951
Wink Saville948282b2013-08-29 08:55:16 -07003952 @Override
3953 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003954 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003955 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003956 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3957 return;
3958 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003959 final long ident = Binder.clearCallingIdentity();
3960 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003961 // Concatenate the range of types onto the range of NetIDs.
3962 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3963 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003964 } finally {
3965 Binder.restoreCallingIdentity(ident);
3966 }
Wink Saville948282b2013-08-29 08:55:16 -07003967 }
Wink Saville7788c612013-08-29 14:57:08 -07003968
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003969 @Override
3970 public void setAirplaneMode(boolean enable) {
3971 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003972 final long ident = Binder.clearCallingIdentity();
3973 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003974 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003975 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003976 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3977 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003978 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003979 } finally {
3980 Binder.restoreCallingIdentity(ident);
3981 }
3982 }
3983
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003984 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003985 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003986 Vpn userVpn = mVpns.get(userId);
3987 if (userVpn != null) {
3988 loge("Starting user already has a VPN");
3989 return;
3990 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003991 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003992 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09003993 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3994 updateLockdownVpn();
3995 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003996 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003997 }
3998
3999 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004000 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004001 Vpn userVpn = mVpns.get(userId);
4002 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004003 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004004 return;
4005 }
Robin Lee17e61832016-05-09 13:46:28 +01004006 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004007 mVpns.delete(userId);
4008 }
4009 }
4010
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004011 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004012 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004013 final int vpnsSize = mVpns.size();
4014 for (int i = 0; i < vpnsSize; i++) {
4015 Vpn vpn = mVpns.valueAt(i);
4016 vpn.onUserAdded(userId);
4017 }
4018 }
4019 }
4020
4021 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004022 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004023 final int vpnsSize = mVpns.size();
4024 for (int i = 0; i < vpnsSize; i++) {
4025 Vpn vpn = mVpns.valueAt(i);
4026 vpn.onUserRemoved(userId);
4027 }
4028 }
4029 }
4030
Robin Lee89e7a692016-02-29 14:38:17 +00004031 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004032 synchronized (mVpns) {
4033 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4034 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4035 updateLockdownVpn();
4036 } else {
4037 startAlwaysOnVpn(userId);
4038 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004039 }
4040 }
4041
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004042 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4043 @Override
4044 public void onReceive(Context context, Intent intent) {
4045 final String action = intent.getAction();
4046 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4047 if (userId == UserHandle.USER_NULL) return;
4048
Robin Lee323f29d2016-05-04 16:38:06 +01004049 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004050 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004051 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004052 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004053 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4054 onUserAdded(userId);
4055 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4056 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004057 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4058 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004059 }
4060 }
4061 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004062
Robin Lee95204e02017-01-27 11:59:22 +00004063 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4064 @Override
4065 public void onReceive(Context context, Intent intent) {
4066 // Try creating lockdown tracker, since user present usually means
4067 // unlocked keystore.
4068 updateLockdownVpn();
4069 mContext.unregisterReceiver(this);
4070 }
4071 };
4072
Robert Greenwalta67be032014-05-16 15:49:14 -07004073 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4074 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004075 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4076 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004077
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004078 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4079 // Map from UID to number of NetworkRequests that UID has filed.
4080 @GuardedBy("mUidToNetworkRequestCount")
4081 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4082
Robert Greenwalta67be032014-05-16 15:49:14 -07004083 private static class NetworkFactoryInfo {
4084 public final String name;
4085 public final Messenger messenger;
4086 public final AsyncChannel asyncChannel;
4087
4088 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4089 this.name = name;
4090 this.messenger = messenger;
4091 this.asyncChannel = asyncChannel;
4092 }
4093 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004094
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004095 private void ensureNetworkRequestHasType(NetworkRequest request) {
4096 if (request.type == NetworkRequest.Type.NONE) {
4097 throw new IllegalArgumentException(
4098 "All NetworkRequests in ConnectivityService must have a type");
4099 }
4100 }
4101
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004102 /**
4103 * Tracks info about the requester.
4104 * Also used to notice when the calling process dies so we can self-expire
4105 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004106 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004107 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004108 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004109 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004110 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004111 final int mPid;
4112 final int mUid;
4113 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004114
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004115 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004116 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004117 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004118 mPendingIntent = pi;
4119 messenger = null;
4120 mBinder = null;
4121 mPid = getCallingPid();
4122 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004123 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004124 }
4125
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004126 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004127 super();
4128 messenger = m;
4129 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004130 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004131 mBinder = binder;
4132 mPid = getCallingPid();
4133 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004134 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004135 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004136
4137 try {
4138 mBinder.linkToDeath(this, 0);
4139 } catch (RemoteException e) {
4140 binderDied();
4141 }
4142 }
4143
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004144 private void enforceRequestCountLimit() {
4145 synchronized (mUidToNetworkRequestCount) {
4146 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4147 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004148 throw new ServiceSpecificException(
4149 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004150 }
4151 mUidToNetworkRequestCount.put(mUid, networkRequests);
4152 }
4153 }
4154
Robert Greenwalt9258c642014-03-26 16:47:06 -07004155 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004156 if (mBinder != null) {
4157 mBinder.unlinkToDeath(this, 0);
4158 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004159 }
4160
4161 public void binderDied() {
4162 log("ConnectivityService NetworkRequestInfo binderDied(" +
4163 request + ", " + mBinder + ")");
4164 releaseNetworkRequest(request);
4165 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004166
4167 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004168 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004169 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004170 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004171 }
4172
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004173 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4174 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4175 if (badCapability != null) {
4176 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004177 }
4178 }
4179
Erik Kline9d598e12015-07-13 16:37:51 +09004180 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004181 final SortedSet<Integer> thresholds = new TreeSet();
4182 synchronized (nai) {
4183 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4184 if (nri.request.networkCapabilities.hasSignalStrength() &&
4185 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4186 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4187 }
4188 }
4189 }
Erik Kline9d598e12015-07-13 16:37:51 +09004190 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004191 }
4192
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004193 private void updateSignalStrengthThresholds(
4194 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4195 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004196 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004197 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4198
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004199 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004200 String detail;
4201 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4202 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4203 } else {
4204 detail = reason;
4205 }
4206 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4207 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4208 }
4209
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004210 nai.asyncChannel.sendMessage(
4211 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004212 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004213 }
4214
Etan Cohen859748f2017-04-03 17:42:34 -07004215 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4216 if (nc == null) {
4217 return;
4218 }
4219 NetworkSpecifier ns = nc.getNetworkSpecifier();
4220 if (ns == null) {
4221 return;
4222 }
4223 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4224 ns.assertValidFromUid(Binder.getCallingUid());
4225 }
4226
Robert Greenwalt9258c642014-03-26 16:47:06 -07004227 @Override
4228 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004229 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004230 final NetworkRequest.Type type = (networkCapabilities == null)
4231 ? NetworkRequest.Type.TRACK_DEFAULT
4232 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004233 // If the requested networkCapabilities is null, take them instead from
4234 // the default network request. This allows callers to keep track of
4235 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004236 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004237 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4238 enforceAccessPermission();
4239 } else {
4240 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4241 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004242 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4243 // of the app when the request is filed, but we never change the request if the app
4244 // changes network state. http://b/29964605
4245 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004246 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004247 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004248
Etan Cohenba07c8c2017-02-05 10:42:27 -08004249 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004250 throw new IllegalArgumentException("Bad timeout specified");
4251 }
Etan Cohen859748f2017-04-03 17:42:34 -07004252 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004253
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004254 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004255 nextNetworkRequestId(), type);
4256 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004257 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004258
4259 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004260 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004261 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004262 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004263 }
4264 return networkRequest;
4265 }
4266
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004267 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004268 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004269 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004270 } else {
4271 enforceChangePermission();
4272 }
4273 }
4274
fenglub15e72b2015-03-20 11:29:56 -07004275 @Override
fengludb571472015-04-21 17:12:05 -07004276 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004277 enforceAccessPermission();
4278 NetworkAgentInfo nai = null;
4279 if (network == null) {
4280 return false;
4281 }
4282 synchronized (mNetworkForNetId) {
4283 nai = mNetworkForNetId.get(network.netId);
4284 }
4285 if (nai != null) {
4286 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4287 return true;
4288 }
4289 return false;
4290 }
4291
Felipe Lemeee27cab2016-06-20 16:36:29 -07004292 private boolean isSystem(int uid) {
4293 return uid < Process.FIRST_APPLICATION_UID;
4294 }
fenglub15e72b2015-03-20 11:29:56 -07004295
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004296 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004297 final int uid = Binder.getCallingUid();
4298 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004299 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004300 return;
4301 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004302 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4303 // Policy already enforced.
4304 return;
4305 }
4306 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4307 // If UID is restricted, don't allow them to bring up metered APNs.
4308 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004309 }
4310 }
4311
Robert Greenwalt9258c642014-03-26 16:47:06 -07004312 @Override
4313 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4314 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004315 checkNotNull(operation, "PendingIntent cannot be null.");
4316 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4317 enforceNetworkRequestPermissions(networkCapabilities);
4318 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004319 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004320 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004321
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004322 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004323 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4324 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004325 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004326 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4327 nri));
4328 return networkRequest;
4329 }
4330
Jeremy Joslin79294842014-12-03 17:15:28 -08004331 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4332 mHandler.sendMessageDelayed(
4333 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4334 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4335 }
4336
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004337 @Override
4338 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004339 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004340 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4341 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004342 }
4343
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004344 // In order to implement the compatibility measure for pre-M apps that call
4345 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4346 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4347 // This ensures it has permission to do so.
4348 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4349 if (nc == null) {
4350 return false;
4351 }
4352 int[] transportTypes = nc.getTransportTypes();
4353 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4354 return false;
4355 }
4356 try {
4357 mContext.enforceCallingOrSelfPermission(
4358 android.Manifest.permission.ACCESS_WIFI_STATE,
4359 "ConnectivityService");
4360 } catch (SecurityException e) {
4361 return false;
4362 }
4363 return true;
4364 }
4365
Robert Greenwalt9258c642014-03-26 16:47:06 -07004366 @Override
4367 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4368 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004369 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4370 enforceAccessPermission();
4371 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004372
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004373 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4374 if (!ConnectivityManager.checkChangePermission(mContext)) {
4375 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4376 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4377 // onLost and onAvailable callbacks when networks move in and out of the background.
4378 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4379 // can't request networks.
4380 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4381 }
Etan Cohen859748f2017-04-03 17:42:34 -07004382 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004383
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004384 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004385 NetworkRequest.Type.LISTEN);
4386 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004387 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004388
4389 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4390 return networkRequest;
4391 }
4392
4393 @Override
4394 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4395 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004396 checkNotNull(operation, "PendingIntent cannot be null.");
4397 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4398 enforceAccessPermission();
4399 }
Etan Cohen859748f2017-04-03 17:42:34 -07004400 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004401
Erik Kline7523eb32015-07-09 18:24:03 +09004402 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004403 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4404 NetworkRequest.Type.LISTEN);
4405 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004406 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004407
4408 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004409 }
4410
Erik Klineacdd6392016-07-07 16:50:58 +09004411 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004412 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004413 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004414 mHandler.sendMessage(mHandler.obtainMessage(
4415 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004416 }
4417
4418 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004419 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004420 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004421 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4422 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004423 }
4424
Robert Greenwalta67be032014-05-16 15:49:14 -07004425 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004426 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004427 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4428 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4429 }
4430
4431 @Override
4432 public void unregisterNetworkFactory(Messenger messenger) {
4433 enforceConnectivityInternalPermission();
4434 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4435 }
4436
4437 private void handleUnregisterNetworkFactory(Messenger messenger) {
4438 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4439 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004440 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004441 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004442 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004443 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004444 }
4445
Robert Greenwalt7b816022014-04-18 15:25:25 -07004446 /**
4447 * NetworkAgentInfo supporting a request by requestId.
4448 * These have already been vetted (their Capabilities satisfy the request)
4449 * and the are the highest scored network available.
4450 * the are keyed off the Requests requestId.
4451 */
Hugo Benichicd952782017-09-20 11:20:14 +09004452 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4453 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004454 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4455 new SparseArray<NetworkAgentInfo>();
4456
Paul Jensen31a94f42015-02-13 14:18:39 -05004457 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4458 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004459 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4460 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004461 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4462 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4463 // there may not be a strict 1:1 correlation between the two.
4464 @GuardedBy("mNetworkForNetId")
4465 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004466
Robert Greenwalt7b816022014-04-18 15:25:25 -07004467 // NetworkAgentInfo keyed off its connecting messenger
4468 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004469 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004470 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4471 new HashMap<Messenger, NetworkAgentInfo>();
4472
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004473 @GuardedBy("mBlockedAppUids")
4474 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4475
Paul Jensen2c311d62014-11-17 12:34:51 -05004476 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004477 private final NetworkRequest mDefaultRequest;
4478
Erik Klineda4bfa82015-04-30 12:58:40 +09004479 // Request used to optionally keep mobile data active even when higher
4480 // priority networks like Wi-Fi are active.
4481 private final NetworkRequest mDefaultMobileDataRequest;
4482
Hugo Benichicd952782017-09-20 11:20:14 +09004483 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4484 synchronized (mNetworkForRequestId) {
4485 return mNetworkForRequestId.get(requestId);
4486 }
4487 }
4488
4489 private void clearNetworkForRequest(int requestId) {
4490 synchronized (mNetworkForRequestId) {
4491 mNetworkForRequestId.remove(requestId);
4492 }
4493 }
4494
4495 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4496 synchronized (mNetworkForRequestId) {
4497 mNetworkForRequestId.put(requestId, nai);
4498 }
4499 }
4500
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004501 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004502 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004503 }
4504
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004505 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004506 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004507 }
4508
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004509 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4510 return nri.request.requestId == mDefaultRequest.requestId;
4511 }
4512
Paul Jensen31a94f42015-02-13 14:18:39 -05004513 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004514 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004515 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004516 enforceConnectivityInternalPermission();
4517
Rubin Xu1bb5c082017-09-05 18:40:49 +01004518 LinkProperties lp = new LinkProperties(linkProperties);
4519 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004520 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4521 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004522 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Rubin Xu1bb5c082017-09-05 18:40:49 +01004523 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp,
4524 new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004525 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004526 synchronized (this) {
4527 nai.networkMonitor.systemReady = mSystemReady;
4528 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004529 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4530 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004531 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004532 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004533 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004534 }
4535
4536 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4537 if (VDBG) log("Got NetworkAgent Messenger");
4538 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004539 synchronized (mNetworkForNetId) {
4540 mNetworkForNetId.put(na.network.netId, na);
4541 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004542 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4543 NetworkInfo networkInfo = na.networkInfo;
4544 na.networkInfo = null;
4545 updateNetworkInfo(na, networkInfo);
4546 }
4547
4548 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4549 LinkProperties newLp = networkAgent.linkProperties;
4550 int netId = networkAgent.network.netId;
4551
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004552 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4553 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004554 if (networkAgent.clatd != null) {
4555 networkAgent.clatd.fixupLinkProperties(oldLp);
4556 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004557
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004558 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004559 updateMtu(newLp, oldLp);
4560 // TODO - figure out what to do for clat
4561// for (LinkProperties lp : newLp.getStackedLinks()) {
4562// updateMtu(lp, null);
4563// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004564 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004565
Erik Kline94887872016-04-05 13:30:49 +09004566 updateRoutes(newLp, oldLp, netId);
4567 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004568
Hugo Benichi6f62b732017-06-27 15:13:20 +09004569 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004570 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004571 if (isDefaultNetwork(networkAgent)) {
4572 handleApplyDefaultProxy(newLp.getHttpProxy());
4573 } else {
4574 updateProxy(newLp, oldLp, networkAgent);
4575 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004576 // TODO - move this check to cover the whole function
4577 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004578 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004579 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4580 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004581
4582 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004583 }
4584
Joel Scherpelz668370b2017-06-08 15:35:21 +09004585 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004586 // Marks are only available on WiFi interaces. Checking for
4587 // marks on unsupported interfaces is harmless.
4588 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4589 return;
4590 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004591
Joel Scherpelz668370b2017-06-08 15:35:21 +09004592 int mark = mContext.getResources().getInteger(
4593 com.android.internal.R.integer.config_networkWakeupPacketMark);
4594 int mask = mContext.getResources().getInteger(
4595 com.android.internal.R.integer.config_networkWakeupPacketMask);
4596
4597 // Mask/mark of zero will not detect anything interesting.
4598 // Don't install rules unless both values are nonzero.
4599 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004600 return;
4601 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004602
4603 final String prefix = "iface:" + iface;
4604 try {
4605 if (add) {
4606 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4607 } else {
4608 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4609 }
4610 } catch (Exception e) {
4611 loge("Exception modifying wakeup packet monitoring: " + e);
4612 }
4613
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004614 }
4615
4616 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4617 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004618 CompareResult<String> interfaceDiff = new CompareResult<String>(
4619 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4620 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004621 for (String iface : interfaceDiff.added) {
4622 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004623 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004624 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004625 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004626 } catch (Exception e) {
4627 loge("Exception adding interface: " + e);
4628 }
4629 }
4630 for (String iface : interfaceDiff.removed) {
4631 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004632 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004633 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004634 mNetd.removeInterfaceFromNetwork(iface, netId);
4635 } catch (Exception e) {
4636 loge("Exception removing interface: " + e);
4637 }
4638 }
4639 }
4640
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004641 /**
4642 * Have netd update routes from oldLp to newLp.
4643 * @return true if routes changed between oldLp and newLp
4644 */
4645 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004646 // Compare the route diff to determine which routes should be added and removed.
4647 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4648 oldLp != null ? oldLp.getAllRoutes() : null,
4649 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004650
4651 // add routes before removing old in case it helps with continuous connectivity
4652
4653 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4654 for (RouteInfo route : routeDiff.added) {
4655 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004656 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004657 try {
4658 mNetd.addRoute(netId, route);
4659 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004660 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4661 loge("Exception in addRoute for non-gateway: " + e);
4662 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004663 }
4664 }
4665 for (RouteInfo route : routeDiff.added) {
4666 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004667 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004668 try {
4669 mNetd.addRoute(netId, route);
4670 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004671 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4672 loge("Exception in addRoute for gateway: " + e);
4673 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004674 }
4675 }
4676
4677 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004678 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004679 try {
4680 mNetd.removeRoute(netId, route);
4681 } catch (Exception e) {
4682 loge("Exception in removeRoute: " + e);
4683 }
4684 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004685 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004686 }
Erik Kline41368502015-06-17 13:19:54 +09004687
Erik Kline94887872016-04-05 13:30:49 +09004688 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4689 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4690 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004691 }
Erik Kline94887872016-04-05 13:30:49 +09004692
Erik Kline1742fe12017-12-13 19:40:49 +09004693 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4694 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4695
Erik Klinea24d4592018-01-11 21:07:29 +09004696 if (DBG) {
4697 final Collection<InetAddress> dnses = newLp.getDnsServers();
4698 log("Setting DNS servers for network " + netId + " to " + dnses);
4699 }
Erik Kline94887872016-04-05 13:30:49 +09004700 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004701 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004702 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004703 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004704 }
Erik Kline4edba012017-04-07 15:29:29 +09004705 }
4706
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004707 private String getNetworkPermission(NetworkCapabilities nc) {
4708 // TODO: make these permission strings AIDL constants instead.
4709 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4710 return NetworkManagementService.PERMISSION_SYSTEM;
4711 }
4712 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4713 return NetworkManagementService.PERMISSION_NETWORK;
4714 }
4715 return null;
4716 }
4717
Paul Jensen3d194ea2015-06-16 14:27:36 -04004718 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004719 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4720 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4721 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004722 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004723 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004724 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004725 if (nai.everConnected &&
4726 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4727 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004728 // does not cause any request (that is not a listen) currently matching that agent to
4729 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004730 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09004731 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004732 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09004733 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004734 }
4735
Paul Jensen3d194ea2015-06-16 14:27:36 -04004736 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004737 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004738 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004739 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004740 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004741 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004742 }
Paul Jensene0988542015-06-25 15:30:08 -04004743 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004744 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004745 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004746 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004747 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004748 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004749 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004750 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004751 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004752 }
4753
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004754 return newNc;
4755 }
4756
4757 /**
4758 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4759 *
4760 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4761 * capabilities we manage and store in {@code nai}, such as validated status and captive
4762 * portal status)
4763 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4764 * potentially triggers rematches.
4765 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4766 * change.)
4767 *
4768 * @param oldScore score of the network before any of the changes that prompted us
4769 * to call this function.
4770 * @param nai the network having its capabilities updated.
4771 * @param nc the new network capabilities.
4772 */
4773 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4774 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4775
4776 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004777
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004778 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004779 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004780 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004781 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004782 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004783 } catch (RemoteException e) {
4784 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004785 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004786 }
4787
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004788 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004789 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004790 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004791 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004792 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004793
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004794 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004795 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4796 // the change we're processing can't affect any requests, it can only affect the listens
4797 // on this network. We might have been called by rematchNetworkAndRequests when a
4798 // network changed foreground state.
4799 processListenRequests(nai, true);
4800 } else {
4801 // If the requestable capabilities have changed or the score changed, we can't have been
4802 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004803 rematchAllNetworksAndRequests(nai, oldScore);
4804 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004805 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004806
4807 // Report changes that are interesting for network statistics tracking.
4808 if (prevNc != null) {
4809 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004810 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004811 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004812 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004813 if (meteredChanged || roamingChanged) {
4814 notifyIfacesChangedForNetworkStats();
4815 }
4816 }
4817
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004818 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004819 // Tell VPNs about updated capabilities, since they may need to
4820 // bubble those changes through.
4821 synchronized (mVpns) {
4822 for (int i = 0; i < mVpns.size(); i++) {
4823 final Vpn vpn = mVpns.valueAt(i);
4824 vpn.updateCapabilities();
4825 }
4826 }
4827 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004828 }
4829
Hugo Benichief502882017-09-01 01:23:32 +00004830 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
4831 if (mNetworkForNetId.get(nai.network.netId) != nai) {
4832 // Ignore updates for disconnected networks
4833 return;
4834 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004835 // newLp is already a defensive copy.
4836 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004837 if (VDBG) {
4838 log("Update of LinkProperties for " + nai.name() +
4839 "; created=" + nai.created +
4840 "; everConnected=" + nai.everConnected);
4841 }
4842 LinkProperties oldLp = nai.linkProperties;
4843 synchronized (nai) {
4844 nai.linkProperties = newLp;
4845 }
4846 if (nai.everConnected) {
4847 updateLinkProperties(nai, oldLp);
4848 }
4849 }
4850
Paul Jensenc8b9a742014-09-30 15:37:41 -04004851 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004852 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4853 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004854 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004855 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004856 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4857 }
4858 }
4859
Robert Greenwalt7b816022014-04-18 15:25:25 -07004860 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4861 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004862 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004863 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4864 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004865 }
4866 }
4867
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004868 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4869 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004870 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004871 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004872 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4873 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004874 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004875 sendIntent(nri.mPendingIntent, intent);
4876 }
4877 // else not handled
4878 }
4879
4880 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4881 mPendingIntentWakeLock.acquire();
4882 try {
4883 if (DBG) log("Sending " + pendingIntent);
4884 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4885 } catch (PendingIntent.CanceledException e) {
4886 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4887 mPendingIntentWakeLock.release();
4888 releasePendingNetworkRequest(pendingIntent);
4889 }
4890 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4891 }
4892
4893 @Override
4894 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4895 String resultData, Bundle resultExtras) {
4896 if (DBG) log("Finished sending " + pendingIntent);
4897 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004898 // Release with a delay so the receiving client has an opportunity to put in its
4899 // own request.
4900 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004901 }
4902
Hugo Benichidba33db2017-03-23 22:40:44 +09004903 private static void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004904 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004905 if (nri.messenger == null) {
4906 return; // Default request has no msgr
4907 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004908 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004909 // TODO: check if defensive copies of data is needed.
4910 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004911 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004912 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4913 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004914 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004915 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004916 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004917 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004918 break;
4919 }
4920 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004921 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004922 break;
4923 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004924 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004925 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004926 break;
4927 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004928 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004929 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004930 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004931 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004932 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004933 String notification = ConnectivityManager.getCallbackName(notificationType);
4934 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004935 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004936 nri.messenger.send(msg);
4937 } catch (RemoteException e) {
4938 // may occur naturally in the race of binder death.
4939 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4940 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004941 }
4942
Hugo Benichidba33db2017-03-23 22:40:44 +09004943 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4944 bundle.putParcelable(t.getClass().getSimpleName(), t);
4945 }
4946
Paul Jensenc8b9a742014-09-30 15:37:41 -04004947 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004948 if (nai.numRequestNetworkRequests() != 0) {
4949 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4950 NetworkRequest nr = nai.requestAt(i);
4951 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004952 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004953 loge("Dead network still had at least " + nr);
4954 break;
4955 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004956 }
4957 nai.asyncChannel.disconnect();
4958 }
4959
Robert Greenwalt7b816022014-04-18 15:25:25 -07004960 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4961 if (oldNetwork == null) {
4962 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4963 return;
4964 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004965 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004966
4967 // If we get here it means that the last linger timeout for this network expired. So there
4968 // must be no other active linger timers, and we must stop lingering.
4969 oldNetwork.clearLingerState();
4970
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004971 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004972 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004973 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004974 } else {
4975 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004976 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4977 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004978 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004979 }
4980
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004981 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004982 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004983 setupDataActivityTracking(newNetwork);
4984 try {
4985 mNetd.setDefaultNetId(newNetwork.network.netId);
4986 } catch (Exception e) {
4987 loge("Exception setting default network :" + e);
4988 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09004989
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004990 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004991 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004992 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09004993 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09004994 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04004995 }
4996
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004997 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004998 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4999 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5000 NetworkRequest nr = nri.request;
5001 if (!nr.isListen()) continue;
5002 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5003 nai.removeRequest(nri.request.requestId);
5004 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5005 }
5006 }
5007
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005008 if (capabilitiesChanged) {
5009 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5010 }
5011
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005012 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5013 NetworkRequest nr = nri.request;
5014 if (!nr.isListen()) continue;
5015 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5016 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005017 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005018 }
5019 }
5020 }
5021
Paul Jensen2161a8e2014-09-11 11:00:39 -04005022 // Handles a network appearing or improving its score.
5023 //
5024 // - Evaluates all current NetworkRequests that can be
5025 // satisfied by newNetwork, and reassigns to newNetwork
5026 // any such requests for which newNetwork is the best.
5027 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005028 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005029 // needed. A network is needed if it is the best network for
5030 // one or more NetworkRequests, or if it is a VPN.
5031 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005032 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005033 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005034 //
5035 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5036 // networks that have no chance (i.e. even if validated)
5037 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005038 //
5039 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5040 // it does not remove NetworkRequests that other Networks could better satisfy.
5041 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5042 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5043 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005044 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005045 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005046 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5047 // performed to tear down unvalidated networks that have no chance (i.e. even if
5048 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005049 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005050 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005051 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005052 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005053 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005054 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005055
5056 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5057 final int score = newNetwork.getCurrentScore();
5058
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005059 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005060
Paul Jensen2161a8e2014-09-11 11:00:39 -04005061 // Find and migrate to this Network any NetworkRequests for
5062 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07005063 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04005064 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005065 NetworkCapabilities nc = newNetwork.networkCapabilities;
5066 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005067 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005068 // Process requests in the first pass and listens in the second pass. This allows us to
5069 // change a network's capabilities depending on which requests it has. This is only
5070 // correct if the change in capabilities doesn't affect whether the network satisfies
5071 // requests or not, and doesn't affect the network's score.
5072 if (nri.request.isListen()) continue;
5073
Hugo Benichicd952782017-09-20 11:20:14 +09005074 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005075 final boolean satisfies = newNetwork.satisfies(nri.request);
5076 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005077 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005078 log("Network " + newNetwork.name() + " was already satisfying" +
5079 " request " + nri.request.requestId + ". No change.");
5080 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005081 keep = true;
5082 continue;
5083 }
5084
5085 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005086 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005087 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005088 // next check if it's better than any current network we're using for
5089 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005090 if (VDBG) {
5091 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005092 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005093 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005094 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005095 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005096 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005097 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005098 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005099 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005100 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005101 affectedNetworks.add(currentNetwork);
5102 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005103 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005104 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005105 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005106 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005107 if (!newNetwork.addRequest(nri.request)) {
5108 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5109 }
5110 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005111 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005112 // Tell NetworkFactories about the new score, so they can stop
5113 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005114 // TODO - this could get expensive if we have alot of requests for this
5115 // network. Think about if there is a way to reduce this. Push
5116 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005117 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005118 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005119 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005120 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005121 if (currentNetwork != null) {
5122 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5123 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005124 }
5125 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005126 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005127 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5128 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005129 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005130 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5131 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5132 // This means this code doesn't have to handle the case where "currentNetwork" no
5133 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5134 if (DBG) {
5135 log("Network " + newNetwork.name() + " stopped satisfying" +
5136 " request " + nri.request.requestId);
5137 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005138 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005139 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005140 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005141 sendUpdatedScoreToFactories(nri.request, 0);
5142 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005143 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5144 newNetwork.name() +
5145 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005146 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005147 // TODO: Technically, sending CALLBACK_LOST here is
5148 // incorrect if there is a replacement network currently
5149 // connected that can satisfy nri, which is a request
5150 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005151 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5152 // so this code is only incorrect for a network that loses
5153 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005154 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005155 }
5156 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005157 if (isNewDefault) {
5158 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005159 makeDefault(newNetwork);
5160 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005161 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005162 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005163 // Have a new default network, release the transition wakelock in
5164 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005165 }
5166
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005167 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5168 Slog.wtf(TAG, String.format(
5169 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005170 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005171 }
5172 if (newNetwork.getCurrentScore() != score) {
5173 Slog.wtf(TAG, String.format(
5174 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005175 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005176 }
5177
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005178 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005179 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5180 // If the network went from background to foreground or vice versa, we need to update
5181 // its foreground state. It is safe to do this after rematching the requests because
5182 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5183 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005184 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005185 } else {
5186 processListenRequests(newNetwork, false);
5187 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005188
Paul Jensencf4c2c62015-07-01 14:16:32 -04005189 // do this after the default net is switched, but
5190 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005191 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005192
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005193 // Linger any networks that are no longer needed. This should be done after sending the
5194 // available callback for newNetwork.
5195 for (NetworkAgentInfo nai : affectedNetworks) {
5196 updateLingerState(nai, now);
5197 }
5198 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5199 // does not need to be done in any particular order.
5200 updateLingerState(newNetwork, now);
5201
Paul Jensencf4c2c62015-07-01 14:16:32 -04005202 if (isNewDefault) {
5203 // Maintain the illusion: since the legacy API only
5204 // understands one network at a time, we must pretend
5205 // that the current default network disconnected before
5206 // the new one connected.
5207 if (oldDefaultNetwork != null) {
5208 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5209 oldDefaultNetwork, true);
5210 }
5211 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5212 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5213 notifyLockdownVpn(newNetwork);
5214 }
5215
Robert Greenwalt7b816022014-04-18 15:25:25 -07005216 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005217 // Notify battery stats service about this network, both the normal
5218 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005219 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005220 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005221 final IBatteryStats bs = BatteryStatsService.getService();
5222 final int type = newNetwork.networkInfo.getType();
5223
5224 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5225 bs.noteNetworkInterfaceType(baseIface, type);
5226 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5227 final String stackedIface = stacked.getInterfaceName();
5228 bs.noteNetworkInterfaceType(stackedIface, type);
5229 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5230 }
5231 } catch (RemoteException ignored) {
5232 }
5233
Robert Greenwalt152ed372014-12-17 17:19:53 -08005234 // This has to happen after the notifyNetworkCallbacks as that tickles each
5235 // ConnectivityManager instance so that legacy requests correctly bind dns
5236 // requests to this network. The legacy users are listening for this bcast
5237 // and will generally do a dns request so they can ensureRouteToHost and if
5238 // they do that before the callbacks happen they'll use the default network.
5239 //
5240 // TODO: Is there still a race here? We send the broadcast
5241 // after sending the callback, but if the app can receive the
5242 // broadcast before the callback, it might still break.
5243 //
5244 // This *does* introduce a race where if the user uses the new api
5245 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5246 // they may get old info. Reverse this after the old startUsing api is removed.
5247 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005248 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5249 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005250 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005251 // legacy type tracker filters out repeat adds
5252 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5253 }
5254 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005255
5256 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5257 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5258 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5259 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5260 if (newNetwork.isVPN()) {
5261 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5262 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005263 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005264 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5265 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005266 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005267 if (nai.getLingerExpiry() > 0) {
5268 // This network has active linger timers and no requests, but is not
5269 // lingering. Linger it.
5270 //
5271 // One way (the only way?) this can happen if this network is unvalidated
5272 // and became unneeded due to another network improving its score to the
5273 // point where this network will no longer be able to satisfy any requests
5274 // even if it validates.
5275 updateLingerState(nai, now);
5276 } else {
5277 if (DBG) log("Reaping " + nai.name());
5278 teardownUnneededNetwork(nai);
5279 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005280 }
5281 }
5282 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005283 }
5284
Paul Jensen1c7ba022015-06-16 14:27:36 -04005285 /**
5286 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5287 * being disconnected.
5288 * @param changed If only one Network's score or capabilities have been modified since the last
5289 * time this function was called, pass this Network in this argument, otherwise pass
5290 * null.
5291 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5292 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5293 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5294 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5295 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005296 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005297 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005298 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5299 // to avoid the slowness. It is not simply enough to process just "changed", for
5300 // example in the case where "changed"'s score decreases and another network should begin
5301 // satifying a NetworkRequest that "changed" currently satisfies.
5302
5303 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5304 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5305 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005306 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005307 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005308 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005309 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005310 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5311 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5312 // Rematch higher scoring networks first to prevent requests first matching a lower
5313 // scoring network and then a higher scoring network, which could produce multiple
5314 // callbacks and inadvertently unlinger networks.
5315 Arrays.sort(nais);
5316 for (NetworkAgentInfo nai : nais) {
5317 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005318 // Only reap the last time through the loop. Reaping before all rematching
5319 // is complete could incorrectly teardown a network that hasn't yet been
5320 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005321 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005322 : ReapUnvalidatedNetworks.REAP,
5323 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005324 }
5325 }
5326 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005327
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005328 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005329 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005330 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005331 // For now only update icons for default connection.
5332 // TODO: Update WiFi and cellular icons separately. b/17237507
5333 if (!isDefaultNetwork(nai)) return;
5334
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005335 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005336 // Don't repeat publish.
5337 if (newInetCondition == mDefaultInetConditionPublished) return;
5338
5339 mDefaultInetConditionPublished = newInetCondition;
5340 sendInetConditionBroadcast(nai.networkInfo);
5341 }
5342
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005343 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005344 synchronized (mVpns) {
5345 if (mLockdownTracker != null) {
5346 if (nai != null && nai.isVPN()) {
5347 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5348 } else {
5349 mLockdownTracker.onNetworkInfoChanged();
5350 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005351 }
5352 }
5353 }
5354
Robert Greenwalt7b816022014-04-18 15:25:25 -07005355 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005356 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005357 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005358 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005359 synchronized (networkAgent) {
5360 oldInfo = networkAgent.networkInfo;
5361 networkAgent.networkInfo = newInfo;
5362 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005363 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005364
Robert Greenwalt7b816022014-04-18 15:25:25 -07005365 if (DBG) {
5366 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5367 (oldInfo == null ? "null" : oldInfo.getState()) +
5368 " to " + state);
5369 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005370
Robin Lee585e2482016-05-01 23:00:00 +01005371 if (!networkAgent.created
5372 && (state == NetworkInfo.State.CONNECTED
5373 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005374
5375 // A network that has just connected has zero requests and is thus a foreground network.
5376 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5377
Robert Greenwalt7b816022014-04-18 15:25:25 -07005378 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005379 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005380 if (networkAgent.isVPN()) {
5381 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005382 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5383 (networkAgent.networkMisc == null ||
5384 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005385 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005386 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005387 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005388 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005389 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005390 loge("Error creating network " + networkAgent.network.netId + ": "
5391 + e.getMessage());
5392 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005393 }
Paul Jenseneec75412014-08-04 12:21:19 -04005394 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005395 }
5396
5397 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5398 networkAgent.everConnected = true;
5399
Robert Greenwalt7b816022014-04-18 15:25:25 -07005400 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005401 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005402
Paul Jensenca8f16a2014-05-09 12:47:55 -04005403 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005404 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005405
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005406 if (networkAgent.isVPN()) {
5407 // Temporarily disable the default proxy (not global).
5408 synchronized (mProxyLock) {
5409 if (!mDefaultProxyDisabled) {
5410 mDefaultProxyDisabled = true;
5411 if (mGlobalProxy == null && mDefaultProxy != null) {
5412 sendProxyBroadcast(null);
5413 }
5414 }
5415 }
5416 // TODO: support proxy per network.
5417 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005418
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005419 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5420 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5421 // capabilities, so it only needs to be done once on initial connect, not every time the
5422 // network's capabilities change. Note that we do this before rematching the network,
5423 // so we could decide to tear it down immediately afterwards. That's fine though - on
5424 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5425 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005426 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005427
Paul Jensen2161a8e2014-09-11 11:00:39 -04005428 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005429 final long now = SystemClock.elapsedRealtime();
5430 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005431
5432 // This has to happen after matching the requests, because callbacks are just requests.
5433 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005434 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005435 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005436 if (networkAgent.isVPN()) {
5437 synchronized (mProxyLock) {
5438 if (mDefaultProxyDisabled) {
5439 mDefaultProxyDisabled = false;
5440 if (mGlobalProxy == null && mDefaultProxy != null) {
5441 sendProxyBroadcast(mDefaultProxy);
5442 }
5443 }
5444 }
5445 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005446 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5447 state == NetworkInfo.State.SUSPENDED) {
5448 // going into or coming out of SUSPEND: rescore and notify
5449 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005450 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005451 }
5452 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5453 ConnectivityManager.CALLBACK_SUSPENDED :
5454 ConnectivityManager.CALLBACK_RESUMED));
5455 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005456 }
5457 }
5458
Robert Greenwaltac96c522014-06-03 16:43:57 -07005459 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005460 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005461 if (score < 0) {
5462 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5463 "). Bumping score to min of 0");
5464 score = 0;
5465 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005466
Paul Jensen2161a8e2014-09-11 11:00:39 -04005467 final int oldScore = nai.getCurrentScore();
5468 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005469
Paul Jensen85cf78e2015-06-25 13:25:07 -04005470 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005471
Paul Jensenc8b9a742014-09-30 15:37:41 -04005472 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005473 }
5474
Erik Klinec75d4fa2017-02-15 19:59:17 +09005475 // Notify only this one new request of the current state. Transfer all the
5476 // current state by calling NetworkCapabilities and LinkProperties callbacks
5477 // so that callers can be guaranteed to have as close to atomicity in state
5478 // transfer as can be supported by this current API.
5479 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005480 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005481 if (nri.mPendingIntent != null) {
5482 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5483 // Attempt no subsequent state pushes where intents are involved.
5484 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005485 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005486
5487 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5488 // Whether a network is currently suspended is also an important
5489 // element of state to be transferred (it would not otherwise be
5490 // delivered by any currently available mechanism).
5491 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5492 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5493 }
5494 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5495 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005496 }
5497
Robert Greenwalt8d482522015-06-24 13:23:42 -07005498 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005499 // The NetworkInfo we actually send out has no bearing on the real
5500 // state of affairs. For example, if the default connection is mobile,
5501 // and a request for HIPRI has just gone away, we need to pretend that
5502 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5503 // the state to DISCONNECTED, even though the network is of type MOBILE
5504 // and is still connected.
5505 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5506 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005507 if (state != DetailedState.DISCONNECTED) {
5508 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005509 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005510 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005511 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005512 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5513 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5514 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5515 if (info.isFailover()) {
5516 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5517 nai.networkInfo.setFailover(false);
5518 }
5519 if (info.getReason() != null) {
5520 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5521 }
5522 if (info.getExtraInfo() != null) {
5523 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5524 }
5525 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005526 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005527 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005528 if (newDefaultAgent != null) {
5529 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5530 newDefaultAgent.networkInfo);
5531 } else {
5532 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5533 }
5534 }
5535 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5536 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005537 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005538 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005539 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005540 }
5541 }
5542 }
5543
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005544 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005545 if (VDBG) {
5546 String notification = ConnectivityManager.getCallbackName(notifyType);
5547 log("notifyType " + notification + " for " + networkAgent.name());
5548 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005549 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5550 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005551 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5552 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005553 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5554 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005555 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005556 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005557 } else {
5558 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5559 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005560 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005561 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005562
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005563 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5564 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5565 }
5566
Jeff Sharkey69736342014-12-08 14:50:12 -08005567 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005568 * Returns the list of all interfaces that could be used by network traffic that does not
5569 * explicitly specify a network. This includes the default network, but also all VPNs that are
5570 * currently connected.
5571 *
5572 * Must be called on the handler thread.
5573 */
5574 private Network[] getDefaultNetworks() {
5575 ArrayList<Network> defaultNetworks = new ArrayList<>();
5576 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5577 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5578 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5579 defaultNetworks.add(nai.network);
5580 }
5581 }
5582 return defaultNetworks.toArray(new Network[0]);
5583 }
5584
5585 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005586 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5587 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005588 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005589 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005590 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005591 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005592 } catch (Exception ignored) {
5593 }
5594 }
5595
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005596 @Override
5597 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005598 int user = UserHandle.getUserId(Binder.getCallingUid());
5599 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005600 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005601 return mVpns.get(user).addAddress(address, prefixLength);
5602 }
5603 }
5604
5605 @Override
5606 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005607 int user = UserHandle.getUserId(Binder.getCallingUid());
5608 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005609 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005610 return mVpns.get(user).removeAddress(address, prefixLength);
5611 }
5612 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005613
5614 @Override
5615 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005616 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005617 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005618 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005619 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005620 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005621 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005622 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005623 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005624 }
5625 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005626 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005627
5628 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005629 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07005630 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005631 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005632 }
5633
5634 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005635 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5636 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5637 enforceKeepalivePermission();
5638 mKeepaliveTracker.startNattKeepalive(
5639 getNetworkAgentInfoForNetwork(network),
5640 intervalSeconds, messenger, binder,
5641 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5642 }
5643
5644 @Override
5645 public void stopKeepalive(Network network, int slot) {
5646 mHandler.sendMessage(mHandler.obtainMessage(
5647 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5648 }
5649
5650 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005651 public void factoryReset() {
5652 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005653
5654 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5655 return;
5656 }
5657
Robin Lee3b3dd942015-05-12 18:14:58 +01005658 final int userId = UserHandle.getCallingUserId();
5659
Stuart Scottf1fb3972015-04-02 18:00:02 -07005660 // Turn airplane mode off
5661 setAirplaneMode(false);
5662
Stuart Scotte3e314d2015-04-20 14:07:45 -07005663 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5664 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005665 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005666 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005667 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005668 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005669 }
5670
Stuart Scotte3e314d2015-04-20 14:07:45 -07005671 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005672 // Remove always-on package
5673 synchronized (mVpns) {
5674 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5675 if (alwaysOnPackage != null) {
5676 setAlwaysOnVpnPackage(userId, null, false);
5677 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5678 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005679
Hugo Benichi69744342017-11-27 10:57:16 +09005680 // Turn Always-on VPN off
5681 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5682 final long ident = Binder.clearCallingIdentity();
5683 try {
5684 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5685 mLockdownEnabled = false;
5686 setLockdownTracker(null);
5687 } finally {
5688 Binder.restoreCallingIdentity(ident);
5689 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005690 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005691
Hugo Benichi69744342017-11-27 10:57:16 +09005692 // Turn VPN off
5693 VpnConfig vpnConfig = getVpnConfig(userId);
5694 if (vpnConfig != null) {
5695 if (vpnConfig.legacy) {
5696 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5697 } else {
5698 // Prevent this app (packagename = vpnConfig.user) from initiating
5699 // VPN connections in the future without user intervention.
5700 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005701
Hugo Benichi69744342017-11-27 10:57:16 +09005702 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5703 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005704 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005705 }
5706 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005707
5708 Settings.Global.putString(mContext.getContentResolver(),
5709 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005710 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005711
Ricky Wai44dcbde2018-01-23 04:09:45 +00005712 @Override
5713 public byte[] getNetworkWatchlistConfigHash() {
5714 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
5715 if (nwm == null) {
5716 loge("Unable to get NetworkWatchlistManager");
5717 return null;
5718 }
5719 // Redirect it to network watchlist service to access watchlist file and calculate hash.
5720 return nwm.getWatchlistConfigHash();
5721 }
5722
Paul Jensencf4c2c62015-07-01 14:16:32 -04005723 @VisibleForTesting
5724 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5725 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5726 return new NetworkMonitor(context, handler, nai, defaultRequest);
5727 }
Erik Kline48f12f22016-04-14 17:30:59 +09005728
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005729 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005730 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5731 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005732 }
5733
5734 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005735 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5736 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5737 }
5738
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005739 @VisibleForTesting
5740 public boolean hasService(String name) {
5741 return ServiceManager.checkService(name) != null;
5742 }
5743
Hugo Benichi64901e52017-10-19 14:42:40 +09005744 @VisibleForTesting
5745 protected IpConnectivityMetrics.Logger metricsLogger() {
5746 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5747 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005748 }
5749
5750 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005751 int[] transports = nai.networkCapabilities.getTransportTypes();
5752 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005753 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005754
5755 private static boolean toBool(int encodedBoolean) {
5756 return encodedBoolean != 0; // Only 0 means false.
5757 }
5758
5759 private static int encodeBool(boolean b) {
5760 return b ? 1 : 0;
5761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005762}