blob: 20bf9966c8ad80eff64b7e24ade74bfd235c7486 [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;
Chalard Jeanb552c462018-02-21 18:43:54 +090020import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey961e3042011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050022import static android.net.ConnectivityManager.NETID_UNSET;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090023import static android.net.ConnectivityManager.TYPE_ETHERNET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070024import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070025import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070026import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070027import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040028import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090029import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090030import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
32import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060033import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jean804b8fb2018-01-30 22:41:41 +090034import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
Chalard Jeandda156a2018-01-10 21:19:32 +090035import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090036import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060037import static android.net.NetworkCapabilities.TRANSPORT_VPN;
38
Hugo Benichia0385682017-03-22 17:07:57 +090039import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060040
Wenchao Tongf5ea3402015-03-04 13:26:38 -080041import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080042import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090043import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070044import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070045import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.ContentResolver;
47import android.content.Context;
48import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070049import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070050import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070051import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090053import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070055import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070056import android.net.INetworkPolicyListener;
57import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070058import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080059import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070060import android.net.LinkProperties.CompareResult;
Hugo Benichib577d652017-06-27 15:13:20 +090061import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070062import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070063import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070064import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070065import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070067import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070068import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090069import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070070import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070071import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070072import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070073import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070074import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070075import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040076import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070077import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040078import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040079import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060080import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +090081import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090082import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090083import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080085import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070086import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040087import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070089import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070090import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070091import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.os.Looper;
93import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070094import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070095import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +090096import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070097import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070098import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070099import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800100import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900101import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900102import android.os.ServiceSpecificException;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900103import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700104import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400105import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700107import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700108import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700109import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700110import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900111import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700112import android.util.LocalLog;
113import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600114import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800115import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700116import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500117import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700118import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700119import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120
Wink Savilleab9321d2013-06-29 21:10:57 -0700121import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400122import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400123import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700124import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700125import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700126import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700127import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800128import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700129import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700130import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600131import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700132import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900133import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900134import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700135import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700136import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400137import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900138import com.android.server.connectivity.DnsManager;
Erik Klinea24d4592018-01-11 21:07:29 +0900139import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
Hugo Benichi64901e52017-10-19 14:42:40 +0900140import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900141import com.android.server.connectivity.KeepaliveTracker;
Charles Hea0a87e82017-05-15 17:07:18 +0100142import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700143import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700144import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600145import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400146import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900147import com.android.server.connectivity.NetworkNotificationManager;
148import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400149import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700150import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800151import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700152import com.android.server.connectivity.Vpn;
Hugo Benichib577d652017-06-27 15:13:20 +0900153import com.android.server.connectivity.tethering.TetheringDependencies;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700154import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700155import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900156import com.android.server.net.NetworkPolicyManagerInternal;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600157
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700158import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700159
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700160import org.xmlpull.v1.XmlPullParser;
161import org.xmlpull.v1.XmlPullParserException;
162
163import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700165import java.io.FileNotFoundException;
166import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700167import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700169import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700170import java.net.InetAddress;
171import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700172import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700173import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700174import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700175import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700176import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700177import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700178import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700179import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700180import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900181import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600182import java.util.SortedSet;
183import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
185/**
186 * @hide
187 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800188public class ConnectivityService extends IConnectivityManager.Stub
189 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900190 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191
Erik Kline7747fd42017-05-12 16:52:48 +0900192 public static final String DIAG_ARG = "--diag";
193 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900194 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900195
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900196 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700197 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198
Jake Hamby786e71a2014-02-06 14:43:50 -0800199 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900200 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700201
Jeff Sharkey899223b2012-08-04 15:24:58 -0700202 // TODO: create better separation between radio types and network types
203
Robert Greenwalt42acef32009-08-12 16:08:25 -0700204 // how long to wait before switching back to a radio's default network
205 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
206 // system property that can override the above value
207 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
208 "android.telephony.apn-restore";
209
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900210 // How long to wait before putting up a "This network doesn't have an Internet connection,
211 // connect anyway?" dialog after the user selects a network that doesn't validate.
212 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
213
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900214 // Default to 30s linger time-out. Modifiable only for testing.
215 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
216 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
217 @VisibleForTesting
218 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
219
Jeremy Joslin79294842014-12-03 17:15:28 -0800220 // How long to delay to removal of a pending intent based request.
221 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
222 private final int mReleasePendingIntentDelayMs;
223
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900224 private MockableSystemProperties mSystemProperties;
225
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800226 private Tethering mTethering;
227
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700228 private final PermissionMonitor mPermissionMonitor;
229
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700230 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700231
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700232 @GuardedBy("mVpns")
233 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700234
Hugo Benichi69744342017-11-27 10:57:16 +0900235 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
236 // a direct call to LockdownVpnTracker.isEnabled().
237 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700238 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900239 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700240 private LockdownVpnTracker mLockdownTracker;
241
Erik Klineda4bfa82015-04-30 12:58:40 +0900242 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700244 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700245 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700248 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700250 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800251 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700252 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900253 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700254
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700255 private String mCurrentTcpBufferSizes;
256
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700257 private static final int ENABLED = 1;
258 private static final int DISABLED = 0;
259
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900260 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900261 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
262 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900263
Paul Jensenb10e37f2014-11-25 12:33:08 -0500264 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400265 // Tear down networks that have no chance (e.g. even if validated) of becoming
266 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500267 // all networks have been rematched against all NetworkRequests.
268 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400269 // Don't reap networks. This should be passed when some networks have not yet been
270 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500271 DONT_REAP
272 };
273
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900274 private enum UnneededFor {
275 LINGER, // Determine whether this network is unneeded and should be lingered.
276 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
277 }
278
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700279 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700280 * used internally to change our mobile data enabled flag
281 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700282 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700283
284 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700285 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700286 * from one net to another. Clear happens when we get a new
287 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
288 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700289 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700290 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700291
Robert Greenwalt434203a2010-10-11 16:00:27 -0700292 /**
293 * used internally to reload global proxy settings
294 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700295 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700296
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700297 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400298 * PAC manager has received new port.
299 */
300 private static final int EVENT_PROXY_HAS_CHANGED = 16;
301
Robert Greenwalte049c232014-04-11 15:53:27 -0700302 /**
303 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700304 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700305 */
306 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
307
Robert Greenwalt7b816022014-04-18 15:25:25 -0700308 /**
309 * used internally when registering NetworkAgents
310 * obj = Messenger
311 */
312 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
313
Robert Greenwalt9258c642014-03-26 16:47:06 -0700314 /**
315 * used to add a network request
316 * includes a NetworkRequestInfo
317 */
318 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
319
320 /**
321 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900322 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700323 * cancel it.
324 * includes a NetworkRequestInfo
325 */
326 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
327
328 /**
329 * used to add a network listener - no request
330 * includes a NetworkRequestInfo
331 */
332 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
333
334 /**
335 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400336 * arg1 = UID of caller
337 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700338 */
339 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
340
Robert Greenwalta67be032014-05-16 15:49:14 -0700341 /**
342 * used internally when registering NetworkFactories
343 * obj = Messenger
344 */
345 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
346
Robert Greenwalt27711812014-06-25 16:45:57 -0700347 /**
348 * used internally to expire a wakelock when transitioning
349 * from one net to another. Expire happens when we fail to find
350 * a new network (typically after 1 minute) -
351 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
352 * a replacement network.
353 */
354 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
355
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700356 /**
357 * Used internally to indicate the system is ready.
358 */
359 private static final int EVENT_SYSTEM_READY = 25;
360
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800361 /**
362 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400363 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800364 */
365 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
366
367 /**
368 * used to remove a pending intent and its associated network request.
369 * arg1 = UID of caller
370 * obj = PendingIntent
371 */
372 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
373
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900374 /**
375 * used to specify whether a network should be used even if unvalidated.
376 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
377 * arg2 = whether to remember this choice in the future (1 or 0)
378 * obj = network
379 */
380 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
381
382 /**
383 * used to ask the user to confirm a connection to an unvalidated network.
384 * obj = network
385 */
386 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700387
Erik Klineda4bfa82015-04-30 12:58:40 +0900388 /**
389 * used internally to (re)configure mobile data always-on settings.
390 */
391 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
392
Paul Jensen694f2b82015-06-17 14:15:39 -0400393 /**
394 * used to add a network listener with a pending intent
395 * obj = NetworkRequestInfo
396 */
397 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
398
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900399 /**
400 * used to specify whether a network should not be penalized when it becomes unvalidated.
401 */
402 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
403
404 /**
405 * used to trigger revalidation of a network.
406 */
407 private static final int EVENT_REVALIDATE_NETWORK = 36;
408
Erik Klinea24d4592018-01-11 21:07:29 +0900409 // Handle changes in Private DNS settings.
410 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
411
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900412 private static String eventName(int what) {
413 return sMagicDecoderRing.get(what, Integer.toString(what));
414 }
415
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900416 /** Handler thread used for both of the handlers below. */
417 @VisibleForTesting
418 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700419 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700420 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700421 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700422 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900423 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700424
Mike Lockwood0f79b542009-08-14 14:18:49 -0400425 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800426 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400427
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700428 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700429 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800430 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700431
Robert Greenwalt434203a2010-10-11 16:00:27 -0700432 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400433 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700434 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700435 private boolean mDefaultProxyDisabled = false;
436
Robert Greenwalt434203a2010-10-11 16:00:27 -0700437 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400438 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700439
Jason Monk602b2322013-07-03 17:04:33 -0400440 private PacManager mPacManager = null;
441
Erik Klineda4bfa82015-04-30 12:58:40 +0900442 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700443
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400444 private UserManager mUserManager;
445
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700446 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700447 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700448
Robert Greenwalt50393202011-06-21 17:26:14 -0700449 // the set of network types that can only be enabled by system/sig apps
450 List mProtectedNetworks;
451
John Spurlockbf991a82013-06-24 14:20:23 -0400452 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700453
Wink Savilleab9321d2013-06-29 21:10:57 -0700454 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400455
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900456 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900457 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900458 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900459
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700460 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800461 private static final int MIN_NET_ID = 100; // some reserved marks
462 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700463 private int mNextNetId = MIN_NET_ID;
464
Robert Greenwalt34524f02014-05-18 16:22:10 -0700465 // sequence number of NetworkRequests
466 private int mNextNetworkRequestId = 1;
467
Erik Kline7523eb32015-07-09 18:24:03 +0900468 // NetworkRequest activity String log entries.
469 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
470 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
471
Hugo Benichic2ae2872016-07-11 11:05:12 +0900472 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900473 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900474 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
475
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900476 private static final int MAX_WAKELOCK_LOGS = 20;
477 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichic3318aa2017-09-05 13:25:07 +0900478 private int mTotalWakelockAcquisitions = 0;
479 private int mTotalWakelockReleases = 0;
480 private long mTotalWakelockDurationMs = 0;
481 private long mMaxWakelockDurationMs = 0;
482 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900483
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700484 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
485 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400486 private static class ValidationLog {
487 final Network mNetwork;
488 final String mNetworkExtraInfo;
489 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700490
Paul Jensen0808eb82016-06-03 13:51:21 -0400491 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
492 mNetwork = network;
493 mNetworkExtraInfo = networkExtraInfo;
494 mLog = log;
495 }
496 }
497 private final ArrayDeque<ValidationLog> mValidationLogs =
498 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
499
500 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900501 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700502 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
503 mValidationLogs.removeLast();
504 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400505 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700506 }
507 }
508
Hugo Benichif9fdf872016-07-28 17:53:06 +0900509 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900510
Erik Kline065ab6e2016-10-02 18:02:14 +0900511 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900512 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900513
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700514 /**
515 * Implements support for the legacy "one network per network type" model.
516 *
517 * We used to have a static array of NetworkStateTrackers, one for each
518 * network type, but that doesn't work any more now that we can have,
519 * for example, more that one wifi network. This class stores all the
520 * NetworkAgentInfo objects that support a given type, but the legacy
521 * API will only see the first one.
522 *
523 * It serves two main purposes:
524 *
525 * 1. Provide information about "the network for a given type" (since this
526 * API only supports one).
527 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
528 * the first network for a given type changes, or if the default network
529 * changes.
530 */
531 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900532
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900533 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900534 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900535
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700536 /**
537 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
538 * Each list holds references to all NetworkAgentInfos that are used to
539 * satisfy requests for that network type.
540 *
541 * This array is built out at startup such that an unsupported network
542 * doesn't get an ArrayList instance, making this a tristate:
543 * unsupported, supported but not active and active.
544 *
545 * The actual lists are populated when we scan the network types that
546 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900547 *
548 * Threading model:
549 * - addSupportedType() is only called in the constructor
550 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
551 * They are therefore not thread-safe with respect to each other.
552 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
553 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
554 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700555 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900556 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700557
558 public LegacyTypeTracker() {
559 mTypeLists = (ArrayList<NetworkAgentInfo>[])
560 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
561 }
562
563 public void addSupportedType(int type) {
564 if (mTypeLists[type] != null) {
565 throw new IllegalStateException(
566 "legacy list for type " + type + "already initialized");
567 }
568 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
569 }
570
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700571 public boolean isTypeSupported(int type) {
572 return isNetworkTypeValid(type) && mTypeLists[type] != null;
573 }
574
575 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900576 synchronized (mTypeLists) {
577 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
578 return mTypeLists[type].get(0);
579 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700580 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900581 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700582 }
583
Robert Greenwalt8d482522015-06-24 13:23:42 -0700584 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900585 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900586 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700587 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900588 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900589 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900590 }
591 }
592
593 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700594 public void add(int type, NetworkAgentInfo nai) {
595 if (!isTypeSupported(type)) {
596 return; // Invalid network type.
597 }
598 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
599
600 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
601 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700602 return;
603 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900604 synchronized (mTypeLists) {
605 list.add(nai);
606 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900607
608 // 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 +0900609 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900610 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700611 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
612 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700613 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700614 }
615
Lorenzo Colittia793a672014-07-31 23:20:17 +0900616 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900617 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900618 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
619 if (list == null || list.isEmpty()) {
620 return;
621 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900622 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900623
Hugo Benichi78caa2582016-06-21 09:48:07 +0900624 synchronized (mTypeLists) {
625 if (!list.remove(nai)) {
626 return;
627 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900628 }
629
Robert Greenwalt8d482522015-06-24 13:23:42 -0700630 final DetailedState state = DetailedState.DISCONNECTED;
631
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900632 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700633 maybeLogBroadcast(nai, state, type, wasDefault);
634 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900635 }
636
637 if (!list.isEmpty() && wasFirstNetwork) {
638 if (DBG) log("Other network available for type " + type +
639 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900640 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700641 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
642 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900643 }
644 }
645
646 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900647 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
648 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700649 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900650 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700651 }
652 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700653
Robert Greenwalt8d482522015-06-24 13:23:42 -0700654 // send out another legacy broadcast - currently only used for suspend/unsuspend
655 // toggle
656 public void update(NetworkAgentInfo nai) {
657 final boolean isDefault = isDefaultNetwork(nai);
658 final DetailedState state = nai.networkInfo.getDetailedState();
659 for (int type = 0; type < mTypeLists.length; type++) {
660 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700661 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900662 final boolean isFirst = contains && (nai == list.get(0));
663 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700664 maybeLogBroadcast(nai, state, type, isDefault);
665 sendLegacyNetworkBroadcast(nai, state, type);
666 }
667 }
668 }
669
Lorenzo Colittia793a672014-07-31 23:20:17 +0900670 private String naiToString(NetworkAgentInfo nai) {
671 String name = (nai != null) ? nai.name() : "null";
672 String state = (nai.networkInfo != null) ?
673 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
674 "???/???";
675 return name + " " + state;
676 }
677
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700678 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900679 pw.println("mLegacyTypeTracker:");
680 pw.increaseIndent();
681 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700682 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900683 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700684 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900685 pw.println();
686 pw.println("Current state:");
687 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900688 synchronized (mTypeLists) {
689 for (int type = 0; type < mTypeLists.length; type++) {
690 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
691 for (NetworkAgentInfo nai : mTypeLists[type]) {
692 pw.println(type + " " + naiToString(nai));
693 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900694 }
695 }
696 pw.decreaseIndent();
697 pw.decreaseIndent();
698 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700699 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700700 }
701 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
702
Jeff Sharkey899223b2012-08-04 15:24:58 -0700703 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700704 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900705 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
706 }
707
708 @VisibleForTesting
709 protected ConnectivityService(Context context, INetworkManagementService netManager,
710 INetworkStatsService statsService, INetworkPolicyManager policyManager,
711 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800712 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800713
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900714 mSystemProperties = getSystemProperties();
715
Hugo Benichif9fdf872016-07-28 17:53:06 +0900716 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900717 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900718 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900719 mNetworkRequests.put(mDefaultRequest, defaultNRI);
720 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900721
Chalard Jeandda156a2018-01-10 21:19:32 +0900722 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900723 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700724
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900725 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900726 mHandlerThread.start();
727 mHandler = new InternalHandler(mHandlerThread.getLooper());
728 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700729
Jeremy Joslin79294842014-12-03 17:15:28 -0800730 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
731 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
732
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900733 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900734
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700735 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700736 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800737 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700738 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900739 mPolicyManagerInternal = checkNotNull(
740 LocalServices.getService(NetworkPolicyManagerInternal.class),
741 "missing NetworkPolicyManagerInternal");
742
Jeff Sharkey82f85212012-08-24 11:17:25 -0700743 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700744 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700745
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700746 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900747 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700748 } catch (RemoteException e) {
749 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700750 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700751 }
752
753 final PowerManager powerManager = (PowerManager) context.getSystemService(
754 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700755 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
756 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
757 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800758 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700759
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700760 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700761
Wink Saville51f456f2013-04-23 14:26:51 -0700762 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900763 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700764 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700765 String[] naStrings = context.getResources().getStringArray(
766 com.android.internal.R.array.networkAttributes);
767 for (String naString : naStrings) {
768 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700769 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700770 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700771 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800772 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700773 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700774 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700775 }
Wink Saville51f456f2013-04-23 14:26:51 -0700776 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
777 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
778 n.type);
779 continue;
780 }
Wink Saville975c8482011-04-07 14:23:45 -0700781 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800782 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700783 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700784 continue;
785 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700786 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700787
Wink Saville975c8482011-04-07 14:23:45 -0700788 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700789 mNetworksDefined++;
790 } catch(Exception e) {
791 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700792 }
793 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700794
795 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
796 if (mNetConfigs[TYPE_VPN] == null) {
797 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
798 // don't need to add TYPE_VPN to mNetConfigs.
799 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
800 mNetworksDefined++; // used only in the log() statement below.
801 }
802
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900803 // Do the same for Ethernet, since it's often not specified in the configs, although many
804 // devices can use it via USB host adapters.
805 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
806 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
807 mNetworksDefined++;
808 }
809
Wink Saville5e56bc52013-07-29 15:00:57 -0700810 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700811
Robert Greenwalt50393202011-06-21 17:26:14 -0700812 mProtectedNetworks = new ArrayList<Integer>();
813 int[] protectedNetworks = context.getResources().getIntArray(
814 com.android.internal.R.array.config_protectedNetworks);
815 for (int p : protectedNetworks) {
816 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
817 mProtectedNetworks.add(p);
818 } else {
819 if (DBG) loge("Ignoring protectedNetwork " + p);
820 }
821 }
822
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900823 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
824 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700825
Erik Kline47222fc2017-04-30 19:36:15 +0900826 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800827
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700828 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
829
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700830 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700831 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100832 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700833 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700834 intentFilter.addAction(Intent.ACTION_USER_ADDED);
835 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000836 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700837 mContext.registerReceiverAsUser(
838 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000839 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
840 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900841
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700842 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700843 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700844 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700845 } catch (RemoteException e) {
846 loge("Error registering observer :" + e);
847 }
848
Erik Klineda4bfa82015-04-30 12:58:40 +0900849 mSettingsObserver = new SettingsObserver(mContext, mHandler);
850 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800851
John Spurlockbf991a82013-06-24 14:20:23 -0400852 mDataConnectionStats = new DataConnectionStats(mContext);
853 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400854
Jason Monkdecd2952013-10-10 14:02:51 -0400855 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700856
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400857 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900858
859 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900860 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
861 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900862
863 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
864 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
865 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
866 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
867 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
868 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
869 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900870
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900871 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900872 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900873 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900874
875 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900876 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700878
Erik Kline47222fc2017-04-30 19:36:15 +0900879 private Tethering makeTethering() {
880 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +0900881 final TetheringDependencies deps = new TetheringDependencies() {
882 @Override
883 public boolean isTetheringSupported() {
884 return ConnectivityService.this.isTetheringSupported();
885 }
886 };
Erik Kline47222fc2017-04-30 19:36:15 +0900887 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
888 IoThread.get().getLooper(), new MockableSystemProperties(),
889 deps);
890 }
891
Chalard Jeandda156a2018-01-10 21:19:32 +0900892 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900893 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900894 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900895 netCap.addCapability(NET_CAPABILITY_INTERNET);
896 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900897 if (transportType > -1) {
898 netCap.addTransportType(transportType);
899 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900900 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900901 }
902
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900903 // Used only for testing.
904 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -0700905 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900906 // changing ContentResolver to make registerContentObserver non-final).
907 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
908 // by subclassing SettingsObserver.
909 @VisibleForTesting
910 void updateMobileDataAlwaysOn() {
911 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
912 }
913
Erik Kline736353a2018-03-21 07:18:33 -0700914 // See FakeSettingsProvider comment above.
915 @VisibleForTesting
916 void updatePrivateDnsSettings() {
917 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
918 }
919
Erik Klineda4bfa82015-04-30 12:58:40 +0900920 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900921 final boolean enable = toBool(Settings.Global.getInt(
922 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900923 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
924 if (enable == isEnabled) {
925 return; // Nothing to do.
926 }
927
928 if (enable) {
929 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900930 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900931 } else {
932 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
933 }
934 }
935
936 private void registerSettingsCallbacks() {
937 // Watch for global HTTP proxy changes.
938 mSettingsObserver.observe(
939 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
940 EVENT_APPLY_GLOBAL_HTTP_PROXY);
941
942 // Watch for whether or not to keep mobile data always on.
943 mSettingsObserver.observe(
944 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
945 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
946 }
947
Erik Klinea24d4592018-01-11 21:07:29 +0900948 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -0700949 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
950 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +0900951 }
952 }
953
Robert Greenwalt34524f02014-05-18 16:22:10 -0700954 private synchronized int nextNetworkRequestId() {
955 return mNextNetworkRequestId++;
956 }
957
Paul Jensen67b0b072015-06-10 11:22:17 -0400958 @VisibleForTesting
959 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400960 synchronized (mNetworkForNetId) {
961 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
962 int netId = mNextNetId;
963 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
964 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500965 if (!mNetIdInUse.get(netId)) {
966 mNetIdInUse.put(netId, true);
967 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400968 }
969 }
970 }
971 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700972 }
973
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600974 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800975 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600976 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
977 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800978 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600979 state = nai.getNetworkState();
980 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800981 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600982 final NetworkInfo info = new NetworkInfo(networkType, 0,
983 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800984 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
985 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -0700986 final NetworkCapabilities capabilities = new NetworkCapabilities();
987 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
988 !info.isRoaming());
989 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600990 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800991 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600992 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600993 return state;
994 } else {
995 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800996 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400997 }
998
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800999 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
1000 if (network == null) {
1001 return null;
1002 }
Erik Kline736353a2018-03-21 07:18:33 -07001003 return getNetworkAgentInfoForNetId(network.netId);
1004 }
1005
1006 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001007 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001008 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001009 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001010 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001011
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001012 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001013 synchronized (mVpns) {
1014 if (!mLockdownEnabled) {
1015 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001016 Vpn vpn = mVpns.get(user);
1017 if (vpn != null && vpn.appliesToUid(uid)) {
1018 return vpn.getUnderlyingNetworks();
1019 }
1020 }
1021 }
1022 return null;
1023 }
1024
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001025 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001026 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001027
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001028 final Network[] networks = getVpnUnderlyingNetworks(uid);
1029 if (networks != null) {
1030 // getUnderlyingNetworks() returns:
1031 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1032 // empty array => the VPN explicitly said "no default network".
1033 // non-empty array => the VPN specified one or more default networks; we use the
1034 // first one.
1035 if (networks.length > 0) {
1036 nai = getNetworkAgentInfoForNetwork(networks[0]);
1037 } else {
1038 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001039 }
1040 }
1041
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001042 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001043 return nai.getNetworkState();
1044 } else {
1045 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001046 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001047 }
1048
1049 /**
1050 * Check if UID should be blocked from using the network with the given LinkProperties.
1051 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001052 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1053 boolean ignoreBlocked) {
1054 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001055 if (ignoreBlocked) {
1056 return false;
1057 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001058 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001059 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1060 if (isSystem(uid)) {
1061 return false;
1062 }
Robin Lee17e61832016-05-09 13:46:28 +01001063 synchronized (mVpns) {
1064 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1065 if (vpn != null && vpn.isBlockingUid(uid)) {
1066 return true;
1067 }
1068 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001069 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001070 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001071 }
1072
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001073 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001074 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1075 return;
1076 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001077 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001078 synchronized (mBlockedAppUids) {
1079 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001080 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001081 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001082 blocked = false;
1083 } else {
1084 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001085 }
1086 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001087 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1088 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1089 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001090 }
1091
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001092 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001093 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1094 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001095 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001096 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001097 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001098 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1099
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001100 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001101 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001102 }
Hugo Benichi69744342017-11-27 10:57:16 +09001103 synchronized (mVpns) {
1104 if (mLockdownTracker != null) {
1105 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1106 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001107 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001108 }
1109
1110 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 * Return NetworkInfo for the active (i.e., connected) network interface.
1112 * It is assumed that at most one network is active at a time. If more
1113 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001114 * @return the info for the active network, or {@code null} if none is
1115 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001117 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001119 enforceAccessPermission();
1120 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001121 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001122 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001123 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1124 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 }
1126
Paul Jensen31a94f42015-02-13 14:18:39 -05001127 @Override
1128 public Network getActiveNetwork() {
1129 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001130 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001131 }
1132
1133 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001134 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001135 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001136 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001137 }
1138
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001139 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001140 final int user = UserHandle.getUserId(uid);
1141 int vpnNetId = NETID_UNSET;
1142 synchronized (mVpns) {
1143 final Vpn vpn = mVpns.get(user);
1144 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1145 }
1146 NetworkAgentInfo nai;
1147 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001148 nai = getNetworkAgentInfoForNetId(vpnNetId);
Paul Jensen31a94f42015-02-13 14:18:39 -05001149 if (nai != null) return nai.network;
1150 }
1151 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001152 if (nai != null
1153 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1154 nai = null;
1155 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001156 return nai != null ? nai.network : null;
1157 }
1158
Lorenzo Colitti18660282016-07-04 12:55:44 +09001159 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001160 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1161 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001162 final int uid = Binder.getCallingUid();
1163 NetworkState state = getUnfilteredActiveNetworkState(uid);
1164 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001165 }
1166
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001167 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001168 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001169 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001170 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001171 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001172 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001173 }
1174
1175 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 public NetworkInfo getNetworkInfo(int networkType) {
1177 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001178 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001179 if (getVpnUnderlyingNetworks(uid) != null) {
1180 // A VPN is active, so we may need to return one of its underlying networks. This
1181 // information is not available in LegacyTypeTracker, so we have to get it from
1182 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001183 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001184 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001185 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001186 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001187 }
1188 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001189 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001190 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 }
1192
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001193 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001194 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001195 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001196 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001197 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001198 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001199 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001200 return state.networkInfo;
1201 } else {
1202 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001203 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001204 }
1205
1206 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 public NetworkInfo[] getAllNetworkInfo() {
1208 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001209 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001210 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1211 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001212 NetworkInfo info = getNetworkInfo(networkType);
1213 if (info != null) {
1214 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001217 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 }
1219
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001220 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001221 public Network getNetworkForType(int networkType) {
1222 enforceAccessPermission();
1223 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001224 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1225 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001226 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001227 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001228 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001229 }
1230
1231 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001232 public Network[] getAllNetworks() {
1233 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001234 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001235 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001236 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001237 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001238 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001239 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001240 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001241 }
1242
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001243 @Override
1244 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1245 // The basic principle is: if an app's traffic could possibly go over a
1246 // network, without the app doing anything multinetwork-specific,
1247 // (hence, by "default"), then include that network's capabilities in
1248 // the array.
1249 //
1250 // In the normal case, app traffic only goes over the system's default
1251 // network connection, so that's the only network returned.
1252 //
1253 // With a VPN in force, some app traffic may go into the VPN, and thus
1254 // over whatever underlying networks the VPN specifies, while other app
1255 // traffic may go over the system default network (e.g.: a split-tunnel
1256 // VPN, or an app disallowed by the VPN), so the set of networks
1257 // returned includes the VPN's underlying networks and the system
1258 // default.
1259 enforceAccessPermission();
1260
1261 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1262
1263 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001264 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001265 if (nc != null) {
1266 result.put(nai.network, nc);
1267 }
1268
Hugo Benichi69744342017-11-27 10:57:16 +09001269 synchronized (mVpns) {
1270 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001271 Vpn vpn = mVpns.get(userId);
1272 if (vpn != null) {
1273 Network[] networks = vpn.getUnderlyingNetworks();
1274 if (networks != null) {
1275 for (Network network : networks) {
1276 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001277 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001278 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001279 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001280 }
1281 }
1282 }
1283 }
1284 }
1285 }
1286
1287 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1288 out = result.values().toArray(out);
1289 return out;
1290 }
1291
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001292 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001293 public boolean isNetworkSupported(int networkType) {
1294 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001295 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001296 }
1297
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001298 /**
1299 * Return LinkProperties for the active (i.e., connected) default
1300 * network interface. It is assumed that at most one default network
1301 * is active at a time. If more than one is active, it is indeterminate
1302 * which will be returned.
1303 * @return the ip properties for the active network, or {@code null} if
1304 * none is active
1305 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001306 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001307 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001308 enforceAccessPermission();
1309 final int uid = Binder.getCallingUid();
1310 NetworkState state = getUnfilteredActiveNetworkState(uid);
1311 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001312 }
1313
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001314 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001315 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001316 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001317 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1318 if (nai != null) {
1319 synchronized (nai) {
1320 return new LinkProperties(nai.linkProperties);
1321 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001322 }
1323 return null;
1324 }
1325
Robert Greenwalt12e67352014-05-13 21:41:06 -07001326 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001327 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001328 public LinkProperties getLinkProperties(Network network) {
1329 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001330 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1331 }
1332
1333 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1334 if (nai == null) {
1335 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001336 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001337 synchronized (nai) {
1338 return new LinkProperties(nai.linkProperties);
1339 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001340 }
1341
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001342 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001343 if (nai != null) {
1344 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001345 if (nai.networkCapabilities != null) {
Chalard Jeanb552c462018-02-21 18:43:54 +09001346 return networkCapabilitiesWithoutUidsUnlessAllowed(nai.networkCapabilities,
1347 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001348 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001349 }
1350 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001351 return null;
1352 }
1353
1354 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001355 public NetworkCapabilities getNetworkCapabilities(Network network) {
1356 enforceAccessPermission();
1357 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1358 }
1359
Chalard Jeanb552c462018-02-21 18:43:54 +09001360 private NetworkCapabilities networkCapabilitiesWithoutUidsUnlessAllowed(
1361 NetworkCapabilities nc, int callerPid, int callerUid) {
1362 if (checkSettingsPermission(callerPid, callerUid)) return new NetworkCapabilities(nc);
Chalard Jeanf19db372018-01-26 19:24:40 +09001363 return new NetworkCapabilities(nc).setUids(null);
1364 }
1365
Chalard Jeanb552c462018-02-21 18:43:54 +09001366 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1367 if (!checkSettingsPermission()) {
1368 nc.setSingleUid(Binder.getCallingUid());
1369 }
1370 }
1371
Chalard Jean1d738002018-03-20 19:13:57 +09001372 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1373 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1374 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1375 }
1376 }
1377
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001378 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001379 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001380 // Require internal since we're handing out IMSI details
1381 enforceConnectivityInternalPermission();
1382
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001383 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001384 for (Network network : getAllNetworks()) {
1385 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1386 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001387 // TODO (b/73321673) : NetworkState contains a copy of the
1388 // NetworkCapabilities, which may contain UIDs of apps to which the
1389 // network applies. Should the UIDs be cleared so as not to leak or
1390 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001391 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001392 }
1393 }
1394 return result.toArray(new NetworkState[result.size()]);
1395 }
1396
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001397 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001398 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001399 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001400 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1401 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1402 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001403 }
1404
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001405 @Override
1406 public boolean isActiveNetworkMetered() {
1407 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001408
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001409 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
1410 if (caps != null) {
1411 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1412 } else {
1413 // Always return the most conservative value
1414 return true;
1415 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001416 }
1417
Jeff Sharkey216c1812012-08-05 14:29:23 -07001418 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1419 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001420 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001421 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001422 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001423 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001424 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001425
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001426 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 * Ensure that a network route exists to deliver traffic to the specified
1428 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001429 * @param networkType the type of the network over which traffic to the
1430 * specified host is to be routed
1431 * @param hostAddress the IP address of the host to which the route is
1432 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 * @return {@code true} on success, {@code false} on failure
1434 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001435 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001436 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001438 if (mProtectedNetworks.contains(networkType)) {
1439 enforceConnectivityInternalPermission();
1440 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001441
Chad Brubakerc0234532014-02-14 13:24:29 -08001442 InetAddress addr;
1443 try {
1444 addr = InetAddress.getByAddress(hostAddress);
1445 } catch (UnknownHostException e) {
1446 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1447 return false;
1448 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001451 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 return false;
1453 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001454
1455 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1456 if (nai == null) {
1457 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1458 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1459 } else {
1460 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1461 }
1462 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001463 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001464
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001465 DetailedState netState;
1466 synchronized (nai) {
1467 netState = nai.networkInfo.getDetailedState();
1468 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001469
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001470 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001471 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001472 log("requestRouteToHostAddress on down network "
1473 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001474 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001475 }
1476 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001478
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001479 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001480 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001481 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001482 LinkProperties lp;
1483 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001484 synchronized (nai) {
1485 lp = nai.linkProperties;
1486 netId = nai.network.netId;
1487 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001488 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001489 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1490 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001491 } finally {
1492 Binder.restoreCallingIdentity(token);
1493 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001494 }
1495
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001496 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001497 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001498 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001499 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001500 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001501 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001502 if (bestRoute.getGateway().equals(addr)) {
1503 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001504 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001505 } else {
1506 // if we will connect to this through another route, add a direct route
1507 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001508 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001509 }
1510 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001511 if (DBG) log("Adding legacy route " + bestRoute +
1512 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001513 try {
1514 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1515 } catch (Exception e) {
1516 // never crash - catch them all
1517 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001518 return false;
1519 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001520 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 }
1522
Jeff Sharkey75d31892018-01-18 22:01:59 +09001523 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001524 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001525 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001526 // TODO: notify UID when it has requested targeted updates
1527 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001528 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001529 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001530 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001531 if (restrictBackground) {
1532 log("onRestrictBackgroundChanged(true): disabling tethering");
1533 mTethering.untetherAll();
1534 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001535 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001536 };
1537
Robin Lee3b3dd942015-05-12 18:14:58 +01001538 /**
1539 * Require that the caller is either in the same user or has appropriate permission to interact
1540 * across users.
1541 *
1542 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1543 */
1544 private void enforceCrossUserPermission(int userId) {
1545 if (userId == UserHandle.getCallingUserId()) {
1546 // Not a cross-user call.
1547 return;
1548 }
1549 mContext.enforceCallingOrSelfPermission(
1550 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1551 "ConnectivityService");
1552 }
1553
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001554 private void enforceInternetPermission() {
1555 mContext.enforceCallingOrSelfPermission(
1556 android.Manifest.permission.INTERNET,
1557 "ConnectivityService");
1558 }
1559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001561 mContext.enforceCallingOrSelfPermission(
1562 android.Manifest.permission.ACCESS_NETWORK_STATE,
1563 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 }
1565
1566 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001567 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 }
1569
Charles Hea0a87e82017-05-15 17:07:18 +01001570 private void enforceSettingsPermission() {
1571 mContext.enforceCallingOrSelfPermission(
1572 android.Manifest.permission.NETWORK_SETTINGS,
1573 "ConnectivityService");
1574 }
1575
Chalard Jeanb552c462018-02-21 18:43:54 +09001576 private boolean checkSettingsPermission() {
1577 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1578 android.Manifest.permission.NETWORK_SETTINGS);
1579 }
1580
1581 private boolean checkSettingsPermission(int pid, int uid) {
1582 return PERMISSION_GRANTED == mContext.checkPermission(
1583 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1584 }
1585
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001586 private void enforceTetherAccessPermission() {
1587 mContext.enforceCallingOrSelfPermission(
1588 android.Manifest.permission.ACCESS_NETWORK_STATE,
1589 "ConnectivityService");
1590 }
1591
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001592 private void enforceConnectivityInternalPermission() {
1593 mContext.enforceCallingOrSelfPermission(
1594 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1595 "ConnectivityService");
1596 }
1597
Hugo Benichi514da602016-07-19 15:59:27 +09001598 private void enforceConnectivityRestrictedNetworksPermission() {
1599 try {
1600 mContext.enforceCallingOrSelfPermission(
1601 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1602 "ConnectivityService");
1603 return;
1604 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1605 enforceConnectivityInternalPermission();
1606 }
1607
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001608 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001609 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001610 }
1611
Lorenzo Colitti18660282016-07-04 12:55:44 +09001612 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001613 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001614 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001615 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001616 }
1617
1618 private void sendInetConditionBroadcast(NetworkInfo info) {
1619 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1620 }
1621
Wink Saville628b0852011-08-04 15:01:58 -07001622 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001623 synchronized (mVpns) {
1624 if (mLockdownTracker != null) {
1625 info = new NetworkInfo(info);
1626 mLockdownTracker.augmentNetworkInfo(info);
1627 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001628 }
1629
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001630 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001631 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001632 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 if (info.isFailover()) {
1634 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1635 info.setFailover(false);
1636 }
1637 if (info.getReason() != null) {
1638 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1639 }
1640 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001641 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1642 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001644 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001645 return intent;
1646 }
1647
1648 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1649 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1650 }
1651
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001652 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001653 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1654 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1655 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001656 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001657 final long ident = Binder.clearCallingIdentity();
1658 try {
1659 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1660 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1661 } finally {
1662 Binder.restoreCallingIdentity(ident);
1663 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001664 }
1665
Mike Lockwood0f79b542009-08-14 14:18:49 -04001666 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001667 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001668 if (!mSystemReady) {
1669 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001670 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001671 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001672 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001673 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001674 }
1675
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001676 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001677 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001678 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001679 final NetworkInfo ni = intent.getParcelableExtra(
1680 ConnectivityManager.EXTRA_NETWORK_INFO);
1681 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1682 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1683 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001684 } else {
1685 BroadcastOptions opts = BroadcastOptions.makeBasic();
1686 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1687 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001688 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001689 final IBatteryStats bs = BatteryStatsService.getService();
1690 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001691 bs.noteConnectivityChanged(intent.getIntExtra(
1692 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1693 ni != null ? ni.getState().toString() : "?");
1694 } catch (RemoteException e) {
1695 }
1696 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001697 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001698 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001699 } finally {
1700 Binder.restoreCallingIdentity(ident);
1701 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001702 }
1703 }
1704
1705 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001706 loadGlobalProxy();
1707
Hugo Benichi20035e02017-04-26 14:53:28 +09001708 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001709 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001710 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001711 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001712 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001713 }
1714 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001715 // load the global proxy at startup
1716 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001717
Robin Lee244ce8e2016-01-05 18:03:46 +00001718 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1719 // for user to unlock device too.
1720 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001721
Erik Klineda4bfa82015-04-30 12:58:40 +09001722 // Configure whether mobile data is always on.
1723 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1724
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001725 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001726
1727 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 }
1729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001731 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001732 *
1733 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001734 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001735 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001736 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1737 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001738
1739 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001740 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001741
Robert Greenwalt7b816022014-04-18 15:25:25 -07001742 if (networkAgent.networkCapabilities.hasTransport(
1743 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001744 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1745 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001746 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001747 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001748 } else if (networkAgent.networkCapabilities.hasTransport(
1749 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001750 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1751 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001752 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001753 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001754 } else {
1755 // do not track any other networks
1756 timeout = 0;
1757 }
1758
Robert Greenwalt7b816022014-04-18 15:25:25 -07001759 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001760 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001761 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001762 } catch (Exception e) {
1763 // You shall not crash!
1764 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001765 }
1766 }
1767 }
1768
1769 /**
1770 * Remove data activity tracking when network disconnects.
1771 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001772 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1773 final String iface = networkAgent.linkProperties.getInterfaceName();
1774 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001775
Robert Greenwalt7b816022014-04-18 15:25:25 -07001776 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1777 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001778 try {
1779 // the call fails silently if no idletimer setup for this interface
1780 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001781 } catch (Exception e) {
1782 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001783 }
1784 }
1785 }
1786
1787 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001788 * Reads the network specific MTU size from reources.
1789 * and set it on it's iface.
1790 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001791 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1792 final String iface = newLp.getInterfaceName();
1793 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001794 if (oldLp == null && mtu == 0) {
1795 // Silently ignore unset MTU value.
1796 return;
1797 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001798 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1799 if (VDBG) log("identical MTU - not setting");
1800 return;
1801 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001802 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001803 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001804 return;
1805 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001806
w1997615afd812014-08-05 15:18:11 -07001807 // Cannot set MTU without interface name
1808 if (TextUtils.isEmpty(iface)) {
1809 loge("Setting MTU size with null iface.");
1810 return;
1811 }
1812
Robert Greenwalt7b816022014-04-18 15:25:25 -07001813 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001814 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001815 mNetd.setMtu(iface, mtu);
1816 } catch (Exception e) {
1817 Slog.e(TAG, "exception in setMtu()" + e);
1818 }
1819 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001820
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001821 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001822 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1823
1824 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001825 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001826 protected MockableSystemProperties getSystemProperties() {
1827 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001828 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001829
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001830 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1831 if (isDefaultNetwork(nai) == false) {
1832 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001833 }
1834
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001835 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1836 String[] values = null;
1837 if (tcpBufferSizes != null) {
1838 values = tcpBufferSizes.split(",");
1839 }
1840
1841 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001842 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001843 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1844 values = tcpBufferSizes.split(",");
1845 }
1846
1847 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1848
1849 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001850 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001851
1852 final String prefix = "/sys/kernel/ipv4/tcp_";
1853 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1854 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1855 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1856 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1857 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1858 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1859 mCurrentTcpBufferSizes = tcpBufferSizes;
1860 } catch (IOException e) {
1861 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001862 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001863
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001864 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001865 Settings.Global.TCP_DEFAULT_INIT_RWND,
1866 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001867 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1868 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001869 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001870 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001871 }
1872
Robert Greenwalt562cc542014-05-15 18:07:26 -07001873 @Override
1874 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001875 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001876 NETWORK_RESTORE_DELAY_PROP_NAME);
1877 if(restoreDefaultNetworkDelayStr != null &&
1878 restoreDefaultNetworkDelayStr.length() != 0) {
1879 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001880 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001881 } catch (NumberFormatException e) {
1882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001884 // if the system property isn't set, use the value for the apn type
1885 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1886
1887 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1888 (mNetConfigs[networkType] != null)) {
1889 ret = mNetConfigs[networkType].restoreTime;
1890 }
1891 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
1893
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001894 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001895 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001896 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001897 }
1898 return false;
1899 }
1900
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001901 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1902 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1903 final long DIAG_TIME_MS = 5000;
1904 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1905 // Start gathering diagnostic information.
1906 netDiags.add(new NetworkDiagnostics(
1907 nai.network,
1908 new LinkProperties(nai.linkProperties), // Must be a copy.
1909 DIAG_TIME_MS));
1910 }
1911
1912 for (NetworkDiagnostics netDiag : netDiags) {
1913 pw.println();
1914 netDiag.waitForMeasurements();
1915 netDiag.dump(pw);
1916 }
1917 }
1918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001920 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1921 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001922 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001923
Erik Kline7747fd42017-05-12 16:52:48 +09001924 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001925 dumpNetworkDiagnostics(pw);
1926 return;
Erik Klineee363c42017-05-29 09:11:03 +09001927 } else if (argsContain(args, TETHERING_ARG)) {
1928 mTethering.dump(fd, pw, args);
1929 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001930 }
Erik Kline379747a2015-06-05 17:47:34 +09001931
Lorenzo Colittie3805462015-06-03 11:18:24 +09001932 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001933 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001934 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001935 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001936 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001937 pw.println();
1938
Paul Jensen85cf78e2015-06-25 13:25:07 -04001939 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001940 pw.print("Active default network: ");
1941 if (defaultNai == null) {
1942 pw.println("none");
1943 } else {
1944 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001946 pw.println();
1947
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001948 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001949 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001950 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1951 pw.println(nai.toString());
1952 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001953 pw.println(String.format(
1954 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1955 nai.numForegroundNetworkRequests(),
1956 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1957 nai.numBackgroundNetworkRequests(),
1958 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001959 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001960 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1961 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001962 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001963 pw.decreaseIndent();
1964 pw.println("Lingered:");
1965 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001966 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001967 pw.decreaseIndent();
1968 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001969 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001970 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001971 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001972
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001973 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001974 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001975 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1976 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001977 }
1978 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001979 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001980
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001981 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001982
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001983 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001984 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001985
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001986 pw.println();
1987 mKeepaliveTracker.dump(pw);
1988
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001989 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001990 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001991
Erik Kline7747fd42017-05-12 16:52:48 +09001992 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001993 pw.println();
1994 synchronized (mValidationLogs) {
1995 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001996 for (ValidationLog p : mValidationLogs) {
1997 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001998 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001999 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002000 pw.decreaseIndent();
2001 }
2002 }
Erik Kline7523eb32015-07-09 18:24:03 +09002003
2004 pw.println();
2005 pw.println("mNetworkRequestInfoLogs (most recent first):");
2006 pw.increaseIndent();
2007 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2008 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002009
2010 pw.println();
2011 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2012 pw.increaseIndent();
2013 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2014 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002015
2016 pw.println();
2017 pw.println("NetTransition WakeLock activity (most recent first):");
2018 pw.increaseIndent();
Hugo Benichic3318aa2017-09-05 13:25:07 +09002019 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2020 pw.println("total releases: " + mTotalWakelockReleases);
2021 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2022 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2023 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2024 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2025 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2026 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002027 mWakelockLogs.reverseDump(fd, pw, args);
2028 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 }
2031
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002032 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002033 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002034 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002035 if (officialNai != null && officialNai.equals(nai)) return true;
2036 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002037 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002038 " - " + nai);
2039 }
2040 return false;
2041 }
2042
Robert Greenwalt42acef32009-08-12 16:08:25 -07002043 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002044 private class NetworkStateTrackerHandler extends Handler {
2045 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002046 super(looper);
2047 }
2048
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002049 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002051 default:
2052 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002053 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002054 handleAsyncChannelHalfConnect(msg);
2055 break;
2056 }
2057 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2058 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2059 if (nai != null) nai.asyncChannel.disconnect();
2060 break;
2061 }
2062 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2063 handleAsyncChannelDisconnected(msg);
2064 break;
2065 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002066 }
2067 return true;
2068 }
2069
2070 private void maybeHandleNetworkAgentMessage(Message msg) {
2071 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2072 if (nai == null) {
2073 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002074 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002075 }
2076 return;
2077 }
2078
2079 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002080 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002081 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2082 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002083 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2084 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002085 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002086 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002087 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002088 break;
2089 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002090 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002091 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002092 break;
2093 }
2094 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002095 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002096 updateNetworkInfo(nai, info);
2097 break;
2098 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002099 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002100 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002101 break;
2102 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002103 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002104 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2105 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002106 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002107 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002108 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002109 break;
2110 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002111 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002112 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2113 break;
2114 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002115 }
2116 }
2117
2118 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2119 switch (msg.what) {
2120 default:
2121 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002122 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002123 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
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
Erik Klinea24d4592018-01-11 21:07:29 +09002130 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2131
Erik Klinea24d4592018-01-11 21:07:29 +09002132 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002133 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2134 ? " with redirect to " + redirectUrl
2135 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002136 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2137 }
Erik Klinea24d4592018-01-11 21:07:29 +09002138 if (valid != nai.lastValidated) {
2139 if (wasDefault) {
2140 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2141 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002142 }
Erik Klinea24d4592018-01-11 21:07:29 +09002143 final int oldScore = nai.getCurrentScore();
2144 nai.lastValidated = valid;
2145 nai.everValidated |= valid;
2146 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2147 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2148 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2149 }
2150 updateInetCondition(nai);
2151 // Let the NetworkAgent know the state of its network
2152 Bundle redirectUrlBundle = new Bundle();
2153 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2154 nai.asyncChannel.sendMessage(
2155 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2156 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2157 0, redirectUrlBundle);
2158 if (wasValidated && !nai.lastValidated) {
2159 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002160 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002161 break;
2162 }
Paul Jensen869868be2014-05-15 10:33:05 -04002163 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002164 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002165 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002166 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002167 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002168 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002169 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002170 nai.lastCaptivePortalDetected = visible;
2171 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002172 if (nai.lastCaptivePortalDetected &&
2173 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2174 if (DBG) log("Avoiding captive portal network: " + nai.name());
2175 nai.asyncChannel.sendMessage(
2176 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2177 teardownUnneededNetwork(nai);
2178 break;
2179 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002180 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002181 }
2182 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002183 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002184 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002185 if (nai == null) {
2186 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2187 break;
2188 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002189 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002190 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002191 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002192 }
Paul Jensen869868be2014-05-15 10:33:05 -04002193 }
Paul Jensen869868be2014-05-15 10:33:05 -04002194 break;
2195 }
Erik Klinea24d4592018-01-11 21:07:29 +09002196 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002197 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002198 if (nai == null) break;
2199
Erik Kline736353a2018-03-21 07:18:33 -07002200 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002201 break;
2202 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002203 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002204 return true;
2205 }
2206
Calvin Onbe96da12016-10-11 15:10:46 -07002207 private int getCaptivePortalMode() {
2208 return Settings.Global.getInt(mContext.getContentResolver(),
2209 Settings.Global.CAPTIVE_PORTAL_MODE,
2210 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2211 }
2212
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002213 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2214 switch (msg.what) {
2215 default:
2216 return false;
2217 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2218 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2219 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2220 handleLingerComplete(nai);
2221 }
2222 break;
2223 }
2224 }
2225 return true;
2226 }
2227
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002228 @Override
2229 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002230 if (!maybeHandleAsyncChannelMessage(msg) &&
2231 !maybeHandleNetworkMonitorMessage(msg) &&
2232 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002233 maybeHandleNetworkAgentMessage(msg);
2234 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002235 }
2236 }
2237
Erik Kline736353a2018-03-21 07:18:33 -07002238 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
2239 return NetworkMonitor.isValidationRequired(
2240 mDefaultRequest.networkCapabilities, nai.networkCapabilities);
2241 }
2242
Erik Klinea24d4592018-01-11 21:07:29 +09002243 private void handlePrivateDnsSettingsChanged() {
2244 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2245
2246 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002247 handlePerNetworkPrivateDnsConfig(nai, cfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002248 }
2249 }
2250
Erik Kline736353a2018-03-21 07:18:33 -07002251 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2252 // Private DNS only ever applies to networks that might provide
2253 // Internet access and therefore also require validation.
2254 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002255
Erik Kline736353a2018-03-21 07:18:33 -07002256 // Notify the NetworkMonitor thread in case it needs to cancel or
2257 // schedule DNS resolutions. If a DNS resolution is required the
2258 // result will be sent back to us.
2259 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2260
2261 // With Private DNS bypass support, we can proceed to update the
2262 // Private DNS config immediately, even if we're in strict mode
2263 // and have not yet resolved the provider name into a set of IPs.
2264 updatePrivateDns(nai, cfg);
2265 }
2266
2267 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2268 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002269 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002270 }
2271
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002272 private void updateLingerState(NetworkAgentInfo nai, long now) {
2273 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2274 // 2. If the network was lingering and there are now requests, unlinger it.
2275 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2276 // one lingered request, start lingering.
2277 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002278 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002279 if (DBG) log("Unlingering " + nai.name());
2280 nai.unlinger();
2281 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002282 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002283 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002284 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002285 nai.linger();
2286 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2287 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2288 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002289 }
2290
Robert Greenwalt7b816022014-04-18 15:25:25 -07002291 private void handleAsyncChannelHalfConnect(Message msg) {
2292 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002293 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002294 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2295 if (VDBG) log("NetworkFactory connected");
2296 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002297 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002298 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002299 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002300 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002301 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002302 }
2303 } else {
2304 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002305 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002306 }
2307 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2308 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2309 if (VDBG) log("NetworkAgent connected");
2310 // A network agent has requested a connection. Establish the connection.
2311 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2312 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2313 } else {
2314 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002315 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002316 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002317 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002318 synchronized (mNetworkForNetId) {
2319 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002320 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002321 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002322 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002323 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002324 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002325 }
2326 }
2327 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002328
Robert Greenwalt7b816022014-04-18 15:25:25 -07002329 private void handleAsyncChannelDisconnected(Message msg) {
2330 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2331 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002332 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002333 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002334 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002335 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002336 // TODO - if we move the logic to the network agent (have them disconnect
2337 // because they lost all their requests or because their score isn't good)
2338 // then they would disconnect organically, report their new state and then
2339 // disconnect the channel.
2340 if (nai.networkInfo.isConnected()) {
2341 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2342 null, null);
2343 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002344 final boolean wasDefault = isDefaultNetwork(nai);
2345 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002346 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002347 // Log default network disconnection before required book-keeping.
2348 // Let rematchAllNetworksAndRequests() below record a new default network event
2349 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2350 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002351 long now = SystemClock.elapsedRealtime();
2352 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002353 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002354 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002355 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2356 // by other networks that are already connected. Perhaps that can be done by
2357 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2358 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002359 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002360 mKeepaliveTracker.handleStopAllKeepalives(nai,
2361 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002362 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2363 // Disable wakeup packet monitoring for each interface.
2364 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2365 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002366 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002367 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002368 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002369 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002370 // Remove the NetworkAgent, but don't mark the netId as
2371 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002372 mNetworkForNetId.remove(nai.network.netId);
2373 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002374 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002375 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2376 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002377 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002378 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002379 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002380 sendUpdatedScoreToFactories(request, 0);
2381 }
2382 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002383 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002384 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002385 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002386 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002387 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002388 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002389 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002390 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002391 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002392 if (nai.created) {
2393 // Tell netd to clean up the configuration for this network
2394 // (routing rules, DNS, etc).
2395 // This may be slow as it requires a lot of netd shelling out to ip and
2396 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2397 // after we've rematched networks with requests which should make a potential
2398 // fallback network the default or requested a new network from the
2399 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2400 // long time.
2401 try {
2402 mNetd.removeNetwork(nai.network.netId);
2403 } catch (Exception e) {
2404 loge("Exception removing network: " + e);
2405 }
Erik Klinea24d4592018-01-11 21:07:29 +09002406 mDnsManager.removeNetwork(nai.network);
Paul Jensen62d30802015-06-17 14:42:30 -04002407 }
2408 synchronized (mNetworkForNetId) {
2409 mNetIdInUse.delete(nai.network.netId);
2410 }
2411 } else {
2412 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2413 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002414 }
2415 }
2416
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002417 // If this method proves to be too slow then we can maintain a separate
2418 // pendingIntent => NetworkRequestInfo map.
2419 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2420 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2421 Intent intent = pendingIntent.getIntent();
2422 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2423 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2424 if (existingPendingIntent != null &&
2425 existingPendingIntent.getIntent().filterEquals(intent)) {
2426 return entry.getValue();
2427 }
2428 }
2429 return null;
2430 }
2431
2432 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2433 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2434
2435 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2436 if (existingRequest != null) { // remove the existing request.
2437 if (DBG) log("Replacing " + existingRequest.request + " with "
2438 + nri.request + " because their intents matched.");
2439 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2440 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002441 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002442 }
2443
Erik Klineda4bfa82015-04-30 12:58:40 +09002444 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002445 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002446 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002447 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002448 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002449 if (nri.request.networkCapabilities.hasSignalStrength() &&
2450 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2451 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002452 }
2453 }
2454 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002455 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002456 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002457 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002458 }
2459 }
2460
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002461 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2462 int callingUid) {
2463 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2464 if (nri != null) {
2465 handleReleaseNetworkRequest(nri.request, callingUid);
2466 }
2467 }
2468
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002469 // Determines whether the network is the best (or could become the best, if it validated), for
2470 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2471 // on the value of reason:
2472 //
2473 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2474 // then it should be torn down.
2475 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2476 // then it should be lingered.
2477 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2478 final int numRequests;
2479 switch (reason) {
2480 case TEARDOWN:
2481 numRequests = nai.numRequestNetworkRequests();
2482 break;
2483 case LINGER:
2484 numRequests = nai.numForegroundNetworkRequests();
2485 break;
2486 default:
2487 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2488 return true;
2489 }
2490
2491 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002492 return false;
2493 }
Paul Jensene0988542015-06-25 15:30:08 -04002494 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002495 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2496 // Background requests don't affect lingering.
2497 continue;
2498 }
2499
Paul Jensene0988542015-06-25 15:30:08 -04002500 // If this Network is already the highest scoring Network for a request, or if
2501 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002502 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002503 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002504 // Note that this catches two important cases:
2505 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2506 // is currently satisfying the request. This is desirable when
2507 // cellular ends up validating but WiFi does not.
2508 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002509 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002510 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002511 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002512 nai.getCurrentScoreAsValidated())) {
2513 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002514 }
2515 }
Paul Jensene0988542015-06-25 15:30:08 -04002516 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002517 }
2518
Erik Klineacdd6392016-07-07 16:50:58 +09002519 private NetworkRequestInfo getNriForAppRequest(
2520 NetworkRequest request, int callingUid, String requestedOperation) {
2521 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2522
Robert Greenwalt9258c642014-03-26 16:47:06 -07002523 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002524 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002525 log(String.format("UID %d attempted to %s for unowned request %s",
2526 callingUid, requestedOperation, nri));
2527 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002528 }
Erik Klineacdd6392016-07-07 16:50:58 +09002529 }
2530
2531 return nri;
2532 }
2533
Erik Kline57faba92015-11-25 12:49:38 +09002534 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002535 if (mNetworkRequests.get(nri.request) == null) {
2536 return;
Erik Kline57faba92015-11-25 12:49:38 +09002537 }
Hugo Benichicd952782017-09-20 11:20:14 +09002538 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002539 return;
2540 }
2541 if (VDBG || (DBG && nri.request.isRequest())) {
2542 log("releasing " + nri.request + " (timeout)");
2543 }
2544 handleRemoveNetworkRequest(nri);
2545 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002546 }
2547
Erik Klineacdd6392016-07-07 16:50:58 +09002548 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002549 final NetworkRequestInfo nri =
2550 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2551 if (nri == null) {
2552 return;
Erik Kline57faba92015-11-25 12:49:38 +09002553 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002554 if (VDBG || (DBG && nri.request.isRequest())) {
2555 log("releasing " + nri.request + " (release request)");
2556 }
2557 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002558 }
Erik Klineacdd6392016-07-07 16:50:58 +09002559
Hugo Benichidba33db2017-03-23 22:40:44 +09002560 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002561 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002562 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002563
Erik Klineacdd6392016-07-07 16:50:58 +09002564 synchronized (mUidToNetworkRequestCount) {
2565 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2566 if (requests < 1) {
2567 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2568 nri.mUid);
2569 } else if (requests == 1) {
2570 mUidToNetworkRequestCount.removeAt(
2571 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2572 } else {
2573 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2574 }
2575 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002576
Erik Klineacdd6392016-07-07 16:50:58 +09002577 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2578 if (nri.request.isRequest()) {
2579 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002580 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002581 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002582 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002583 nai.removeRequest(nri.request.requestId);
2584 if (VDBG) {
2585 log(" Removing from current network " + nai.name() +
2586 ", leaving " + nai.numNetworkRequests() + " requests.");
2587 }
2588 // If there are still lingered requests on this network, don't tear it down,
2589 // but resume lingering instead.
2590 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002591 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002592 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2593 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002594 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002595 wasKept = true;
2596 }
Hugo Benichicd952782017-09-20 11:20:14 +09002597 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002598 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2599 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002600 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002601 }
Erik Klineacdd6392016-07-07 16:50:58 +09002602 }
2603
2604 // TODO: remove this code once we know that the Slog.wtf is never hit.
2605 //
2606 // Find all networks that are satisfying this request and remove the request
2607 // from their request lists.
2608 // TODO - it's my understanding that for a request there is only a single
2609 // network satisfying it, so this loop is wasteful
2610 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2611 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2612 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2613 otherNai.name() + ", but mNetworkAgentInfos says " +
2614 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002615 }
2616 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002617
Erik Klineacdd6392016-07-07 16:50:58 +09002618 // Maintain the illusion. When this request arrived, we might have pretended
2619 // that a network connected to serve it, even though the network was already
2620 // connected. Now that this request has gone away, we might have to pretend
2621 // that the network disconnected. LegacyTypeTracker will generate that
2622 // phantom disconnect for this type.
2623 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2624 boolean doRemove = true;
2625 if (wasKept) {
2626 // check if any of the remaining requests for this network are for the
2627 // same legacy type - if so, don't remove the nai
2628 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2629 NetworkRequest otherRequest = nai.requestAt(i);
2630 if (otherRequest.legacyType == nri.request.legacyType &&
2631 otherRequest.isRequest()) {
2632 if (DBG) log(" still have other legacy request - leaving");
2633 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002634 }
2635 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002636 }
2637
Erik Klineacdd6392016-07-07 16:50:58 +09002638 if (doRemove) {
2639 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002640 }
2641 }
Erik Klineacdd6392016-07-07 16:50:58 +09002642
2643 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2644 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2645 nri.request);
2646 }
2647 } else {
2648 // listens don't have a singular affectedNetwork. Check all networks to see
2649 // if this listen request applies and remove it.
2650 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2651 nai.removeRequest(nri.request.requestId);
2652 if (nri.request.networkCapabilities.hasSignalStrength() &&
2653 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2654 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2655 }
2656 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002657 }
2658 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002659
Lorenzo Colitti18660282016-07-04 12:55:44 +09002660 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002661 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2662 enforceConnectivityInternalPermission();
2663 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002664 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002665 }
2666
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002667 @Override
2668 public void setAvoidUnvalidated(Network network) {
2669 enforceConnectivityInternalPermission();
2670 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2671 }
2672
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002673 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2674 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2675 " accept=" + accept + " always=" + always);
2676
2677 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2678 if (nai == null) {
2679 // Nothing to do.
2680 return;
2681 }
2682
2683 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002684 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002685 return;
2686 }
2687
2688 if (!nai.networkMisc.explicitlySelected) {
2689 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2690 }
2691
2692 if (accept != nai.networkMisc.acceptUnvalidated) {
2693 int oldScore = nai.getCurrentScore();
2694 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002695 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002696 sendUpdatedScoreToFactories(nai);
2697 }
2698
2699 if (always) {
2700 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002701 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002702 }
2703
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002704 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002705 // Tell the NetworkAgent to not automatically reconnect to the network.
2706 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2707 // Teardown the nework.
2708 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002709 }
2710
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002711 }
2712
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002713 private void handleSetAvoidUnvalidated(Network network) {
2714 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2715 if (nai == null || nai.lastValidated) {
2716 // Nothing to do. The network either disconnected or revalidated.
2717 return;
2718 }
2719 if (!nai.avoidUnvalidated) {
2720 int oldScore = nai.getCurrentScore();
2721 nai.avoidUnvalidated = true;
2722 rematchAllNetworksAndRequests(nai, oldScore);
2723 sendUpdatedScoreToFactories(nai);
2724 }
2725 }
2726
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002727 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002728 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002729 mHandler.sendMessageDelayed(
2730 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2731 PROMPT_UNVALIDATED_DELAY_MS);
2732 }
2733
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002734 @Override
2735 public void startCaptivePortalApp(Network network) {
2736 enforceConnectivityInternalPermission();
2737 mHandler.post(() -> {
2738 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2739 if (nai == null) return;
2740 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2741 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2742 });
2743 }
2744
Hugo Benichic8e9e122016-09-14 23:23:08 +00002745 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002746 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002747 }
2748
Erik Kline065ab6e2016-10-02 18:02:14 +09002749 private void rematchForAvoidBadWifiUpdate() {
2750 rematchAllNetworksAndRequests(null, 0);
2751 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2752 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2753 sendUpdatedScoreToFactories(nai);
2754 }
2755 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002756 }
2757
Erik Kline065ab6e2016-10-02 18:02:14 +09002758 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002759 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002760 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002761 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002762 if (!configRestrict) {
2763 pw.println("Bad Wi-Fi avoidance: unrestricted");
2764 return;
2765 }
2766
2767 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2768 pw.increaseIndent();
2769 pw.println("Config restrict: " + configRestrict);
2770
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002771 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002772 String description;
2773 // Can't use a switch statement because strings are legal case labels, but null is not.
2774 if ("0".equals(value)) {
2775 description = "get stuck";
2776 } else if (value == null) {
2777 description = "prompt";
2778 } else if ("1".equals(value)) {
2779 description = "avoid";
2780 } else {
2781 description = value + " (?)";
2782 }
2783 pw.println("User setting: " + description);
2784 pw.println("Network overrides:");
2785 pw.increaseIndent();
2786 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2787 if (nai.avoidUnvalidated) {
2788 pw.println(nai.name());
2789 }
2790 }
2791 pw.decreaseIndent();
2792 pw.decreaseIndent();
2793 }
2794
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002795 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2796 final String action;
2797 switch (type) {
2798 case NO_INTERNET:
2799 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2800 break;
2801 case LOST_INTERNET:
2802 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2803 break;
2804 default:
2805 Slog.wtf(TAG, "Unknown notification type " + type);
2806 return;
2807 }
2808
2809 Intent intent = new Intent(action);
2810 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2811 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2812 intent.setClassName("com.android.settings",
2813 "com.android.settings.wifi.WifiNoInternetDialog");
2814
2815 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2816 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2817 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2818 }
2819
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002820 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002821 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002822 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2823
2824 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2825 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002826 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002827 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002828 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2829 return;
2830 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002831 showValidationNotification(nai, NotificationType.NO_INTERNET);
2832 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002833
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002834 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2835 NetworkCapabilities nc = nai.networkCapabilities;
2836 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002837
Erik Kline065ab6e2016-10-02 18:02:14 +09002838 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002839 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002840 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2841 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002842 }
2843
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002844 @Override
2845 public int getMultipathPreference(Network network) {
2846 enforceAccessPermission();
2847
2848 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002849 if (nai != null && nai.networkCapabilities
2850 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002851 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2852 }
2853
2854 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2855 }
2856
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002857 private class InternalHandler extends Handler {
2858 public InternalHandler(Looper looper) {
2859 super(looper);
2860 }
2861
2862 @Override
2863 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002864 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002865 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002866 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002867 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002868 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002869 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002870 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002871 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002872 break;
2873 }
Jason Monkdecd2952013-10-10 14:02:51 -04002874 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002875 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002876 break;
2877 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002878 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002879 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2880 break;
2881 }
2882 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2883 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002884 break;
2885 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002886 case EVENT_REGISTER_NETWORK_AGENT: {
2887 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2888 break;
2889 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002890 case EVENT_REGISTER_NETWORK_REQUEST:
2891 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002892 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002893 break;
2894 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002895 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2896 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002897 handleRegisterNetworkRequestWithIntent(msg);
2898 break;
2899 }
Erik Kline57faba92015-11-25 12:49:38 +09002900 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2901 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2902 handleTimedOutNetworkRequest(nri);
2903 break;
2904 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002905 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2906 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2907 break;
2908 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002909 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002910 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002911 break;
2912 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002913 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002914 Network network = (Network) msg.obj;
2915 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002916 break;
2917 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002918 case EVENT_SET_AVOID_UNVALIDATED: {
2919 handleSetAvoidUnvalidated((Network) msg.obj);
2920 break;
2921 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002922 case EVENT_PROMPT_UNVALIDATED: {
2923 handlePromptUnvalidated((Network) msg.obj);
2924 break;
2925 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002926 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2927 handleMobileDataAlwaysOn();
2928 break;
2929 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002930 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2931 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2932 mKeepaliveTracker.handleStartKeepalive(msg);
2933 break;
2934 }
2935 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2936 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2937 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2938 int slot = msg.arg1;
2939 int reason = msg.arg2;
2940 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2941 break;
2942 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002943 case EVENT_SYSTEM_READY: {
2944 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2945 nai.networkMonitor.systemReady = true;
2946 }
2947 break;
2948 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002949 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002950 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002951 break;
2952 }
Erik Klinea24d4592018-01-11 21:07:29 +09002953 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
2954 handlePrivateDnsSettingsChanged();
2955 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002956 }
2957 }
2958 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002959
2960 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002961 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002962 public int tether(String iface, String callerPkg) {
2963 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002964 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002965 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002966 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002967 } else {
2968 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2969 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002970 }
2971
2972 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002973 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002974 public int untether(String iface, String callerPkg) {
2975 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002976
2977 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002978 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002979 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002980 } else {
2981 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2982 }
2983 }
2984
2985 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002986 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002987 public int getLastTetherError(String iface) {
2988 enforceTetherAccessPermission();
2989
2990 if (isTetheringSupported()) {
2991 return mTethering.getLastTetherError(iface);
2992 } else {
2993 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2994 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002995 }
2996
2997 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002998 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002999 public String[] getTetherableUsbRegexs() {
3000 enforceTetherAccessPermission();
3001 if (isTetheringSupported()) {
3002 return mTethering.getTetherableUsbRegexs();
3003 } else {
3004 return new String[0];
3005 }
3006 }
3007
Lorenzo Colitti18660282016-07-04 12:55:44 +09003008 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003009 public String[] getTetherableWifiRegexs() {
3010 enforceTetherAccessPermission();
3011 if (isTetheringSupported()) {
3012 return mTethering.getTetherableWifiRegexs();
3013 } else {
3014 return new String[0];
3015 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003016 }
3017
Lorenzo Colitti18660282016-07-04 12:55:44 +09003018 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003019 public String[] getTetherableBluetoothRegexs() {
3020 enforceTetherAccessPermission();
3021 if (isTetheringSupported()) {
3022 return mTethering.getTetherableBluetoothRegexs();
3023 } else {
3024 return new String[0];
3025 }
3026 }
3027
Lorenzo Colitti18660282016-07-04 12:55:44 +09003028 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003029 public int setUsbTethering(boolean enable, String callerPkg) {
3030 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003031 if (isTetheringSupported()) {
3032 return mTethering.setUsbTethering(enable);
3033 } else {
3034 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3035 }
3036 }
3037
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003038 // TODO - move iface listing, queries, etc to new module
3039 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003040 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003041 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003042 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003043 return mTethering.getTetherableIfaces();
3044 }
3045
Lorenzo Colitti18660282016-07-04 12:55:44 +09003046 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003047 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003048 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003049 return mTethering.getTetheredIfaces();
3050 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003051
Lorenzo Colitti18660282016-07-04 12:55:44 +09003052 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003053 public String[] getTetheringErroredIfaces() {
3054 enforceTetherAccessPermission();
3055 return mTethering.getErroredIfaces();
3056 }
3057
Lorenzo Colitti18660282016-07-04 12:55:44 +09003058 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003059 public String[] getTetheredDhcpRanges() {
3060 enforceConnectivityInternalPermission();
3061 return mTethering.getTetheredDhcpRanges();
3062 }
3063
Udam Sainic3b640c2017-06-07 12:06:28 -07003064 @Override
3065 public boolean isTetheringSupported(String callerPkg) {
3066 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3067 return isTetheringSupported();
3068 }
3069
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003070 // if ro.tether.denied = true we default to no tethering
3071 // gservices could set the secure setting to 1 though to enable it on a build where it
3072 // had previously been turned off.
Udam Sainic3b640c2017-06-07 12:06:28 -07003073 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003074 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3075 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3076 Settings.Global.TETHER_SUPPORTED, defaultVal));
3077 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003078 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003079
3080 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3081 boolean adminUser = false;
3082 final long token = Binder.clearCallingIdentity();
3083 try {
3084 adminUser = mUserManager.isAdminUser();
3085 } finally {
3086 Binder.restoreCallingIdentity(token);
3087 }
3088
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003089 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003090 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003091
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003092 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003093 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3094 String callerPkg) {
3095 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003096 if (!isTetheringSupported()) {
3097 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3098 return;
3099 }
3100 mTethering.startTethering(type, receiver, showProvisioningUi);
3101 }
3102
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003103 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003104 public void stopTethering(int type, String callerPkg) {
3105 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003106 mTethering.stopTethering(type);
3107 }
3108
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003109 // Called when we lose the default network and have no replacement yet.
3110 // This will automatically be cleared after X seconds or a new default network
3111 // becomes CONNECTED, whichever happens first. The timer is started by the
3112 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003113 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003114 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003115 if (mNetTransitionWakeLock.isHeld()) {
3116 return;
3117 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003118 mNetTransitionWakeLock.acquire();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003119 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3120 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003121 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003122 mWakelockLogs.log("ACQUIRE for " + forWhom);
3123 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3124 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003125 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003126
Hugo Benichi4c31b342017-03-30 23:18:10 +09003127 // Called when we gain a new default network to release the network transition wakelock in a
3128 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3129 // message is cancelled.
3130 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003131 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003132 if (!mNetTransitionWakeLock.isHeld()) {
3133 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003134 }
3135 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003136 // Cancel self timeout on wakelock hold.
3137 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3138 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3139 mHandler.sendMessageDelayed(msg, 1000);
3140 }
3141
3142 // Called when either message of ensureNetworkTransitionWakelock or
3143 // scheduleReleaseNetworkTransitionWakelock is processed.
3144 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3145 String event = eventName(eventId);
3146 synchronized (this) {
3147 if (!mNetTransitionWakeLock.isHeld()) {
3148 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3149 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3150 return;
3151 }
3152 mNetTransitionWakeLock.release();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003153 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3154 mTotalWakelockDurationMs += lockDuration;
3155 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3156 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003157 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003158 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003159 }
3160
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003161 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003162 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003163 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003164 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003165 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003166 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003167 }
3168
Lorenzo Colitti18660282016-07-04 12:55:44 +09003169 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003170 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003171 enforceAccessPermission();
3172 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003173 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003174 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003175 mHandler.sendMessage(
3176 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3177 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003178
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003179 private void handleReportNetworkConnectivity(
3180 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003181 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003182 if (network == null) {
3183 nai = getDefaultNetwork();
3184 } else {
3185 nai = getNetworkAgentInfoForNetwork(network);
3186 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003187 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3188 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3189 return;
3190 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003191 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003192 if (hasConnectivity == nai.lastValidated) {
3193 return;
3194 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003195 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003196 int netid = nai.network.netId;
3197 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003198 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003199 // Validating a network that has not yet connected could result in a call to
3200 // rematchNetworkAndRequests() which is not meant to work on such networks.
3201 if (!nai.everConnected) {
3202 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003203 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003204 LinkProperties lp = getLinkProperties(nai);
3205 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3206 return;
3207 }
Erik Kline736353a2018-03-21 07:18:33 -07003208 nai.networkMonitor.forceReevaluation(uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003209 }
3210
Paul Jensencee9b512015-05-06 07:32:40 -04003211 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003212 // this information is already available as a world read/writable jvm property
3213 // so this API change wouldn't have a benifit. It also breaks the passing
3214 // of proxy info to all the JVMs.
3215 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003216 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003217 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003218 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3219 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003220 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003221 }
3222
Lorenzo Colitti18660282016-07-04 12:55:44 +09003223 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003224 public ProxyInfo getProxyForNetwork(Network network) {
3225 if (network == null) return getDefaultProxy();
3226 final ProxyInfo globalProxy = getGlobalProxy();
3227 if (globalProxy != null) return globalProxy;
3228 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3229 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3230 // caller may not have.
3231 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3232 if (nai == null) return null;
3233 synchronized (nai) {
3234 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3235 if (proxyInfo == null) return null;
3236 return new ProxyInfo(proxyInfo);
3237 }
3238 }
3239
Paul Jensene0bef712014-12-10 15:12:18 -05003240 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3241 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3242 // proxy is null then there is no proxy in place).
3243 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3244 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3245 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3246 proxy = null;
3247 }
3248 return proxy;
3249 }
3250
3251 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3252 // better for determining if a new proxy broadcast is necessary:
3253 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3254 // avoid unnecessary broadcasts.
3255 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3256 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3257 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3258 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3259 // all set.
3260 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3261 a = canonicalizeProxyInfo(a);
3262 b = canonicalizeProxyInfo(b);
3263 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3264 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3265 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3266 }
3267
Jason Monk207900c2014-04-25 15:00:09 -04003268 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003269 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003270
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003271 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003272 if (proxyProperties == mGlobalProxy) return;
3273 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3274 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3275
3276 String host = "";
3277 int port = 0;
3278 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003279 String pacFileUrl = "";
3280 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003281 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003282 if (!proxyProperties.isValid()) {
3283 if (DBG)
3284 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3285 return;
3286 }
Jason Monk207900c2014-04-25 15:00:09 -04003287 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003288 host = mGlobalProxy.getHost();
3289 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003290 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003291 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003292 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003293 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003294 } else {
3295 mGlobalProxy = null;
3296 }
3297 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003298 final long token = Binder.clearCallingIdentity();
3299 try {
3300 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3301 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3302 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3303 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003304 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003305 } finally {
3306 Binder.restoreCallingIdentity(token);
3307 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003308
Jason Monkcf0f97a2014-10-02 15:39:38 -04003309 if (mGlobalProxy == null) {
3310 proxyProperties = mDefaultProxy;
3311 }
3312 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003313 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003314 }
3315
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003316 private void loadGlobalProxy() {
3317 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003318 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3319 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3320 String exclList = Settings.Global.getString(res,
3321 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003322 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3323 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003324 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003325 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003326 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003327 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003328 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003329 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003330 if (!proxyProperties.isValid()) {
3331 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3332 return;
3333 }
3334
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003335 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003336 mGlobalProxy = proxyProperties;
3337 }
3338 }
3339 }
3340
Jason Monk207900c2014-04-25 15:00:09 -04003341 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003342 // this information is already available as a world read/writable jvm property
3343 // so this API change wouldn't have a benifit. It also breaks the passing
3344 // of proxy info to all the JVMs.
3345 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003346 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003347 return mGlobalProxy;
3348 }
3349 }
3350
Jason Monk207900c2014-04-25 15:00:09 -04003351 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003352 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003353 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003354 proxy = null;
3355 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003356 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003357 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003358 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003359 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003360 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3361 return;
3362 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003363
3364 // This call could be coming from the PacManager, containing the port of the local
3365 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3366 // global (to get the correct local port), and send a broadcast.
3367 // TODO: Switch PacManager to have its own message to send back rather than
3368 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003369 if ((mGlobalProxy != null) && (proxy != null)
3370 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003371 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3372 mGlobalProxy = proxy;
3373 sendProxyBroadcast(mGlobalProxy);
3374 return;
3375 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003376 mDefaultProxy = proxy;
3377
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003378 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003379 if (!mDefaultProxyDisabled) {
3380 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003381 }
3382 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003383 }
3384
Paul Jensene0bef712014-12-10 15:12:18 -05003385 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3386 // This method gets called when any network changes proxy, but the broadcast only ever contains
3387 // the default proxy (even if it hasn't changed).
3388 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3389 // world where an app might be bound to a non-default network.
3390 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3391 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3392 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3393
3394 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3395 sendProxyBroadcast(getDefaultProxy());
3396 }
3397 }
3398
Robert Greenwalt434203a2010-10-11 16:00:27 -07003399 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003400 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3401 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003402 if (!TextUtils.isEmpty(proxy)) {
3403 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003404 if (data.length == 0) {
3405 return;
3406 }
3407
Robert Greenwalt434203a2010-10-11 16:00:27 -07003408 String proxyHost = data[0];
3409 int proxyPort = 8080;
3410 if (data.length > 1) {
3411 try {
3412 proxyPort = Integer.parseInt(data[1]);
3413 } catch (NumberFormatException e) {
3414 return;
3415 }
3416 }
Jason Monk207900c2014-04-25 15:00:09 -04003417 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003418 setGlobalProxy(p);
3419 }
3420 }
3421
Jason Monk207900c2014-04-25 15:00:09 -04003422 private void sendProxyBroadcast(ProxyInfo proxy) {
3423 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003424 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003425 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003426 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003427 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3428 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003429 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003430 final long ident = Binder.clearCallingIdentity();
3431 try {
3432 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3433 } finally {
3434 Binder.restoreCallingIdentity(ident);
3435 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003436 }
3437
3438 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003439 final private HashMap<Uri, Integer> mUriEventMap;
3440 final private Context mContext;
3441 final private Handler mHandler;
3442
3443 SettingsObserver(Context context, Handler handler) {
3444 super(null);
3445 mUriEventMap = new HashMap<Uri, Integer>();
3446 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003447 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003448 }
3449
Erik Klineda4bfa82015-04-30 12:58:40 +09003450 void observe(Uri uri, int what) {
3451 mUriEventMap.put(uri, what);
3452 final ContentResolver resolver = mContext.getContentResolver();
3453 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003454 }
3455
3456 @Override
3457 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003458 Slog.wtf(TAG, "Should never be reached.");
3459 }
3460
3461 @Override
3462 public void onChange(boolean selfChange, Uri uri) {
3463 final Integer what = mUriEventMap.get(uri);
3464 if (what != null) {
3465 mHandler.obtainMessage(what.intValue()).sendToTarget();
3466 } else {
3467 loge("No matching event to send for URI=" + uri);
3468 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003469 }
3470 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003471
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003472 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003473 Slog.d(TAG, s);
3474 }
3475
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003476 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003477 Slog.e(TAG, s);
3478 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003479
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003480 private static void loge(String s, Throwable t) {
3481 Slog.e(TAG, s, t);
3482 }
3483
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003484 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003485 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003486 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3487 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3488 *
3489 * @param oldPackage Package name of the application which currently controls VPN, which will
3490 * be replaced. If there is no such application, this should should either be
3491 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3492 * @param newPackage Package name of the application which should gain control of VPN, or
3493 * {@code null} to disable.
3494 * @param userId User for whom to prepare the new VPN.
3495 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003496 * @hide
3497 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003498 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003499 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3500 int userId) {
3501 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003502
Hugo Benichi20035e02017-04-26 14:53:28 +09003503 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003504 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003505 Vpn vpn = mVpns.get(userId);
3506 if (vpn != null) {
3507 return vpn.prepare(oldPackage, newPackage);
3508 } else {
3509 return false;
3510 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003511 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003512 }
3513
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003514 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003515 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3516 * This method is used by system-privileged apps.
3517 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3518 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3519 *
3520 * @param packageName The package for which authorization state should change.
3521 * @param userId User for whom {@code packageName} is installed.
3522 * @param authorized {@code true} if this app should be able to start a VPN connection without
3523 * explicit user approval, {@code false} if not.
3524 *
Jeff Davidson05542602014-08-11 14:07:27 -07003525 * @hide
3526 */
3527 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003528 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3529 enforceCrossUserPermission(userId);
3530
Hugo Benichi20035e02017-04-26 14:53:28 +09003531 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003532 Vpn vpn = mVpns.get(userId);
3533 if (vpn != null) {
3534 vpn.setPackageAuthorization(packageName, authorized);
3535 }
Jeff Davidson05542602014-08-11 14:07:27 -07003536 }
3537 }
3538
3539 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003540 * Configure a TUN interface and return its file descriptor. Parameters
3541 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003542 * and not available in ConnectivityManager. Permissions are checked in
3543 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003544 * @hide
3545 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003546 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003547 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003548 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003549 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003550 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003551 return mVpns.get(user).establish(config);
3552 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003553 }
3554
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003555 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003556 * Start legacy VPN, controlling native daemons as needed. Creates a
3557 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003558 */
3559 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003560 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003561 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003562 final LinkProperties egress = getActiveLinkProperties();
3563 if (egress == null) {
3564 throw new IllegalStateException("Missing active network connection");
3565 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003566 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003567 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003568 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3569 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003570 }
3571
3572 /**
3573 * Return the information of the ongoing legacy VPN. This method is used
3574 * by VpnSettings and not available in ConnectivityManager. Permissions
3575 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003576 */
3577 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003578 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3579 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003580
Hugo Benichi20035e02017-04-26 14:53:28 +09003581 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003582 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003583 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003584 }
3585
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003586 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003587 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3588 * and not available in ConnectivityManager.
3589 */
3590 @Override
3591 public VpnInfo[] getAllVpnInfo() {
3592 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003593 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003594 if (mLockdownEnabled) {
3595 return new VpnInfo[0];
3596 }
3597
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003598 List<VpnInfo> infoList = new ArrayList<>();
3599 for (int i = 0; i < mVpns.size(); i++) {
3600 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3601 if (info != null) {
3602 infoList.add(info);
3603 }
3604 }
3605 return infoList.toArray(new VpnInfo[infoList.size()]);
3606 }
3607 }
3608
3609 /**
3610 * @return VPN information for accounting, or null if we can't retrieve all required
3611 * information, e.g primary underlying iface.
3612 */
3613 @Nullable
3614 private VpnInfo createVpnInfo(Vpn vpn) {
3615 VpnInfo info = vpn.getVpnInfo();
3616 if (info == null) {
3617 return null;
3618 }
3619 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3620 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3621 // the underlyingNetworks list.
3622 if (underlyingNetworks == null) {
3623 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3624 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3625 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3626 }
3627 } else if (underlyingNetworks.length > 0) {
3628 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3629 if (linkProperties != null) {
3630 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3631 }
3632 }
3633 return info.primaryUnderlyingIface == null ? null : info;
3634 }
3635
3636 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003637 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3638 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003639 * Permissions are checked in Vpn class.
3640 * @hide
3641 */
3642 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003643 public VpnConfig getVpnConfig(int userId) {
3644 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003645 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003646 Vpn vpn = mVpns.get(userId);
3647 if (vpn != null) {
3648 return vpn.getVpnConfig();
3649 } else {
3650 return null;
3651 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003652 }
3653 }
3654
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003655 @Override
3656 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003657 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3658 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3659 return false;
3660 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003661
Hugo Benichi69744342017-11-27 10:57:16 +09003662 synchronized (mVpns) {
3663 // Tear down existing lockdown if profile was removed
3664 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3665 if (mLockdownEnabled) {
3666 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3667 if (profileTag == null) {
3668 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3669 return false;
3670 }
3671 String profileName = new String(profileTag);
3672 final VpnProfile profile = VpnProfile.decode(
3673 profileName, mKeyStore.get(Credentials.VPN + profileName));
3674 if (profile == null) {
3675 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3676 setLockdownTracker(null);
3677 return true;
3678 }
3679 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003680 Vpn vpn = mVpns.get(user);
3681 if (vpn == null) {
3682 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3683 return false;
3684 }
3685 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003686 } else {
3687 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003688 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003689 }
3690
3691 return true;
3692 }
3693
3694 /**
3695 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3696 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3697 */
Hugo Benichi69744342017-11-27 10:57:16 +09003698 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003699 private void setLockdownTracker(LockdownVpnTracker tracker) {
3700 // Shutdown any existing tracker
3701 final LockdownVpnTracker existing = mLockdownTracker;
3702 mLockdownTracker = null;
3703 if (existing != null) {
3704 existing.shutdown();
3705 }
3706
Robin Leec3736bc2017-03-10 16:19:54 +00003707 if (tracker != null) {
3708 mLockdownTracker = tracker;
3709 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003710 }
3711 }
3712
Hugo Benichi69744342017-11-27 10:57:16 +09003713 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003714 private void throwIfLockdownEnabled() {
3715 if (mLockdownEnabled) {
3716 throw new IllegalStateException("Unavailable in lockdown mode");
3717 }
3718 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003719
Robin Lee244ce8e2016-01-05 18:03:46 +00003720 /**
Robin Lee17e61832016-05-09 13:46:28 +01003721 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3722 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003723 *
Robin Lee17e61832016-05-09 13:46:28 +01003724 * @return {@code true} if the service was started, the service was already connected, or there
3725 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003726 */
Robin Lee17e61832016-05-09 13:46:28 +01003727 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003728 synchronized (mVpns) {
3729 Vpn vpn = mVpns.get(userId);
3730 if (vpn == null) {
3731 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3732 // exists already.
3733 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3734 return false;
3735 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003736
Robin Lee812800c2016-05-13 15:38:08 +01003737 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003738 }
3739 }
3740
3741 @Override
Charles Hea0a87e82017-05-15 17:07:18 +01003742 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3743 enforceSettingsPermission();
3744 enforceCrossUserPermission(userId);
3745
3746 synchronized (mVpns) {
3747 Vpn vpn = mVpns.get(userId);
3748 if (vpn == null) {
3749 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3750 return false;
3751 }
3752 return vpn.isAlwaysOnPackageSupported(packageName);
3753 }
3754 }
3755
3756 @Override
Robin Leedc679712016-05-03 13:23:03 +01003757 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003758 enforceConnectivityInternalPermission();
3759 enforceCrossUserPermission(userId);
3760
Robin Lee244ce8e2016-01-05 18:03:46 +00003761 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003762 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3763 if (LockdownVpnTracker.isEnabled()) {
3764 return false;
3765 }
3766
Robin Lee244ce8e2016-01-05 18:03:46 +00003767 Vpn vpn = mVpns.get(userId);
3768 if (vpn == null) {
3769 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3770 return false;
3771 }
Robin Lee17e61832016-05-09 13:46:28 +01003772 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003773 return false;
3774 }
Robin Lee17e61832016-05-09 13:46:28 +01003775 if (!startAlwaysOnVpn(userId)) {
3776 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003777 return false;
3778 }
3779 }
3780 return true;
3781 }
3782
3783 @Override
3784 public String getAlwaysOnVpnPackage(int userId) {
3785 enforceConnectivityInternalPermission();
3786 enforceCrossUserPermission(userId);
3787
3788 synchronized (mVpns) {
3789 Vpn vpn = mVpns.get(userId);
3790 if (vpn == null) {
3791 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3792 return null;
3793 }
3794 return vpn.getAlwaysOnPackage();
3795 }
3796 }
3797
Wink Savilleab9321d2013-06-29 21:10:57 -07003798 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003799 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003800 // TODO: Remove? Any reason to trigger a provisioning check?
3801 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003802 }
3803
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003804 /** Location to an updatable file listing carrier provisioning urls.
3805 * An example:
3806 *
3807 * <?xml version="1.0" encoding="utf-8"?>
3808 * <provisioningUrls>
3809 * <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 -07003810 * </provisioningUrls>
3811 */
3812 private static final String PROVISIONING_URL_PATH =
3813 "/data/misc/radio/provisioning_urls.xml";
3814 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003815
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003816 /** XML tag for root element. */
3817 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3818 /** XML tag for individual url */
3819 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003820 /** XML attribute for mcc */
3821 private static final String ATTR_MCC = "mcc";
3822 /** XML attribute for mnc */
3823 private static final String ATTR_MNC = "mnc";
3824
Paul Jensen434dde82015-06-11 09:43:30 -04003825 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003826 FileReader fileReader = null;
3827 XmlPullParser parser = null;
3828 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003829
3830 try {
3831 fileReader = new FileReader(mProvisioningUrlFile);
3832 parser = Xml.newPullParser();
3833 parser.setInput(fileReader);
3834 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3835
3836 while (true) {
3837 XmlUtils.nextElement(parser);
3838
3839 String element = parser.getName();
3840 if (element == null) break;
3841
Paul Jensen434dde82015-06-11 09:43:30 -04003842 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003843 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3844 try {
3845 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3846 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3847 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3848 parser.next();
3849 if (parser.getEventType() == XmlPullParser.TEXT) {
3850 return parser.getText();
3851 }
3852 }
3853 }
3854 } catch (NumberFormatException e) {
3855 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3856 }
3857 }
3858 }
3859 return null;
3860 } catch (FileNotFoundException e) {
3861 loge("Carrier Provisioning Urls file not found");
3862 } catch (XmlPullParserException e) {
3863 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3864 } catch (IOException e) {
3865 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3866 } finally {
3867 if (fileReader != null) {
3868 try {
3869 fileReader.close();
3870 } catch (IOException e) {}
3871 }
3872 }
3873 return null;
3874 }
3875
Wink Saville42d4f082013-07-20 20:31:59 -07003876 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003877 public String getMobileProvisioningUrl() {
3878 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003879 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003880 if (TextUtils.isEmpty(url)) {
3881 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003882 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003883 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003884 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003885 }
Wink Saville8cf35602013-07-10 23:00:07 -07003886 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003887 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003888 String phoneNumber = mTelephonyManager.getLine1Number();
3889 if (TextUtils.isEmpty(phoneNumber)) {
3890 phoneNumber = "0000000000";
3891 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003892 url = String.format(url,
3893 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3894 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003895 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003896 }
3897
Wink Savilleab9321d2013-06-29 21:10:57 -07003898 return url;
3899 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003900
Wink Saville948282b2013-08-29 08:55:16 -07003901 @Override
3902 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003903 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003904 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003905 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3906 return;
3907 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003908 final long ident = Binder.clearCallingIdentity();
3909 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003910 // Concatenate the range of types onto the range of NetIDs.
3911 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3912 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003913 } finally {
3914 Binder.restoreCallingIdentity(ident);
3915 }
Wink Saville948282b2013-08-29 08:55:16 -07003916 }
Wink Saville7788c612013-08-29 14:57:08 -07003917
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003918 @Override
3919 public void setAirplaneMode(boolean enable) {
3920 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003921 final long ident = Binder.clearCallingIdentity();
3922 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003923 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003924 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003925 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3926 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003927 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003928 } finally {
3929 Binder.restoreCallingIdentity(ident);
3930 }
3931 }
3932
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003933 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003934 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003935 Vpn userVpn = mVpns.get(userId);
3936 if (userVpn != null) {
3937 loge("Starting user already has a VPN");
3938 return;
3939 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003940 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003941 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09003942 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3943 updateLockdownVpn();
3944 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003945 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003946 }
3947
3948 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003949 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003950 Vpn userVpn = mVpns.get(userId);
3951 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003952 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003953 return;
3954 }
Robin Lee17e61832016-05-09 13:46:28 +01003955 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003956 mVpns.delete(userId);
3957 }
3958 }
3959
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003960 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003961 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003962 final int vpnsSize = mVpns.size();
3963 for (int i = 0; i < vpnsSize; i++) {
3964 Vpn vpn = mVpns.valueAt(i);
3965 vpn.onUserAdded(userId);
3966 }
3967 }
3968 }
3969
3970 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003971 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003972 final int vpnsSize = mVpns.size();
3973 for (int i = 0; i < vpnsSize; i++) {
3974 Vpn vpn = mVpns.valueAt(i);
3975 vpn.onUserRemoved(userId);
3976 }
3977 }
3978 }
3979
Robin Lee89e7a692016-02-29 14:38:17 +00003980 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09003981 synchronized (mVpns) {
3982 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3983 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3984 updateLockdownVpn();
3985 } else {
3986 startAlwaysOnVpn(userId);
3987 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003988 }
3989 }
3990
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003991 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3992 @Override
3993 public void onReceive(Context context, Intent intent) {
3994 final String action = intent.getAction();
3995 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3996 if (userId == UserHandle.USER_NULL) return;
3997
Robin Lee323f29d2016-05-04 16:38:06 +01003998 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003999 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004000 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004001 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004002 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4003 onUserAdded(userId);
4004 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4005 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004006 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4007 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004008 }
4009 }
4010 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004011
Robin Lee95204e02017-01-27 11:59:22 +00004012 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4013 @Override
4014 public void onReceive(Context context, Intent intent) {
4015 // Try creating lockdown tracker, since user present usually means
4016 // unlocked keystore.
4017 updateLockdownVpn();
4018 mContext.unregisterReceiver(this);
4019 }
4020 };
4021
Robert Greenwalta67be032014-05-16 15:49:14 -07004022 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4023 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004024 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4025 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004026
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004027 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4028 // Map from UID to number of NetworkRequests that UID has filed.
4029 @GuardedBy("mUidToNetworkRequestCount")
4030 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4031
Robert Greenwalta67be032014-05-16 15:49:14 -07004032 private static class NetworkFactoryInfo {
4033 public final String name;
4034 public final Messenger messenger;
4035 public final AsyncChannel asyncChannel;
4036
4037 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4038 this.name = name;
4039 this.messenger = messenger;
4040 this.asyncChannel = asyncChannel;
4041 }
4042 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004043
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004044 private void ensureNetworkRequestHasType(NetworkRequest request) {
4045 if (request.type == NetworkRequest.Type.NONE) {
4046 throw new IllegalArgumentException(
4047 "All NetworkRequests in ConnectivityService must have a type");
4048 }
4049 }
4050
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004051 /**
4052 * Tracks info about the requester.
4053 * Also used to notice when the calling process dies so we can self-expire
4054 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004055 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004056 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004057 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004058 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004059 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004060 final int mPid;
4061 final int mUid;
4062 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004063
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004064 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004065 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004066 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004067 mPendingIntent = pi;
4068 messenger = null;
4069 mBinder = null;
4070 mPid = getCallingPid();
4071 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004072 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004073 }
4074
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004075 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004076 super();
4077 messenger = m;
4078 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004079 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004080 mBinder = binder;
4081 mPid = getCallingPid();
4082 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004083 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004084 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004085
4086 try {
4087 mBinder.linkToDeath(this, 0);
4088 } catch (RemoteException e) {
4089 binderDied();
4090 }
4091 }
4092
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004093 private void enforceRequestCountLimit() {
4094 synchronized (mUidToNetworkRequestCount) {
4095 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4096 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004097 throw new ServiceSpecificException(
4098 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004099 }
4100 mUidToNetworkRequestCount.put(mUid, networkRequests);
4101 }
4102 }
4103
Robert Greenwalt9258c642014-03-26 16:47:06 -07004104 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004105 if (mBinder != null) {
4106 mBinder.unlinkToDeath(this, 0);
4107 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004108 }
4109
4110 public void binderDied() {
4111 log("ConnectivityService NetworkRequestInfo binderDied(" +
4112 request + ", " + mBinder + ")");
4113 releaseNetworkRequest(request);
4114 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004115
4116 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004117 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004118 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004119 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004120 }
4121
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004122 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4123 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4124 if (badCapability != null) {
4125 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004126 }
4127 }
4128
Erik Kline9d598e12015-07-13 16:37:51 +09004129 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004130 final SortedSet<Integer> thresholds = new TreeSet();
4131 synchronized (nai) {
4132 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4133 if (nri.request.networkCapabilities.hasSignalStrength() &&
4134 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4135 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4136 }
4137 }
4138 }
Erik Kline9d598e12015-07-13 16:37:51 +09004139 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004140 }
4141
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004142 private void updateSignalStrengthThresholds(
4143 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4144 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004145 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004146 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4147
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004148 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004149 String detail;
4150 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4151 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4152 } else {
4153 detail = reason;
4154 }
4155 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4156 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4157 }
4158
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004159 nai.asyncChannel.sendMessage(
4160 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004161 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004162 }
4163
Etan Cohen859748f2017-04-03 17:42:34 -07004164 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4165 if (nc == null) {
4166 return;
4167 }
4168 NetworkSpecifier ns = nc.getNetworkSpecifier();
4169 if (ns == null) {
4170 return;
4171 }
4172 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4173 ns.assertValidFromUid(Binder.getCallingUid());
4174 }
4175
Robert Greenwalt9258c642014-03-26 16:47:06 -07004176 @Override
4177 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004178 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004179 final NetworkRequest.Type type = (networkCapabilities == null)
4180 ? NetworkRequest.Type.TRACK_DEFAULT
4181 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004182 // If the requested networkCapabilities is null, take them instead from
4183 // the default network request. This allows callers to keep track of
4184 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004185 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004186 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004187 networkCapabilities.removeCapability(NET_CAPABILITY_NOT_VPN);
Erik Klinea2d29402016-03-16 15:31:39 +09004188 enforceAccessPermission();
4189 } else {
4190 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4191 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004192 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4193 // of the app when the request is filed, but we never change the request if the app
4194 // changes network state. http://b/29964605
4195 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004196 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004197 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004198 // Set the UID range for this request to the single UID of the requester, or to an empty
4199 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004200 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4201 // are no visible methods to set the UIDs, an app could use reflection to try and get
4202 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004203 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004204
Etan Cohenba07c8c2017-02-05 10:42:27 -08004205 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004206 throw new IllegalArgumentException("Bad timeout specified");
4207 }
Etan Cohen859748f2017-04-03 17:42:34 -07004208 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004209
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004210 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004211 nextNetworkRequestId(), type);
4212 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004213 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004214
4215 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004216 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004217 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004218 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004219 }
4220 return networkRequest;
4221 }
4222
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004223 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004224 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004225 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004226 } else {
4227 enforceChangePermission();
4228 }
4229 }
4230
fenglub15e72b2015-03-20 11:29:56 -07004231 @Override
fengludb571472015-04-21 17:12:05 -07004232 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004233 enforceAccessPermission();
4234 NetworkAgentInfo nai = null;
4235 if (network == null) {
4236 return false;
4237 }
4238 synchronized (mNetworkForNetId) {
4239 nai = mNetworkForNetId.get(network.netId);
4240 }
4241 if (nai != null) {
4242 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4243 return true;
4244 }
4245 return false;
4246 }
4247
Felipe Lemeee27cab2016-06-20 16:36:29 -07004248 private boolean isSystem(int uid) {
4249 return uid < Process.FIRST_APPLICATION_UID;
4250 }
fenglub15e72b2015-03-20 11:29:56 -07004251
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004252 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004253 final int uid = Binder.getCallingUid();
4254 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004255 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004256 return;
4257 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004258 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4259 // Policy already enforced.
4260 return;
4261 }
4262 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4263 // If UID is restricted, don't allow them to bring up metered APNs.
4264 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004265 }
4266 }
4267
Robert Greenwalt9258c642014-03-26 16:47:06 -07004268 @Override
4269 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4270 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004271 checkNotNull(operation, "PendingIntent cannot be null.");
4272 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4273 enforceNetworkRequestPermissions(networkCapabilities);
4274 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004275 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004276 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004277 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004278
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004279 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004280 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4281 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004282 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004283 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4284 nri));
4285 return networkRequest;
4286 }
4287
Jeremy Joslin79294842014-12-03 17:15:28 -08004288 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4289 mHandler.sendMessageDelayed(
4290 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4291 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4292 }
4293
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004294 @Override
4295 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004296 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004297 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4298 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004299 }
4300
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004301 // In order to implement the compatibility measure for pre-M apps that call
4302 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4303 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4304 // This ensures it has permission to do so.
4305 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4306 if (nc == null) {
4307 return false;
4308 }
4309 int[] transportTypes = nc.getTransportTypes();
4310 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4311 return false;
4312 }
4313 try {
4314 mContext.enforceCallingOrSelfPermission(
4315 android.Manifest.permission.ACCESS_WIFI_STATE,
4316 "ConnectivityService");
4317 } catch (SecurityException e) {
4318 return false;
4319 }
4320 return true;
4321 }
4322
Robert Greenwalt9258c642014-03-26 16:47:06 -07004323 @Override
4324 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4325 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004326 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4327 enforceAccessPermission();
4328 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004329
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004330 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004331 restrictRequestUidsForCaller(nc);
Chalard Jean1d738002018-03-20 19:13:57 +09004332 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4333 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4334 // onLost and onAvailable callbacks when networks move in and out of the background.
4335 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4336 // can't request networks.
4337 restrictBackgroundRequestForCaller(nc);
4338 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004339
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004340 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004341 NetworkRequest.Type.LISTEN);
4342 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004343 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004344
4345 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4346 return networkRequest;
4347 }
4348
4349 @Override
4350 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4351 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004352 checkNotNull(operation, "PendingIntent cannot be null.");
4353 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4354 enforceAccessPermission();
4355 }
Etan Cohen859748f2017-04-03 17:42:34 -07004356 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004357
Chalard Jeandda156a2018-01-10 21:19:32 +09004358 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004359 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004360
4361 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004362 NetworkRequest.Type.LISTEN);
4363 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004364 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004365
4366 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004367 }
4368
Erik Klineacdd6392016-07-07 16:50:58 +09004369 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004370 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004371 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004372 mHandler.sendMessage(mHandler.obtainMessage(
4373 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004374 }
4375
4376 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004377 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004378 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004379 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4380 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004381 }
4382
Robert Greenwalta67be032014-05-16 15:49:14 -07004383 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004384 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004385 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4386 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4387 }
4388
4389 @Override
4390 public void unregisterNetworkFactory(Messenger messenger) {
4391 enforceConnectivityInternalPermission();
4392 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4393 }
4394
4395 private void handleUnregisterNetworkFactory(Messenger messenger) {
4396 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4397 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004398 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004399 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004400 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004401 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004402 }
4403
Robert Greenwalt7b816022014-04-18 15:25:25 -07004404 /**
4405 * NetworkAgentInfo supporting a request by requestId.
4406 * These have already been vetted (their Capabilities satisfy the request)
4407 * and the are the highest scored network available.
4408 * the are keyed off the Requests requestId.
4409 */
Hugo Benichicd952782017-09-20 11:20:14 +09004410 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4411 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004412 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4413 new SparseArray<NetworkAgentInfo>();
4414
Paul Jensen31a94f42015-02-13 14:18:39 -05004415 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4416 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004417 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4418 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004419 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4420 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4421 // there may not be a strict 1:1 correlation between the two.
4422 @GuardedBy("mNetworkForNetId")
4423 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004424
Robert Greenwalt7b816022014-04-18 15:25:25 -07004425 // NetworkAgentInfo keyed off its connecting messenger
4426 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004427 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004428 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4429 new HashMap<Messenger, NetworkAgentInfo>();
4430
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004431 @GuardedBy("mBlockedAppUids")
4432 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4433
Paul Jensen2c311d62014-11-17 12:34:51 -05004434 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004435 private final NetworkRequest mDefaultRequest;
4436
Erik Klineda4bfa82015-04-30 12:58:40 +09004437 // Request used to optionally keep mobile data active even when higher
4438 // priority networks like Wi-Fi are active.
4439 private final NetworkRequest mDefaultMobileDataRequest;
4440
Hugo Benichicd952782017-09-20 11:20:14 +09004441 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4442 synchronized (mNetworkForRequestId) {
4443 return mNetworkForRequestId.get(requestId);
4444 }
4445 }
4446
4447 private void clearNetworkForRequest(int requestId) {
4448 synchronized (mNetworkForRequestId) {
4449 mNetworkForRequestId.remove(requestId);
4450 }
4451 }
4452
4453 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4454 synchronized (mNetworkForRequestId) {
4455 mNetworkForRequestId.put(requestId, nai);
4456 }
4457 }
4458
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004459 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004460 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004461 }
4462
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004463 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004464 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004465 }
4466
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004467 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4468 return nri.request.requestId == mDefaultRequest.requestId;
4469 }
4470
Paul Jensen31a94f42015-02-13 14:18:39 -05004471 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004472 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004473 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004474 enforceConnectivityInternalPermission();
4475
Rubin Xu1bb5c082017-09-05 18:40:49 +01004476 LinkProperties lp = new LinkProperties(linkProperties);
4477 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004478 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4479 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004480 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004481 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004482 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004483 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004484 // Make sure the network capabilities reflect what the agent info says.
4485 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004486 synchronized (this) {
4487 nai.networkMonitor.systemReady = mSystemReady;
4488 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004489 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4490 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004491 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004492 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004493 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004494 }
4495
Erik Klinee5dac902018-03-04 21:01:01 +09004496 private void handleRegisterNetworkAgent(NetworkAgentInfo nai) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004497 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09004498 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004499 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09004500 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004501 }
Erik Klinee5dac902018-03-04 21:01:01 +09004502 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
4503 NetworkInfo networkInfo = nai.networkInfo;
4504 nai.networkInfo = null;
4505 updateNetworkInfo(nai, networkInfo);
4506 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004507 }
4508
4509 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4510 LinkProperties newLp = networkAgent.linkProperties;
4511 int netId = networkAgent.network.netId;
4512
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004513 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4514 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004515 if (networkAgent.clatd != null) {
4516 networkAgent.clatd.fixupLinkProperties(oldLp);
4517 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004518
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004519 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004520 updateMtu(newLp, oldLp);
4521 // TODO - figure out what to do for clat
4522// for (LinkProperties lp : newLp.getStackedLinks()) {
4523// updateMtu(lp, null);
4524// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004525 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004526
Erik Kline94887872016-04-05 13:30:49 +09004527 updateRoutes(newLp, oldLp, netId);
4528 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004529
Hugo Benichib577d652017-06-27 15:13:20 +09004530 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004531 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004532 if (isDefaultNetwork(networkAgent)) {
4533 handleApplyDefaultProxy(newLp.getHttpProxy());
4534 } else {
4535 updateProxy(newLp, oldLp, networkAgent);
4536 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004537 // TODO - move this check to cover the whole function
4538 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004539 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004540 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4541 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004542
4543 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004544 }
4545
Joel Scherpelz668370b2017-06-08 15:35:21 +09004546 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004547 // Marks are only available on WiFi interaces. Checking for
4548 // marks on unsupported interfaces is harmless.
4549 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4550 return;
4551 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004552
Joel Scherpelz668370b2017-06-08 15:35:21 +09004553 int mark = mContext.getResources().getInteger(
4554 com.android.internal.R.integer.config_networkWakeupPacketMark);
4555 int mask = mContext.getResources().getInteger(
4556 com.android.internal.R.integer.config_networkWakeupPacketMask);
4557
4558 // Mask/mark of zero will not detect anything interesting.
4559 // Don't install rules unless both values are nonzero.
4560 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004561 return;
4562 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004563
4564 final String prefix = "iface:" + iface;
4565 try {
4566 if (add) {
4567 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4568 } else {
4569 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4570 }
4571 } catch (Exception e) {
4572 loge("Exception modifying wakeup packet monitoring: " + e);
4573 }
4574
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004575 }
4576
4577 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4578 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004579 CompareResult<String> interfaceDiff = new CompareResult<String>(
4580 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4581 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004582 for (String iface : interfaceDiff.added) {
4583 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004584 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004585 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004586 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004587 } catch (Exception e) {
4588 loge("Exception adding interface: " + e);
4589 }
4590 }
4591 for (String iface : interfaceDiff.removed) {
4592 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004593 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004594 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004595 mNetd.removeInterfaceFromNetwork(iface, netId);
4596 } catch (Exception e) {
4597 loge("Exception removing interface: " + e);
4598 }
4599 }
4600 }
4601
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004602 /**
4603 * Have netd update routes from oldLp to newLp.
4604 * @return true if routes changed between oldLp and newLp
4605 */
4606 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004607 // Compare the route diff to determine which routes should be added and removed.
4608 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4609 oldLp != null ? oldLp.getAllRoutes() : null,
4610 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004611
4612 // add routes before removing old in case it helps with continuous connectivity
4613
4614 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4615 for (RouteInfo route : routeDiff.added) {
4616 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004617 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004618 try {
4619 mNetd.addRoute(netId, route);
4620 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004621 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4622 loge("Exception in addRoute for non-gateway: " + e);
4623 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004624 }
4625 }
4626 for (RouteInfo route : routeDiff.added) {
4627 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004628 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004629 try {
4630 mNetd.addRoute(netId, route);
4631 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004632 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4633 loge("Exception in addRoute for gateway: " + e);
4634 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004635 }
4636 }
4637
4638 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004639 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004640 try {
4641 mNetd.removeRoute(netId, route);
4642 } catch (Exception e) {
4643 loge("Exception in removeRoute: " + e);
4644 }
4645 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004646 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004647 }
Erik Kline41368502015-06-17 13:19:54 +09004648
Erik Kline94887872016-04-05 13:30:49 +09004649 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4650 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4651 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004652 }
Erik Kline94887872016-04-05 13:30:49 +09004653
Erik Kline1742fe12017-12-13 19:40:49 +09004654 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4655 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4656
Erik Klinea24d4592018-01-11 21:07:29 +09004657 if (DBG) {
4658 final Collection<InetAddress> dnses = newLp.getDnsServers();
4659 log("Setting DNS servers for network " + netId + " to " + dnses);
4660 }
Erik Kline94887872016-04-05 13:30:49 +09004661 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004662 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004663 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004664 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004665 }
Erik Kline4edba012017-04-07 15:29:29 +09004666 }
4667
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004668 private String getNetworkPermission(NetworkCapabilities nc) {
4669 // TODO: make these permission strings AIDL constants instead.
4670 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4671 return NetworkManagementService.PERMISSION_SYSTEM;
4672 }
4673 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4674 return NetworkManagementService.PERMISSION_NETWORK;
4675 }
4676 return null;
4677 }
4678
Paul Jensen3d194ea2015-06-16 14:27:36 -04004679 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004680 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4681 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4682 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004683 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004684 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004685 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004686 if (nai.everConnected &&
4687 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4688 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichibae105a2017-08-16 13:19:04 +09004689 // does not cause any request (that is not a listen) currently matching that agent to
4690 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004691 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichieae7a222017-07-25 11:40:56 +09004692 if (!TextUtils.isEmpty(diff)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004693 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichieae7a222017-07-25 11:40:56 +09004694 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004695 }
4696
Paul Jensen3d194ea2015-06-16 14:27:36 -04004697 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004698 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004699 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004700 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004701 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004702 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004703 }
Paul Jensene0988542015-06-25 15:30:08 -04004704 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004705 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004706 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004707 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004708 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004709 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004710 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004711 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004712 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004713 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004714 if (nai.isSuspended()) {
4715 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4716 } else {
4717 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4718 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004719
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004720 return newNc;
4721 }
4722
4723 /**
4724 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4725 *
4726 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4727 * capabilities we manage and store in {@code nai}, such as validated status and captive
4728 * portal status)
4729 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4730 * potentially triggers rematches.
4731 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4732 * change.)
4733 *
4734 * @param oldScore score of the network before any of the changes that prompted us
4735 * to call this function.
4736 * @param nai the network having its capabilities updated.
4737 * @param nc the new network capabilities.
4738 */
4739 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4740 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4741
4742 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004743
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004744 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004745 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004746 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004747 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004748 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004749 } catch (RemoteException e) {
4750 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004751 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004752 }
4753
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004754 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004755 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004756 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004757 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004758 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004759
Chalard Jeanf213ca12018-01-16 18:43:05 +09004760 updateUids(nai, prevNc, newNc);
4761
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004762 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004763 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4764 // the change we're processing can't affect any requests, it can only affect the listens
4765 // on this network. We might have been called by rematchNetworkAndRequests when a
4766 // network changed foreground state.
4767 processListenRequests(nai, true);
4768 } else {
4769 // If the requestable capabilities have changed or the score changed, we can't have been
4770 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004771 rematchAllNetworksAndRequests(nai, oldScore);
4772 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004773 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004774
4775 // Report changes that are interesting for network statistics tracking.
4776 if (prevNc != null) {
4777 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004778 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004779 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004780 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004781 if (meteredChanged || roamingChanged) {
4782 notifyIfacesChangedForNetworkStats();
4783 }
4784 }
4785
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004786 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004787 // Tell VPNs about updated capabilities, since they may need to
4788 // bubble those changes through.
4789 synchronized (mVpns) {
4790 for (int i = 0; i < mVpns.size(); i++) {
4791 final Vpn vpn = mVpns.valueAt(i);
4792 vpn.updateCapabilities();
4793 }
4794 }
4795 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004796 }
4797
Chalard Jeanf213ca12018-01-16 18:43:05 +09004798 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4799 NetworkCapabilities newNc) {
4800 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4801 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4802 if (null == prevRanges) prevRanges = new ArraySet<>();
4803 if (null == newRanges) newRanges = new ArraySet<>();
4804 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4805
4806 prevRanges.removeAll(newRanges);
4807 newRanges.removeAll(prevRangesCopy);
4808
4809 try {
4810 if (!newRanges.isEmpty()) {
4811 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4812 newRanges.toArray(addedRangesArray);
4813 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4814 }
4815 if (!prevRanges.isEmpty()) {
4816 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4817 prevRanges.toArray(removedRangesArray);
4818 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4819 }
4820 } catch (Exception e) {
4821 // Never crash!
4822 loge("Exception in updateUids: " + e);
4823 }
4824 }
4825
Hugo Benichief502882017-09-01 01:23:32 +00004826 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Erik Kline736353a2018-03-21 07:18:33 -07004827 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00004828 // Ignore updates for disconnected networks
4829 return;
4830 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004831 // newLp is already a defensive copy.
4832 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004833 if (VDBG) {
4834 log("Update of LinkProperties for " + nai.name() +
4835 "; created=" + nai.created +
4836 "; everConnected=" + nai.everConnected);
4837 }
4838 LinkProperties oldLp = nai.linkProperties;
4839 synchronized (nai) {
4840 nai.linkProperties = newLp;
4841 }
4842 if (nai.everConnected) {
4843 updateLinkProperties(nai, oldLp);
4844 }
4845 }
4846
Paul Jensenc8b9a742014-09-30 15:37:41 -04004847 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004848 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4849 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004850 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004851 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004852 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4853 }
4854 }
4855
Robert Greenwalt7b816022014-04-18 15:25:25 -07004856 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4857 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004858 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004859 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4860 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004861 }
4862 }
4863
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004864 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4865 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004866 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004867 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004868 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4869 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004870 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004871 sendIntent(nri.mPendingIntent, intent);
4872 }
4873 // else not handled
4874 }
4875
4876 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4877 mPendingIntentWakeLock.acquire();
4878 try {
4879 if (DBG) log("Sending " + pendingIntent);
4880 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4881 } catch (PendingIntent.CanceledException e) {
4882 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4883 mPendingIntentWakeLock.release();
4884 releasePendingNetworkRequest(pendingIntent);
4885 }
4886 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4887 }
4888
4889 @Override
4890 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4891 String resultData, Bundle resultExtras) {
4892 if (DBG) log("Finished sending " + pendingIntent);
4893 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004894 // Release with a delay so the receiving client has an opportunity to put in its
4895 // own request.
4896 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004897 }
4898
Chalard Jeanf19db372018-01-26 19:24:40 +09004899 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004900 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004901 if (nri.messenger == null) {
4902 return; // Default request has no msgr
4903 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004904 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004905 // TODO: check if defensive copies of data is needed.
4906 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004907 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004908 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4909 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004910 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004911 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09004912 case ConnectivityManager.CALLBACK_AVAILABLE: {
4913 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
4914 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
4915 break;
4916 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004917 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004918 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004919 break;
4920 }
4921 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09004922 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb552c462018-02-21 18:43:54 +09004923 final NetworkCapabilities nc = networkCapabilitiesWithoutUidsUnlessAllowed(
4924 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09004925 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004926 break;
4927 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004928 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004929 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004930 break;
4931 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004932 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004933 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004934 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004935 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004936 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004937 String notification = ConnectivityManager.getCallbackName(notificationType);
4938 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004939 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004940 nri.messenger.send(msg);
4941 } catch (RemoteException e) {
4942 // may occur naturally in the race of binder death.
4943 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4944 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004945 }
4946
Hugo Benichidba33db2017-03-23 22:40:44 +09004947 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4948 bundle.putParcelable(t.getClass().getSimpleName(), t);
4949 }
4950
Paul Jensenc8b9a742014-09-30 15:37:41 -04004951 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004952 if (nai.numRequestNetworkRequests() != 0) {
4953 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4954 NetworkRequest nr = nai.requestAt(i);
4955 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004956 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004957 loge("Dead network still had at least " + nr);
4958 break;
4959 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004960 }
4961 nai.asyncChannel.disconnect();
4962 }
4963
Robert Greenwalt7b816022014-04-18 15:25:25 -07004964 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4965 if (oldNetwork == null) {
4966 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4967 return;
4968 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004969 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004970
4971 // If we get here it means that the last linger timeout for this network expired. So there
4972 // must be no other active linger timers, and we must stop lingering.
4973 oldNetwork.clearLingerState();
4974
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004975 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004976 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004977 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004978 } else {
4979 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004980 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4981 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004982 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004983 }
4984
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004985 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004986 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004987 setupDataActivityTracking(newNetwork);
4988 try {
4989 mNetd.setDefaultNetId(newNetwork.network.netId);
4990 } catch (Exception e) {
4991 loge("Exception setting default network :" + e);
4992 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09004993
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004994 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004995 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004996 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09004997 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09004998 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04004999 }
5000
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005001 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005002 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5003 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5004 NetworkRequest nr = nri.request;
5005 if (!nr.isListen()) continue;
5006 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5007 nai.removeRequest(nri.request.requestId);
5008 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5009 }
5010 }
5011
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005012 if (capabilitiesChanged) {
5013 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5014 }
5015
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005016 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5017 NetworkRequest nr = nri.request;
5018 if (!nr.isListen()) continue;
5019 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5020 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005021 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005022 }
5023 }
5024 }
5025
Paul Jensen2161a8e2014-09-11 11:00:39 -04005026 // Handles a network appearing or improving its score.
5027 //
5028 // - Evaluates all current NetworkRequests that can be
5029 // satisfied by newNetwork, and reassigns to newNetwork
5030 // any such requests for which newNetwork is the best.
5031 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005032 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005033 // needed. A network is needed if it is the best network for
5034 // one or more NetworkRequests, or if it is a VPN.
5035 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005036 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005037 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005038 //
5039 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5040 // networks that have no chance (i.e. even if validated)
5041 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005042 //
5043 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5044 // it does not remove NetworkRequests that other Networks could better satisfy.
5045 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5046 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5047 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005048 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005049 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005050 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5051 // performed to tear down unvalidated networks that have no chance (i.e. even if
5052 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005053 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005054 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005055 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005056 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005057 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005058 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005059
5060 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5061 final int score = newNetwork.getCurrentScore();
5062
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005063 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005064
Paul Jensen2161a8e2014-09-11 11:00:39 -04005065 // Find and migrate to this Network any NetworkRequests for
5066 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07005067 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04005068 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005069 NetworkCapabilities nc = newNetwork.networkCapabilities;
5070 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005071 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005072 // Process requests in the first pass and listens in the second pass. This allows us to
5073 // change a network's capabilities depending on which requests it has. This is only
5074 // correct if the change in capabilities doesn't affect whether the network satisfies
5075 // requests or not, and doesn't affect the network's score.
5076 if (nri.request.isListen()) continue;
5077
Hugo Benichicd952782017-09-20 11:20:14 +09005078 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005079 final boolean satisfies = newNetwork.satisfies(nri.request);
5080 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005081 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005082 log("Network " + newNetwork.name() + " was already satisfying" +
5083 " request " + nri.request.requestId + ". No change.");
5084 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005085 keep = true;
5086 continue;
5087 }
5088
5089 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005090 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005091 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005092 // next check if it's better than any current network we're using for
5093 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005094 if (VDBG) {
5095 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005096 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005097 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005098 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005099 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005100 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005101 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005102 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005103 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005104 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005105 affectedNetworks.add(currentNetwork);
5106 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005107 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005108 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005109 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005110 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005111 if (!newNetwork.addRequest(nri.request)) {
5112 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5113 }
5114 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005115 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005116 // Tell NetworkFactories about the new score, so they can stop
5117 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005118 // TODO - this could get expensive if we have alot of requests for this
5119 // network. Think about if there is a way to reduce this. Push
5120 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005121 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005122 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005123 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005124 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005125 if (currentNetwork != null) {
5126 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5127 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005128 }
5129 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005130 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005131 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5132 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005133 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005134 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5135 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5136 // This means this code doesn't have to handle the case where "currentNetwork" no
5137 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5138 if (DBG) {
5139 log("Network " + newNetwork.name() + " stopped satisfying" +
5140 " request " + nri.request.requestId);
5141 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005142 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005143 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005144 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005145 sendUpdatedScoreToFactories(nri.request, 0);
5146 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005147 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5148 newNetwork.name() +
5149 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005150 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005151 // TODO: Technically, sending CALLBACK_LOST here is
5152 // incorrect if there is a replacement network currently
5153 // connected that can satisfy nri, which is a request
5154 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005155 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5156 // so this code is only incorrect for a network that loses
5157 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005158 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005159 }
5160 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005161 if (isNewDefault) {
5162 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005163 makeDefault(newNetwork);
5164 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005165 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005166 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005167 // Have a new default network, release the transition wakelock in
5168 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005169 }
5170
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005171 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5172 Slog.wtf(TAG, String.format(
5173 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005174 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005175 }
5176 if (newNetwork.getCurrentScore() != score) {
5177 Slog.wtf(TAG, String.format(
5178 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005179 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005180 }
5181
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005182 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005183 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5184 // If the network went from background to foreground or vice versa, we need to update
5185 // its foreground state. It is safe to do this after rematching the requests because
5186 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5187 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005188 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005189 } else {
5190 processListenRequests(newNetwork, false);
5191 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005192
Paul Jensencf4c2c62015-07-01 14:16:32 -04005193 // do this after the default net is switched, but
5194 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005195 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005196
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005197 // Linger any networks that are no longer needed. This should be done after sending the
5198 // available callback for newNetwork.
5199 for (NetworkAgentInfo nai : affectedNetworks) {
5200 updateLingerState(nai, now);
5201 }
5202 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5203 // does not need to be done in any particular order.
5204 updateLingerState(newNetwork, now);
5205
Paul Jensencf4c2c62015-07-01 14:16:32 -04005206 if (isNewDefault) {
5207 // Maintain the illusion: since the legacy API only
5208 // understands one network at a time, we must pretend
5209 // that the current default network disconnected before
5210 // the new one connected.
5211 if (oldDefaultNetwork != null) {
5212 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5213 oldDefaultNetwork, true);
5214 }
5215 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5216 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5217 notifyLockdownVpn(newNetwork);
5218 }
5219
Robert Greenwalt7b816022014-04-18 15:25:25 -07005220 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005221 // Notify battery stats service about this network, both the normal
5222 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005223 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005224 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005225 final IBatteryStats bs = BatteryStatsService.getService();
5226 final int type = newNetwork.networkInfo.getType();
5227
5228 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5229 bs.noteNetworkInterfaceType(baseIface, type);
5230 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5231 final String stackedIface = stacked.getInterfaceName();
5232 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005233 }
5234 } catch (RemoteException ignored) {
5235 }
5236
Robert Greenwalt152ed372014-12-17 17:19:53 -08005237 // This has to happen after the notifyNetworkCallbacks as that tickles each
5238 // ConnectivityManager instance so that legacy requests correctly bind dns
5239 // requests to this network. The legacy users are listening for this bcast
5240 // and will generally do a dns request so they can ensureRouteToHost and if
5241 // they do that before the callbacks happen they'll use the default network.
5242 //
5243 // TODO: Is there still a race here? We send the broadcast
5244 // after sending the callback, but if the app can receive the
5245 // broadcast before the callback, it might still break.
5246 //
5247 // This *does* introduce a race where if the user uses the new api
5248 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5249 // they may get old info. Reverse this after the old startUsing api is removed.
5250 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005251 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5252 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005253 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005254 // legacy type tracker filters out repeat adds
5255 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5256 }
5257 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005258
5259 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5260 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5261 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5262 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5263 if (newNetwork.isVPN()) {
5264 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5265 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005266 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005267 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5268 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005269 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005270 if (nai.getLingerExpiry() > 0) {
5271 // This network has active linger timers and no requests, but is not
5272 // lingering. Linger it.
5273 //
5274 // One way (the only way?) this can happen if this network is unvalidated
5275 // and became unneeded due to another network improving its score to the
5276 // point where this network will no longer be able to satisfy any requests
5277 // even if it validates.
5278 updateLingerState(nai, now);
5279 } else {
5280 if (DBG) log("Reaping " + nai.name());
5281 teardownUnneededNetwork(nai);
5282 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005283 }
5284 }
5285 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005286 }
5287
Paul Jensen1c7ba022015-06-16 14:27:36 -04005288 /**
5289 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5290 * being disconnected.
5291 * @param changed If only one Network's score or capabilities have been modified since the last
5292 * time this function was called, pass this Network in this argument, otherwise pass
5293 * null.
5294 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5295 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5296 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5297 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5298 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005299 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005300 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005301 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5302 // to avoid the slowness. It is not simply enough to process just "changed", for
5303 // example in the case where "changed"'s score decreases and another network should begin
5304 // satifying a NetworkRequest that "changed" currently satisfies.
5305
5306 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5307 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5308 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005309 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005310 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005311 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005312 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005313 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5314 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5315 // Rematch higher scoring networks first to prevent requests first matching a lower
5316 // scoring network and then a higher scoring network, which could produce multiple
5317 // callbacks and inadvertently unlinger networks.
5318 Arrays.sort(nais);
5319 for (NetworkAgentInfo nai : nais) {
5320 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005321 // Only reap the last time through the loop. Reaping before all rematching
5322 // is complete could incorrectly teardown a network that hasn't yet been
5323 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005324 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005325 : ReapUnvalidatedNetworks.REAP,
5326 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005327 }
5328 }
5329 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005330
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005331 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005332 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005333 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005334 // For now only update icons for default connection.
5335 // TODO: Update WiFi and cellular icons separately. b/17237507
5336 if (!isDefaultNetwork(nai)) return;
5337
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005338 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005339 // Don't repeat publish.
5340 if (newInetCondition == mDefaultInetConditionPublished) return;
5341
5342 mDefaultInetConditionPublished = newInetCondition;
5343 sendInetConditionBroadcast(nai.networkInfo);
5344 }
5345
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005346 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005347 synchronized (mVpns) {
5348 if (mLockdownTracker != null) {
5349 if (nai != null && nai.isVPN()) {
5350 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5351 } else {
5352 mLockdownTracker.onNetworkInfoChanged();
5353 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005354 }
5355 }
5356 }
5357
Robert Greenwalt7b816022014-04-18 15:25:25 -07005358 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005359 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005360 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005361 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005362 synchronized (networkAgent) {
5363 oldInfo = networkAgent.networkInfo;
5364 networkAgent.networkInfo = newInfo;
5365 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005366 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005367
Robert Greenwalt7b816022014-04-18 15:25:25 -07005368 if (DBG) {
5369 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5370 (oldInfo == null ? "null" : oldInfo.getState()) +
5371 " to " + state);
5372 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005373
Robin Lee585e2482016-05-01 23:00:00 +01005374 if (!networkAgent.created
5375 && (state == NetworkInfo.State.CONNECTED
5376 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005377
5378 // A network that has just connected has zero requests and is thus a foreground network.
5379 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5380
Robert Greenwalt7b816022014-04-18 15:25:25 -07005381 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005382 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005383 if (networkAgent.isVPN()) {
5384 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005385 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5386 (networkAgent.networkMisc == null ||
5387 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005388 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005389 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005390 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005391 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005392 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005393 loge("Error creating network " + networkAgent.network.netId + ": "
5394 + e.getMessage());
5395 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005396 }
Paul Jenseneec75412014-08-04 12:21:19 -04005397 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005398 }
5399
5400 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5401 networkAgent.everConnected = true;
5402
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09005403 if (networkAgent.linkProperties == null) {
5404 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
5405 }
5406
Erik Kline736353a2018-03-21 07:18:33 -07005407 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005408 updateLinkProperties(networkAgent, null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005409
Paul Jensenca8f16a2014-05-09 12:47:55 -04005410 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005411 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005412
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005413 if (networkAgent.isVPN()) {
5414 // Temporarily disable the default proxy (not global).
5415 synchronized (mProxyLock) {
5416 if (!mDefaultProxyDisabled) {
5417 mDefaultProxyDisabled = true;
5418 if (mGlobalProxy == null && mDefaultProxy != null) {
5419 sendProxyBroadcast(null);
5420 }
5421 }
5422 }
5423 // TODO: support proxy per network.
5424 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005425
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005426 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5427 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5428 // capabilities, so it only needs to be done once on initial connect, not every time the
5429 // network's capabilities change. Note that we do this before rematching the network,
5430 // so we could decide to tear it down immediately afterwards. That's fine though - on
5431 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5432 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005433 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005434
Paul Jensen2161a8e2014-09-11 11:00:39 -04005435 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005436 final long now = SystemClock.elapsedRealtime();
5437 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005438
5439 // This has to happen after matching the requests, because callbacks are just requests.
5440 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005441 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005442 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005443 if (networkAgent.isVPN()) {
5444 synchronized (mProxyLock) {
5445 if (mDefaultProxyDisabled) {
5446 mDefaultProxyDisabled = false;
5447 if (mGlobalProxy == null && mDefaultProxy != null) {
5448 sendProxyBroadcast(mDefaultProxy);
5449 }
5450 }
5451 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005452 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005453 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005454 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5455 state == NetworkInfo.State.SUSPENDED) {
5456 // going into or coming out of SUSPEND: rescore and notify
5457 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005458 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005459 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005460 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5461 networkAgent.networkCapabilities);
5462 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5463 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005464 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5465 ConnectivityManager.CALLBACK_SUSPENDED :
5466 ConnectivityManager.CALLBACK_RESUMED));
5467 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005468 }
5469 }
5470
Robert Greenwaltac96c522014-06-03 16:43:57 -07005471 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005472 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005473 if (score < 0) {
5474 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5475 "). Bumping score to min of 0");
5476 score = 0;
5477 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005478
Paul Jensen2161a8e2014-09-11 11:00:39 -04005479 final int oldScore = nai.getCurrentScore();
5480 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005481
Paul Jensen85cf78e2015-06-25 13:25:07 -04005482 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005483
Paul Jensenc8b9a742014-09-30 15:37:41 -04005484 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005485 }
5486
Erik Klinec75d4fa2017-02-15 19:59:17 +09005487 // Notify only this one new request of the current state. Transfer all the
5488 // current state by calling NetworkCapabilities and LinkProperties callbacks
5489 // so that callers can be guaranteed to have as close to atomicity in state
5490 // transfer as can be supported by this current API.
5491 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005492 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005493 if (nri.mPendingIntent != null) {
5494 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5495 // Attempt no subsequent state pushes where intents are involved.
5496 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005497 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005498
5499 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005500 }
5501
Robert Greenwalt8d482522015-06-24 13:23:42 -07005502 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005503 // The NetworkInfo we actually send out has no bearing on the real
5504 // state of affairs. For example, if the default connection is mobile,
5505 // and a request for HIPRI has just gone away, we need to pretend that
5506 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5507 // the state to DISCONNECTED, even though the network is of type MOBILE
5508 // and is still connected.
5509 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5510 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005511 if (state != DetailedState.DISCONNECTED) {
5512 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005513 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005514 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005515 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005516 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5517 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5518 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5519 if (info.isFailover()) {
5520 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5521 nai.networkInfo.setFailover(false);
5522 }
5523 if (info.getReason() != null) {
5524 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5525 }
5526 if (info.getExtraInfo() != null) {
5527 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5528 }
5529 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005530 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005531 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005532 if (newDefaultAgent != null) {
5533 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5534 newDefaultAgent.networkInfo);
5535 } else {
5536 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5537 }
5538 }
5539 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5540 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005541 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005542 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005543 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005544 }
5545 }
5546 }
5547
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005548 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005549 if (VDBG) {
5550 String notification = ConnectivityManager.getCallbackName(notifyType);
5551 log("notifyType " + notification + " for " + networkAgent.name());
5552 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005553 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5554 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005555 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5556 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005557 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5558 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005559 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005560 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005561 } else {
5562 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5563 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005564 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005565 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005566
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005567 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5568 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5569 }
5570
Jeff Sharkey69736342014-12-08 14:50:12 -08005571 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005572 * Returns the list of all interfaces that could be used by network traffic that does not
5573 * explicitly specify a network. This includes the default network, but also all VPNs that are
5574 * currently connected.
5575 *
5576 * Must be called on the handler thread.
5577 */
5578 private Network[] getDefaultNetworks() {
5579 ArrayList<Network> defaultNetworks = new ArrayList<>();
5580 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5581 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5582 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5583 defaultNetworks.add(nai.network);
5584 }
5585 }
5586 return defaultNetworks.toArray(new Network[0]);
5587 }
5588
5589 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005590 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5591 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005592 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005593 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005594 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005595 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005596 } catch (Exception ignored) {
5597 }
5598 }
5599
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005600 @Override
5601 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005602 int user = UserHandle.getUserId(Binder.getCallingUid());
5603 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005604 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005605 return mVpns.get(user).addAddress(address, prefixLength);
5606 }
5607 }
5608
5609 @Override
5610 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005611 int user = UserHandle.getUserId(Binder.getCallingUid());
5612 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005613 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005614 return mVpns.get(user).removeAddress(address, prefixLength);
5615 }
5616 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005617
5618 @Override
5619 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005620 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005621 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005622 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005623 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005624 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005625 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005626 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005627 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005628 }
5629 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005630 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005631
5632 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005633 public String getCaptivePortalServerUrl() {
Udam Sainic3b640c2017-06-07 12:06:28 -07005634 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005635 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005636 }
5637
5638 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005639 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5640 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5641 enforceKeepalivePermission();
5642 mKeepaliveTracker.startNattKeepalive(
5643 getNetworkAgentInfoForNetwork(network),
5644 intervalSeconds, messenger, binder,
5645 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5646 }
5647
5648 @Override
5649 public void stopKeepalive(Network network, int slot) {
5650 mHandler.sendMessage(mHandler.obtainMessage(
5651 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5652 }
5653
5654 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005655 public void factoryReset() {
5656 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005657
5658 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5659 return;
5660 }
5661
Robin Lee3b3dd942015-05-12 18:14:58 +01005662 final int userId = UserHandle.getCallingUserId();
5663
Stuart Scottf1fb3972015-04-02 18:00:02 -07005664 // Turn airplane mode off
5665 setAirplaneMode(false);
5666
Stuart Scotte3e314d2015-04-20 14:07:45 -07005667 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5668 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005669 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005670 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005671 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005672 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005673 }
5674
Stuart Scotte3e314d2015-04-20 14:07:45 -07005675 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005676 // Remove always-on package
5677 synchronized (mVpns) {
5678 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5679 if (alwaysOnPackage != null) {
5680 setAlwaysOnVpnPackage(userId, null, false);
5681 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5682 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005683
Hugo Benichi69744342017-11-27 10:57:16 +09005684 // Turn Always-on VPN off
5685 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5686 final long ident = Binder.clearCallingIdentity();
5687 try {
5688 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5689 mLockdownEnabled = false;
5690 setLockdownTracker(null);
5691 } finally {
5692 Binder.restoreCallingIdentity(ident);
5693 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005694 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005695
Hugo Benichi69744342017-11-27 10:57:16 +09005696 // Turn VPN off
5697 VpnConfig vpnConfig = getVpnConfig(userId);
5698 if (vpnConfig != null) {
5699 if (vpnConfig.legacy) {
5700 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5701 } else {
5702 // Prevent this app (packagename = vpnConfig.user) from initiating
5703 // VPN connections in the future without user intervention.
5704 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005705
Hugo Benichi69744342017-11-27 10:57:16 +09005706 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5707 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005708 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005709 }
5710 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005711
5712 Settings.Global.putString(mContext.getContentResolver(),
5713 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005714 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005715
5716 @VisibleForTesting
5717 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5718 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5719 return new NetworkMonitor(context, handler, nai, defaultRequest);
5720 }
Erik Kline48f12f22016-04-14 17:30:59 +09005721
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005722 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005723 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5724 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005725 }
5726
5727 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005728 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5729 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5730 }
5731
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005732 @VisibleForTesting
5733 public boolean hasService(String name) {
5734 return ServiceManager.checkService(name) != null;
5735 }
5736
Hugo Benichi64901e52017-10-19 14:42:40 +09005737 @VisibleForTesting
5738 protected IpConnectivityMetrics.Logger metricsLogger() {
5739 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5740 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005741 }
5742
5743 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005744 int[] transports = nai.networkCapabilities.getTransportTypes();
5745 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005746 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005747
5748 private static boolean toBool(int encodedBoolean) {
5749 return encodedBoolean != 0; // Only 0 means false.
5750 }
5751
5752 private static int encodeBool(boolean b) {
5753 return b ? 1 : 0;
5754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005755}