blob: 995f926479820ba8dd6f46b304577327ee317aaa [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:
905 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
906 // 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 Klineda4bfa82015-04-30 12:58:40 +0900914 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900915 final boolean enable = toBool(Settings.Global.getInt(
916 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900917 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
918 if (enable == isEnabled) {
919 return; // Nothing to do.
920 }
921
922 if (enable) {
923 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900924 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900925 } else {
926 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
927 }
928 }
929
930 private void registerSettingsCallbacks() {
931 // Watch for global HTTP proxy changes.
932 mSettingsObserver.observe(
933 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
934 EVENT_APPLY_GLOBAL_HTTP_PROXY);
935
936 // Watch for whether or not to keep mobile data always on.
937 mSettingsObserver.observe(
938 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
939 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
940 }
941
Erik Klinea24d4592018-01-11 21:07:29 +0900942 private void registerPrivateDnsSettingsCallbacks() {
943 for (Uri u : DnsManager.getPrivateDnsSettingsUris()) {
944 mSettingsObserver.observe(u, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
945 }
946 }
947
Robert Greenwalt34524f02014-05-18 16:22:10 -0700948 private synchronized int nextNetworkRequestId() {
949 return mNextNetworkRequestId++;
950 }
951
Paul Jensen67b0b072015-06-10 11:22:17 -0400952 @VisibleForTesting
953 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400954 synchronized (mNetworkForNetId) {
955 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
956 int netId = mNextNetId;
957 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
958 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500959 if (!mNetIdInUse.get(netId)) {
960 mNetIdInUse.put(netId, true);
961 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400962 }
963 }
964 }
965 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700966 }
967
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600968 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800969 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600970 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
971 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800972 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600973 state = nai.getNetworkState();
974 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800975 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600976 final NetworkInfo info = new NetworkInfo(networkType, 0,
977 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800978 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
979 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -0700980 final NetworkCapabilities capabilities = new NetworkCapabilities();
981 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
982 !info.isRoaming());
983 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600984 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800985 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600986 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600987 return state;
988 } else {
989 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800990 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400991 }
992
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800993 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
994 if (network == null) {
995 return null;
996 }
997 synchronized (mNetworkForNetId) {
998 return mNetworkForNetId.get(network.netId);
999 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001000 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001001
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001002 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001003 synchronized (mVpns) {
1004 if (!mLockdownEnabled) {
1005 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001006 Vpn vpn = mVpns.get(user);
1007 if (vpn != null && vpn.appliesToUid(uid)) {
1008 return vpn.getUnderlyingNetworks();
1009 }
1010 }
1011 }
1012 return null;
1013 }
1014
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001015 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001016 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001017
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001018 final Network[] networks = getVpnUnderlyingNetworks(uid);
1019 if (networks != null) {
1020 // getUnderlyingNetworks() returns:
1021 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1022 // empty array => the VPN explicitly said "no default network".
1023 // non-empty array => the VPN specified one or more default networks; we use the
1024 // first one.
1025 if (networks.length > 0) {
1026 nai = getNetworkAgentInfoForNetwork(networks[0]);
1027 } else {
1028 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001029 }
1030 }
1031
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001032 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001033 return nai.getNetworkState();
1034 } else {
1035 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001036 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001037 }
1038
1039 /**
1040 * Check if UID should be blocked from using the network with the given LinkProperties.
1041 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001042 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1043 boolean ignoreBlocked) {
1044 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001045 if (ignoreBlocked) {
1046 return false;
1047 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001048 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001049 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1050 if (isSystem(uid)) {
1051 return false;
1052 }
Robin Lee17e61832016-05-09 13:46:28 +01001053 synchronized (mVpns) {
1054 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1055 if (vpn != null && vpn.isBlockingUid(uid)) {
1056 return true;
1057 }
1058 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001059 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001060 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001061 }
1062
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001063 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001064 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1065 return;
1066 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001067 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001068 synchronized (mBlockedAppUids) {
1069 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001070 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001071 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001072 blocked = false;
1073 } else {
1074 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001075 }
1076 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001077 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1078 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1079 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001080 }
1081
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001082 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001083 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1084 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001085 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001086 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001087 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001088 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1089
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001090 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001091 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001092 }
Hugo Benichi69744342017-11-27 10:57:16 +09001093 synchronized (mVpns) {
1094 if (mLockdownTracker != null) {
1095 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1096 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001097 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001098 }
1099
1100 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 * Return NetworkInfo for the active (i.e., connected) network interface.
1102 * It is assumed that at most one network is active at a time. If more
1103 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001104 * @return the info for the active network, or {@code null} if none is
1105 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001107 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001109 enforceAccessPermission();
1110 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001111 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001112 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001113 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1114 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 }
1116
Paul Jensen31a94f42015-02-13 14:18:39 -05001117 @Override
1118 public Network getActiveNetwork() {
1119 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001120 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001121 }
1122
1123 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001124 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001125 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001126 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001127 }
1128
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001129 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001130 final int user = UserHandle.getUserId(uid);
1131 int vpnNetId = NETID_UNSET;
1132 synchronized (mVpns) {
1133 final Vpn vpn = mVpns.get(user);
1134 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1135 }
1136 NetworkAgentInfo nai;
1137 if (vpnNetId != NETID_UNSET) {
1138 synchronized (mNetworkForNetId) {
1139 nai = mNetworkForNetId.get(vpnNetId);
1140 }
1141 if (nai != null) return nai.network;
1142 }
1143 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001144 if (nai != null
1145 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1146 nai = null;
1147 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001148 return nai != null ? nai.network : null;
1149 }
1150
Lorenzo Colitti18660282016-07-04 12:55:44 +09001151 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001152 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1153 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001154 final int uid = Binder.getCallingUid();
1155 NetworkState state = getUnfilteredActiveNetworkState(uid);
1156 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001157 }
1158
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001159 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001160 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001161 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001162 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001163 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001164 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001165 }
1166
1167 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 public NetworkInfo getNetworkInfo(int networkType) {
1169 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001170 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001171 if (getVpnUnderlyingNetworks(uid) != null) {
1172 // A VPN is active, so we may need to return one of its underlying networks. This
1173 // information is not available in LegacyTypeTracker, so we have to get it from
1174 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001175 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001176 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001177 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001178 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001179 }
1180 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001181 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001182 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 }
1184
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001185 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001186 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001187 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001188 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001189 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001190 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001191 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001192 return state.networkInfo;
1193 } else {
1194 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001195 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001196 }
1197
1198 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 public NetworkInfo[] getAllNetworkInfo() {
1200 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001201 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001202 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1203 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001204 NetworkInfo info = getNetworkInfo(networkType);
1205 if (info != null) {
1206 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001209 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 }
1211
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001212 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001213 public Network getNetworkForType(int networkType) {
1214 enforceAccessPermission();
1215 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001216 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1217 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001218 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001219 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001220 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001221 }
1222
1223 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001224 public Network[] getAllNetworks() {
1225 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001226 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001227 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001228 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001229 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001230 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001231 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001232 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001233 }
1234
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001235 @Override
1236 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1237 // The basic principle is: if an app's traffic could possibly go over a
1238 // network, without the app doing anything multinetwork-specific,
1239 // (hence, by "default"), then include that network's capabilities in
1240 // the array.
1241 //
1242 // In the normal case, app traffic only goes over the system's default
1243 // network connection, so that's the only network returned.
1244 //
1245 // With a VPN in force, some app traffic may go into the VPN, and thus
1246 // over whatever underlying networks the VPN specifies, while other app
1247 // traffic may go over the system default network (e.g.: a split-tunnel
1248 // VPN, or an app disallowed by the VPN), so the set of networks
1249 // returned includes the VPN's underlying networks and the system
1250 // default.
1251 enforceAccessPermission();
1252
1253 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1254
1255 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001256 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001257 if (nc != null) {
1258 result.put(nai.network, nc);
1259 }
1260
Hugo Benichi69744342017-11-27 10:57:16 +09001261 synchronized (mVpns) {
1262 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001263 Vpn vpn = mVpns.get(userId);
1264 if (vpn != null) {
1265 Network[] networks = vpn.getUnderlyingNetworks();
1266 if (networks != null) {
1267 for (Network network : networks) {
1268 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001269 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001270 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001271 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001272 }
1273 }
1274 }
1275 }
1276 }
1277 }
1278
1279 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1280 out = result.values().toArray(out);
1281 return out;
1282 }
1283
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001284 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001285 public boolean isNetworkSupported(int networkType) {
1286 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001287 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001288 }
1289
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001290 /**
1291 * Return LinkProperties for the active (i.e., connected) default
1292 * network interface. It is assumed that at most one default network
1293 * is active at a time. If more than one is active, it is indeterminate
1294 * which will be returned.
1295 * @return the ip properties for the active network, or {@code null} if
1296 * none is active
1297 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001298 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001299 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001300 enforceAccessPermission();
1301 final int uid = Binder.getCallingUid();
1302 NetworkState state = getUnfilteredActiveNetworkState(uid);
1303 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001304 }
1305
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001306 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001307 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001308 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001309 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1310 if (nai != null) {
1311 synchronized (nai) {
1312 return new LinkProperties(nai.linkProperties);
1313 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001314 }
1315 return null;
1316 }
1317
Robert Greenwalt12e67352014-05-13 21:41:06 -07001318 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001319 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001320 public LinkProperties getLinkProperties(Network network) {
1321 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001322 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1323 }
1324
1325 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1326 if (nai == null) {
1327 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001328 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001329 synchronized (nai) {
1330 return new LinkProperties(nai.linkProperties);
1331 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001332 }
1333
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001334 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001335 if (nai != null) {
1336 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001337 if (nai.networkCapabilities != null) {
Chalard Jeanb552c462018-02-21 18:43:54 +09001338 return networkCapabilitiesWithoutUidsUnlessAllowed(nai.networkCapabilities,
1339 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001340 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001341 }
1342 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001343 return null;
1344 }
1345
1346 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001347 public NetworkCapabilities getNetworkCapabilities(Network network) {
1348 enforceAccessPermission();
1349 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1350 }
1351
Chalard Jeanb552c462018-02-21 18:43:54 +09001352 private NetworkCapabilities networkCapabilitiesWithoutUidsUnlessAllowed(
1353 NetworkCapabilities nc, int callerPid, int callerUid) {
1354 if (checkSettingsPermission(callerPid, callerUid)) return new NetworkCapabilities(nc);
Chalard Jeanf19db372018-01-26 19:24:40 +09001355 return new NetworkCapabilities(nc).setUids(null);
1356 }
1357
Chalard Jeanb552c462018-02-21 18:43:54 +09001358 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1359 if (!checkSettingsPermission()) {
1360 nc.setSingleUid(Binder.getCallingUid());
1361 }
1362 }
1363
Chalard Jean1d738002018-03-20 19:13:57 +09001364 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1365 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1366 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1367 }
1368 }
1369
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001370 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001371 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001372 // Require internal since we're handing out IMSI details
1373 enforceConnectivityInternalPermission();
1374
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001375 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001376 for (Network network : getAllNetworks()) {
1377 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1378 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001379 // TODO (b/73321673) : NetworkState contains a copy of the
1380 // NetworkCapabilities, which may contain UIDs of apps to which the
1381 // network applies. Should the UIDs be cleared so as not to leak or
1382 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001383 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001384 }
1385 }
1386 return result.toArray(new NetworkState[result.size()]);
1387 }
1388
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001389 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001390 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001391 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001392 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1393 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1394 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001395 }
1396
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001397 @Override
1398 public boolean isActiveNetworkMetered() {
1399 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001400
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001401 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
1402 if (caps != null) {
1403 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1404 } else {
1405 // Always return the most conservative value
1406 return true;
1407 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001408 }
1409
Jeff Sharkey216c1812012-08-05 14:29:23 -07001410 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1411 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001412 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001413 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001414 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001415 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001416 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001417
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001418 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 * Ensure that a network route exists to deliver traffic to the specified
1420 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001421 * @param networkType the type of the network over which traffic to the
1422 * specified host is to be routed
1423 * @param hostAddress the IP address of the host to which the route is
1424 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 * @return {@code true} on success, {@code false} on failure
1426 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001427 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001428 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001430 if (mProtectedNetworks.contains(networkType)) {
1431 enforceConnectivityInternalPermission();
1432 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001433
Chad Brubakerc0234532014-02-14 13:24:29 -08001434 InetAddress addr;
1435 try {
1436 addr = InetAddress.getByAddress(hostAddress);
1437 } catch (UnknownHostException e) {
1438 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1439 return false;
1440 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001443 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 return false;
1445 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001446
1447 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1448 if (nai == null) {
1449 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1450 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1451 } else {
1452 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1453 }
1454 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001455 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001456
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001457 DetailedState netState;
1458 synchronized (nai) {
1459 netState = nai.networkInfo.getDetailedState();
1460 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001461
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001462 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001463 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001464 log("requestRouteToHostAddress on down network "
1465 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001466 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001467 }
1468 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001470
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001471 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001472 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001473 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001474 LinkProperties lp;
1475 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001476 synchronized (nai) {
1477 lp = nai.linkProperties;
1478 netId = nai.network.netId;
1479 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001480 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001481 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1482 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001483 } finally {
1484 Binder.restoreCallingIdentity(token);
1485 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001486 }
1487
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001488 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001489 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001490 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001491 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001492 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001493 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001494 if (bestRoute.getGateway().equals(addr)) {
1495 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001496 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001497 } else {
1498 // if we will connect to this through another route, add a direct route
1499 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001500 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001501 }
1502 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001503 if (DBG) log("Adding legacy route " + bestRoute +
1504 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001505 try {
1506 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1507 } catch (Exception e) {
1508 // never crash - catch them all
1509 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001510 return false;
1511 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001512 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 }
1514
Jeff Sharkey75d31892018-01-18 22:01:59 +09001515 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001516 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001517 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001518 // TODO: notify UID when it has requested targeted updates
1519 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001520 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001521 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001522 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001523 if (restrictBackground) {
1524 log("onRestrictBackgroundChanged(true): disabling tethering");
1525 mTethering.untetherAll();
1526 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001527 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001528 };
1529
Robin Lee3b3dd942015-05-12 18:14:58 +01001530 /**
1531 * Require that the caller is either in the same user or has appropriate permission to interact
1532 * across users.
1533 *
1534 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1535 */
1536 private void enforceCrossUserPermission(int userId) {
1537 if (userId == UserHandle.getCallingUserId()) {
1538 // Not a cross-user call.
1539 return;
1540 }
1541 mContext.enforceCallingOrSelfPermission(
1542 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1543 "ConnectivityService");
1544 }
1545
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001546 private void enforceInternetPermission() {
1547 mContext.enforceCallingOrSelfPermission(
1548 android.Manifest.permission.INTERNET,
1549 "ConnectivityService");
1550 }
1551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001553 mContext.enforceCallingOrSelfPermission(
1554 android.Manifest.permission.ACCESS_NETWORK_STATE,
1555 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 }
1557
1558 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001559 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 }
1561
Charles Hea0a87e82017-05-15 17:07:18 +01001562 private void enforceSettingsPermission() {
1563 mContext.enforceCallingOrSelfPermission(
1564 android.Manifest.permission.NETWORK_SETTINGS,
1565 "ConnectivityService");
1566 }
1567
Chalard Jeanb552c462018-02-21 18:43:54 +09001568 private boolean checkSettingsPermission() {
1569 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1570 android.Manifest.permission.NETWORK_SETTINGS);
1571 }
1572
1573 private boolean checkSettingsPermission(int pid, int uid) {
1574 return PERMISSION_GRANTED == mContext.checkPermission(
1575 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1576 }
1577
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001578 private void enforceTetherAccessPermission() {
1579 mContext.enforceCallingOrSelfPermission(
1580 android.Manifest.permission.ACCESS_NETWORK_STATE,
1581 "ConnectivityService");
1582 }
1583
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001584 private void enforceConnectivityInternalPermission() {
1585 mContext.enforceCallingOrSelfPermission(
1586 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1587 "ConnectivityService");
1588 }
1589
Hugo Benichi514da602016-07-19 15:59:27 +09001590 private void enforceConnectivityRestrictedNetworksPermission() {
1591 try {
1592 mContext.enforceCallingOrSelfPermission(
1593 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1594 "ConnectivityService");
1595 return;
1596 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1597 enforceConnectivityInternalPermission();
1598 }
1599
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001600 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001601 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001602 }
1603
Lorenzo Colitti18660282016-07-04 12:55:44 +09001604 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001605 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001606 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001607 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001608 }
1609
1610 private void sendInetConditionBroadcast(NetworkInfo info) {
1611 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1612 }
1613
Wink Saville628b0852011-08-04 15:01:58 -07001614 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001615 synchronized (mVpns) {
1616 if (mLockdownTracker != null) {
1617 info = new NetworkInfo(info);
1618 mLockdownTracker.augmentNetworkInfo(info);
1619 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001620 }
1621
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001622 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001623 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001624 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 if (info.isFailover()) {
1626 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1627 info.setFailover(false);
1628 }
1629 if (info.getReason() != null) {
1630 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1631 }
1632 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001633 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1634 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001636 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001637 return intent;
1638 }
1639
1640 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1641 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1642 }
1643
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001644 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001645 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1646 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1647 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001648 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001649 final long ident = Binder.clearCallingIdentity();
1650 try {
1651 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1652 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1653 } finally {
1654 Binder.restoreCallingIdentity(ident);
1655 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001656 }
1657
Mike Lockwood0f79b542009-08-14 14:18:49 -04001658 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001659 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001660 if (!mSystemReady) {
1661 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001662 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001663 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001664 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001665 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001666 }
1667
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001668 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001669 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001670 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001671 final NetworkInfo ni = intent.getParcelableExtra(
1672 ConnectivityManager.EXTRA_NETWORK_INFO);
1673 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1674 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1675 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001676 } else {
1677 BroadcastOptions opts = BroadcastOptions.makeBasic();
1678 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1679 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001680 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001681 final IBatteryStats bs = BatteryStatsService.getService();
1682 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001683 bs.noteConnectivityChanged(intent.getIntExtra(
1684 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1685 ni != null ? ni.getState().toString() : "?");
1686 } catch (RemoteException e) {
1687 }
1688 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001689 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001690 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001691 } finally {
1692 Binder.restoreCallingIdentity(ident);
1693 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001694 }
1695 }
1696
1697 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001698 loadGlobalProxy();
1699
Hugo Benichi20035e02017-04-26 14:53:28 +09001700 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001701 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001702 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001703 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001704 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001705 }
1706 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001707 // load the global proxy at startup
1708 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001709
Robin Lee244ce8e2016-01-05 18:03:46 +00001710 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1711 // for user to unlock device too.
1712 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001713
Erik Klineda4bfa82015-04-30 12:58:40 +09001714 // Configure whether mobile data is always on.
1715 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1716
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001717 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001718
1719 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 }
1721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001723 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001724 *
1725 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001726 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001727 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001728 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1729 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001730
1731 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001732 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001733
Robert Greenwalt7b816022014-04-18 15:25:25 -07001734 if (networkAgent.networkCapabilities.hasTransport(
1735 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001736 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1737 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001738 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001739 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001740 } else if (networkAgent.networkCapabilities.hasTransport(
1741 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001742 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1743 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001744 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001745 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001746 } else {
1747 // do not track any other networks
1748 timeout = 0;
1749 }
1750
Robert Greenwalt7b816022014-04-18 15:25:25 -07001751 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001752 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001753 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001754 } catch (Exception e) {
1755 // You shall not crash!
1756 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001757 }
1758 }
1759 }
1760
1761 /**
1762 * Remove data activity tracking when network disconnects.
1763 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001764 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1765 final String iface = networkAgent.linkProperties.getInterfaceName();
1766 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001767
Robert Greenwalt7b816022014-04-18 15:25:25 -07001768 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1769 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001770 try {
1771 // the call fails silently if no idletimer setup for this interface
1772 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001773 } catch (Exception e) {
1774 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001775 }
1776 }
1777 }
1778
1779 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001780 * Reads the network specific MTU size from reources.
1781 * and set it on it's iface.
1782 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001783 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1784 final String iface = newLp.getInterfaceName();
1785 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001786 if (oldLp == null && mtu == 0) {
1787 // Silently ignore unset MTU value.
1788 return;
1789 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001790 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1791 if (VDBG) log("identical MTU - not setting");
1792 return;
1793 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001794 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001795 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001796 return;
1797 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001798
w1997615afd812014-08-05 15:18:11 -07001799 // Cannot set MTU without interface name
1800 if (TextUtils.isEmpty(iface)) {
1801 loge("Setting MTU size with null iface.");
1802 return;
1803 }
1804
Robert Greenwalt7b816022014-04-18 15:25:25 -07001805 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001806 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001807 mNetd.setMtu(iface, mtu);
1808 } catch (Exception e) {
1809 Slog.e(TAG, "exception in setMtu()" + e);
1810 }
1811 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001812
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001813 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001814 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1815
1816 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001817 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001818 protected MockableSystemProperties getSystemProperties() {
1819 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001820 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001821
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001822 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1823 if (isDefaultNetwork(nai) == false) {
1824 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001825 }
1826
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001827 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1828 String[] values = null;
1829 if (tcpBufferSizes != null) {
1830 values = tcpBufferSizes.split(",");
1831 }
1832
1833 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001834 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001835 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1836 values = tcpBufferSizes.split(",");
1837 }
1838
1839 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1840
1841 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001842 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001843
1844 final String prefix = "/sys/kernel/ipv4/tcp_";
1845 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1846 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1847 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1848 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1849 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1850 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1851 mCurrentTcpBufferSizes = tcpBufferSizes;
1852 } catch (IOException e) {
1853 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001854 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001855
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001856 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001857 Settings.Global.TCP_DEFAULT_INIT_RWND,
1858 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001859 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1860 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001861 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001862 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001863 }
1864
Robert Greenwalt562cc542014-05-15 18:07:26 -07001865 @Override
1866 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001867 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001868 NETWORK_RESTORE_DELAY_PROP_NAME);
1869 if(restoreDefaultNetworkDelayStr != null &&
1870 restoreDefaultNetworkDelayStr.length() != 0) {
1871 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001872 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001873 } catch (NumberFormatException e) {
1874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001876 // if the system property isn't set, use the value for the apn type
1877 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1878
1879 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1880 (mNetConfigs[networkType] != null)) {
1881 ret = mNetConfigs[networkType].restoreTime;
1882 }
1883 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 }
1885
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001886 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001887 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001888 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001889 }
1890 return false;
1891 }
1892
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001893 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1894 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1895 final long DIAG_TIME_MS = 5000;
1896 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1897 // Start gathering diagnostic information.
1898 netDiags.add(new NetworkDiagnostics(
1899 nai.network,
1900 new LinkProperties(nai.linkProperties), // Must be a copy.
1901 DIAG_TIME_MS));
1902 }
1903
1904 for (NetworkDiagnostics netDiag : netDiags) {
1905 pw.println();
1906 netDiag.waitForMeasurements();
1907 netDiag.dump(pw);
1908 }
1909 }
1910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001912 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1913 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001914 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001915
Erik Kline7747fd42017-05-12 16:52:48 +09001916 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001917 dumpNetworkDiagnostics(pw);
1918 return;
Erik Klineee363c42017-05-29 09:11:03 +09001919 } else if (argsContain(args, TETHERING_ARG)) {
1920 mTethering.dump(fd, pw, args);
1921 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001922 }
Erik Kline379747a2015-06-05 17:47:34 +09001923
Lorenzo Colittie3805462015-06-03 11:18:24 +09001924 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001925 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001926 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001927 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001928 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001929 pw.println();
1930
Paul Jensen85cf78e2015-06-25 13:25:07 -04001931 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001932 pw.print("Active default network: ");
1933 if (defaultNai == null) {
1934 pw.println("none");
1935 } else {
1936 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001938 pw.println();
1939
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001940 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001941 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001942 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1943 pw.println(nai.toString());
1944 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001945 pw.println(String.format(
1946 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1947 nai.numForegroundNetworkRequests(),
1948 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1949 nai.numBackgroundNetworkRequests(),
1950 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001951 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001952 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1953 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001954 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001955 pw.decreaseIndent();
1956 pw.println("Lingered:");
1957 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001958 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001959 pw.decreaseIndent();
1960 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001961 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001962 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001963 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001964
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001965 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001966 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001967 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1968 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001969 }
1970 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001971 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001972
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001973 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001974
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001975 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001976 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001977
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001978 pw.println();
1979 mKeepaliveTracker.dump(pw);
1980
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001981 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001982 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001983
Erik Kline7747fd42017-05-12 16:52:48 +09001984 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001985 pw.println();
1986 synchronized (mValidationLogs) {
1987 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001988 for (ValidationLog p : mValidationLogs) {
1989 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001990 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001991 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001992 pw.decreaseIndent();
1993 }
1994 }
Erik Kline7523eb32015-07-09 18:24:03 +09001995
1996 pw.println();
1997 pw.println("mNetworkRequestInfoLogs (most recent first):");
1998 pw.increaseIndent();
1999 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2000 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002001
2002 pw.println();
2003 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2004 pw.increaseIndent();
2005 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2006 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002007
2008 pw.println();
2009 pw.println("NetTransition WakeLock activity (most recent first):");
2010 pw.increaseIndent();
Hugo Benichic3318aa2017-09-05 13:25:07 +09002011 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2012 pw.println("total releases: " + mTotalWakelockReleases);
2013 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2014 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2015 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2016 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2017 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2018 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002019 mWakelockLogs.reverseDump(fd, pw, args);
2020 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002022 }
2023
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002024 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002025 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002026 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002027 if (officialNai != null && officialNai.equals(nai)) return true;
2028 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002029 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002030 " - " + nai);
2031 }
2032 return false;
2033 }
2034
Robert Greenwalt42acef32009-08-12 16:08:25 -07002035 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002036 private class NetworkStateTrackerHandler extends Handler {
2037 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002038 super(looper);
2039 }
2040
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002041 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002043 default:
2044 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002045 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002046 handleAsyncChannelHalfConnect(msg);
2047 break;
2048 }
2049 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2050 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2051 if (nai != null) nai.asyncChannel.disconnect();
2052 break;
2053 }
2054 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2055 handleAsyncChannelDisconnected(msg);
2056 break;
2057 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002058 }
2059 return true;
2060 }
2061
2062 private void maybeHandleNetworkAgentMessage(Message msg) {
2063 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2064 if (nai == null) {
2065 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002066 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002067 }
2068 return;
2069 }
2070
2071 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002072 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002073 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2074 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002075 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2076 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002077 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002078 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002079 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002080 break;
2081 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002082 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002083 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002084 break;
2085 }
2086 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002087 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002088 updateNetworkInfo(nai, info);
2089 break;
2090 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002091 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002092 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002093 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002094 break;
2095 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002096 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002097 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2098 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002099 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002100 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002101 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002102 break;
2103 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002104 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002105 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2106 break;
2107 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002108 }
2109 }
2110
2111 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2112 switch (msg.what) {
2113 default:
2114 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002115 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002116 final NetworkAgentInfo nai;
2117 synchronized (mNetworkForNetId) {
2118 nai = mNetworkForNetId.get(msg.arg2);
2119 }
Erik Klinea24d4592018-01-11 21:07:29 +09002120 if (nai == null) break;
2121
2122 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2123 final boolean wasValidated = nai.lastValidated;
2124 final boolean wasDefault = isDefaultNetwork(nai);
2125
2126 final PrivateDnsConfig privateDnsCfg = (msg.obj instanceof PrivateDnsConfig)
2127 ? (PrivateDnsConfig) msg.obj : null;
2128 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2129
2130 final boolean reevaluationRequired;
2131 final String logMsg;
2132 if (valid) {
2133 reevaluationRequired = updatePrivateDns(nai, privateDnsCfg);
2134 logMsg = (DBG && (privateDnsCfg != null))
2135 ? " with " + privateDnsCfg.toString() : "";
2136 } else {
2137 reevaluationRequired = false;
2138 logMsg = (DBG && !TextUtils.isEmpty(redirectUrl))
2139 ? " with redirect to " + redirectUrl : "";
2140 }
2141 if (DBG) {
2142 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2143 }
2144 // If there is a change in Private DNS configuration,
2145 // trigger reevaluation of the network to test it.
2146 if (reevaluationRequired) {
2147 nai.networkMonitor.sendMessage(
2148 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2149 break;
2150 }
2151 if (valid != nai.lastValidated) {
2152 if (wasDefault) {
2153 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2154 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002155 }
Erik Klinea24d4592018-01-11 21:07:29 +09002156 final int oldScore = nai.getCurrentScore();
2157 nai.lastValidated = valid;
2158 nai.everValidated |= valid;
2159 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2160 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2161 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2162 }
2163 updateInetCondition(nai);
2164 // Let the NetworkAgent know the state of its network
2165 Bundle redirectUrlBundle = new Bundle();
2166 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2167 nai.asyncChannel.sendMessage(
2168 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2169 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2170 0, redirectUrlBundle);
2171 if (wasValidated && !nai.lastValidated) {
2172 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002173 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002174 break;
2175 }
Paul Jensen869868be2014-05-15 10:33:05 -04002176 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002177 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002178 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002179 final NetworkAgentInfo nai;
2180 synchronized (mNetworkForNetId) {
2181 nai = mNetworkForNetId.get(netId);
2182 }
Calvin Onbe96da12016-10-11 15:10:46 -07002183 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002184 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002185 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002186 nai.lastCaptivePortalDetected = visible;
2187 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002188 if (nai.lastCaptivePortalDetected &&
2189 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2190 if (DBG) log("Avoiding captive portal network: " + nai.name());
2191 nai.asyncChannel.sendMessage(
2192 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2193 teardownUnneededNetwork(nai);
2194 break;
2195 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002196 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002197 }
2198 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002199 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002200 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002201 if (nai == null) {
2202 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2203 break;
2204 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002205 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002206 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002207 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002208 }
Paul Jensen869868be2014-05-15 10:33:05 -04002209 }
Paul Jensen869868be2014-05-15 10:33:05 -04002210 break;
2211 }
Erik Klinea24d4592018-01-11 21:07:29 +09002212 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
2213 final NetworkAgentInfo nai;
2214 synchronized (mNetworkForNetId) {
2215 nai = mNetworkForNetId.get(msg.arg2);
2216 }
2217 if (nai == null) break;
2218
2219 final PrivateDnsConfig cfg = (PrivateDnsConfig) msg.obj;
2220 final boolean reevaluationRequired = updatePrivateDns(nai, cfg);
2221 if (nai.lastValidated && reevaluationRequired) {
2222 nai.networkMonitor.sendMessage(
2223 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2224 }
2225 break;
2226 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002227 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002228 return true;
2229 }
2230
Calvin Onbe96da12016-10-11 15:10:46 -07002231 private int getCaptivePortalMode() {
2232 return Settings.Global.getInt(mContext.getContentResolver(),
2233 Settings.Global.CAPTIVE_PORTAL_MODE,
2234 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2235 }
2236
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002237 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2238 switch (msg.what) {
2239 default:
2240 return false;
2241 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2242 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2243 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2244 handleLingerComplete(nai);
2245 }
2246 break;
2247 }
2248 }
2249 return true;
2250 }
2251
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002252 @Override
2253 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002254 if (!maybeHandleAsyncChannelMessage(msg) &&
2255 !maybeHandleNetworkMonitorMessage(msg) &&
2256 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002257 maybeHandleNetworkAgentMessage(msg);
2258 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002259 }
2260 }
2261
Erik Klinea24d4592018-01-11 21:07:29 +09002262 private void handlePrivateDnsSettingsChanged() {
2263 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2264
2265 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2266 // Private DNS only ever applies to networks that might provide
2267 // Internet access and therefore also require validation.
2268 if (!NetworkMonitor.isValidationRequired(
2269 mDefaultRequest.networkCapabilities, nai.networkCapabilities)) {
2270 continue;
2271 }
2272
2273 // Notify the NetworkMonitor thread in case it needs to cancel or
2274 // schedule DNS resolutions. If a DNS resolution is required the
2275 // result will be sent back to us.
2276 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2277
2278 if (!cfg.inStrictMode()) {
2279 // No strict mode hostname DNS resolution needed, so just update
2280 // DNS settings directly. In opportunistic and "off" modes this
2281 // just reprograms netd with the network-supplied DNS servers
2282 // (and of course the boolean of whether or not to attempt TLS).
2283 //
2284 // TODO: Consider code flow parity with strict mode, i.e. having
2285 // NetworkMonitor relay the PrivateDnsConfig back to us and then
2286 // performing this call at that time.
2287 updatePrivateDns(nai, cfg);
2288 }
2289 }
2290 }
2291
2292 private boolean updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2293 final boolean reevaluationRequired = true;
2294 final boolean dontReevaluate = false;
2295
2296 final PrivateDnsConfig oldCfg = mDnsManager.updatePrivateDns(nai.network, newCfg);
2297 updateDnses(nai.linkProperties, null, nai.network.netId);
2298
2299 if (newCfg == null) {
2300 if (oldCfg == null) return dontReevaluate;
2301 return oldCfg.useTls ? reevaluationRequired : dontReevaluate;
2302 }
2303
2304 if (oldCfg == null) {
2305 return newCfg.useTls ? reevaluationRequired : dontReevaluate;
2306 }
2307
2308 if (oldCfg.useTls != newCfg.useTls) {
2309 return reevaluationRequired;
2310 }
2311
2312 if (newCfg.inStrictMode() && !Objects.equals(oldCfg.hostname, newCfg.hostname)) {
2313 return reevaluationRequired;
2314 }
2315
2316 return dontReevaluate;
2317 }
2318
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002319 private void updateLingerState(NetworkAgentInfo nai, long now) {
2320 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2321 // 2. If the network was lingering and there are now requests, unlinger it.
2322 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2323 // one lingered request, start lingering.
2324 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002325 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002326 if (DBG) log("Unlingering " + nai.name());
2327 nai.unlinger();
2328 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002329 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002330 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002331 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002332 nai.linger();
2333 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2334 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2335 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002336 }
2337
Robert Greenwalt7b816022014-04-18 15:25:25 -07002338 private void handleAsyncChannelHalfConnect(Message msg) {
2339 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002340 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002341 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2342 if (VDBG) log("NetworkFactory connected");
2343 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002344 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002345 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002346 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002347 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002348 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002349 }
2350 } else {
2351 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002352 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002353 }
2354 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2355 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2356 if (VDBG) log("NetworkAgent connected");
2357 // A network agent has requested a connection. Establish the connection.
2358 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2359 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2360 } else {
2361 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002362 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002363 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002364 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002365 synchronized (mNetworkForNetId) {
2366 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002367 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002368 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002369 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002370 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002371 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002372 }
2373 }
2374 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002375
Robert Greenwalt7b816022014-04-18 15:25:25 -07002376 private void handleAsyncChannelDisconnected(Message msg) {
2377 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2378 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002379 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002380 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002381 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002382 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002383 // TODO - if we move the logic to the network agent (have them disconnect
2384 // because they lost all their requests or because their score isn't good)
2385 // then they would disconnect organically, report their new state and then
2386 // disconnect the channel.
2387 if (nai.networkInfo.isConnected()) {
2388 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2389 null, null);
2390 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002391 final boolean wasDefault = isDefaultNetwork(nai);
2392 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002393 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002394 // Log default network disconnection before required book-keeping.
2395 // Let rematchAllNetworksAndRequests() below record a new default network event
2396 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2397 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002398 long now = SystemClock.elapsedRealtime();
2399 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002400 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002401 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002402 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2403 // by other networks that are already connected. Perhaps that can be done by
2404 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2405 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002406 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002407 mKeepaliveTracker.handleStopAllKeepalives(nai,
2408 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002409 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2410 // Disable wakeup packet monitoring for each interface.
2411 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2412 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002413 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002414 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002415 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002416 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002417 // Remove the NetworkAgent, but don't mark the netId as
2418 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002419 mNetworkForNetId.remove(nai.network.netId);
2420 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002421 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002422 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2423 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002424 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002425 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002426 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002427 sendUpdatedScoreToFactories(request, 0);
2428 }
2429 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002430 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002431 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002432 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002433 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002434 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002435 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002436 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002437 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002438 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002439 if (nai.created) {
2440 // Tell netd to clean up the configuration for this network
2441 // (routing rules, DNS, etc).
2442 // This may be slow as it requires a lot of netd shelling out to ip and
2443 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2444 // after we've rematched networks with requests which should make a potential
2445 // fallback network the default or requested a new network from the
2446 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2447 // long time.
2448 try {
2449 mNetd.removeNetwork(nai.network.netId);
2450 } catch (Exception e) {
2451 loge("Exception removing network: " + e);
2452 }
Erik Klinea24d4592018-01-11 21:07:29 +09002453 mDnsManager.removeNetwork(nai.network);
Paul Jensen62d30802015-06-17 14:42:30 -04002454 }
2455 synchronized (mNetworkForNetId) {
2456 mNetIdInUse.delete(nai.network.netId);
2457 }
2458 } else {
2459 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2460 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002461 }
2462 }
2463
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002464 // If this method proves to be too slow then we can maintain a separate
2465 // pendingIntent => NetworkRequestInfo map.
2466 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2467 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2468 Intent intent = pendingIntent.getIntent();
2469 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2470 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2471 if (existingPendingIntent != null &&
2472 existingPendingIntent.getIntent().filterEquals(intent)) {
2473 return entry.getValue();
2474 }
2475 }
2476 return null;
2477 }
2478
2479 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2480 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2481
2482 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2483 if (existingRequest != null) { // remove the existing request.
2484 if (DBG) log("Replacing " + existingRequest.request + " with "
2485 + nri.request + " because their intents matched.");
2486 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2487 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002488 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002489 }
2490
Erik Klineda4bfa82015-04-30 12:58:40 +09002491 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002492 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002493 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002494 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002495 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002496 if (nri.request.networkCapabilities.hasSignalStrength() &&
2497 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2498 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002499 }
2500 }
2501 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002502 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002503 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002504 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002505 }
2506 }
2507
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002508 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2509 int callingUid) {
2510 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2511 if (nri != null) {
2512 handleReleaseNetworkRequest(nri.request, callingUid);
2513 }
2514 }
2515
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002516 // Determines whether the network is the best (or could become the best, if it validated), for
2517 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2518 // on the value of reason:
2519 //
2520 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2521 // then it should be torn down.
2522 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2523 // then it should be lingered.
2524 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2525 final int numRequests;
2526 switch (reason) {
2527 case TEARDOWN:
2528 numRequests = nai.numRequestNetworkRequests();
2529 break;
2530 case LINGER:
2531 numRequests = nai.numForegroundNetworkRequests();
2532 break;
2533 default:
2534 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2535 return true;
2536 }
2537
2538 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002539 return false;
2540 }
Paul Jensene0988542015-06-25 15:30:08 -04002541 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002542 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2543 // Background requests don't affect lingering.
2544 continue;
2545 }
2546
Paul Jensene0988542015-06-25 15:30:08 -04002547 // If this Network is already the highest scoring Network for a request, or if
2548 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002549 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002550 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002551 // Note that this catches two important cases:
2552 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2553 // is currently satisfying the request. This is desirable when
2554 // cellular ends up validating but WiFi does not.
2555 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002556 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002557 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002558 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002559 nai.getCurrentScoreAsValidated())) {
2560 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002561 }
2562 }
Paul Jensene0988542015-06-25 15:30:08 -04002563 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002564 }
2565
Erik Klineacdd6392016-07-07 16:50:58 +09002566 private NetworkRequestInfo getNriForAppRequest(
2567 NetworkRequest request, int callingUid, String requestedOperation) {
2568 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2569
Robert Greenwalt9258c642014-03-26 16:47:06 -07002570 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002571 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002572 log(String.format("UID %d attempted to %s for unowned request %s",
2573 callingUid, requestedOperation, nri));
2574 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002575 }
Erik Klineacdd6392016-07-07 16:50:58 +09002576 }
2577
2578 return nri;
2579 }
2580
Erik Kline57faba92015-11-25 12:49:38 +09002581 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002582 if (mNetworkRequests.get(nri.request) == null) {
2583 return;
Erik Kline57faba92015-11-25 12:49:38 +09002584 }
Hugo Benichicd952782017-09-20 11:20:14 +09002585 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002586 return;
2587 }
2588 if (VDBG || (DBG && nri.request.isRequest())) {
2589 log("releasing " + nri.request + " (timeout)");
2590 }
2591 handleRemoveNetworkRequest(nri);
2592 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002593 }
2594
Erik Klineacdd6392016-07-07 16:50:58 +09002595 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002596 final NetworkRequestInfo nri =
2597 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2598 if (nri == null) {
2599 return;
Erik Kline57faba92015-11-25 12:49:38 +09002600 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002601 if (VDBG || (DBG && nri.request.isRequest())) {
2602 log("releasing " + nri.request + " (release request)");
2603 }
2604 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002605 }
Erik Klineacdd6392016-07-07 16:50:58 +09002606
Hugo Benichidba33db2017-03-23 22:40:44 +09002607 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002608 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002609 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002610
Erik Klineacdd6392016-07-07 16:50:58 +09002611 synchronized (mUidToNetworkRequestCount) {
2612 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2613 if (requests < 1) {
2614 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2615 nri.mUid);
2616 } else if (requests == 1) {
2617 mUidToNetworkRequestCount.removeAt(
2618 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2619 } else {
2620 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2621 }
2622 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002623
Erik Klineacdd6392016-07-07 16:50:58 +09002624 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2625 if (nri.request.isRequest()) {
2626 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002627 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002628 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002629 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002630 nai.removeRequest(nri.request.requestId);
2631 if (VDBG) {
2632 log(" Removing from current network " + nai.name() +
2633 ", leaving " + nai.numNetworkRequests() + " requests.");
2634 }
2635 // If there are still lingered requests on this network, don't tear it down,
2636 // but resume lingering instead.
2637 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002638 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002639 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2640 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002641 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002642 wasKept = true;
2643 }
Hugo Benichicd952782017-09-20 11:20:14 +09002644 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002645 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2646 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002647 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002648 }
Erik Klineacdd6392016-07-07 16:50:58 +09002649 }
2650
2651 // TODO: remove this code once we know that the Slog.wtf is never hit.
2652 //
2653 // Find all networks that are satisfying this request and remove the request
2654 // from their request lists.
2655 // TODO - it's my understanding that for a request there is only a single
2656 // network satisfying it, so this loop is wasteful
2657 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2658 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2659 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2660 otherNai.name() + ", but mNetworkAgentInfos says " +
2661 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002662 }
2663 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002664
Erik Klineacdd6392016-07-07 16:50:58 +09002665 // Maintain the illusion. When this request arrived, we might have pretended
2666 // that a network connected to serve it, even though the network was already
2667 // connected. Now that this request has gone away, we might have to pretend
2668 // that the network disconnected. LegacyTypeTracker will generate that
2669 // phantom disconnect for this type.
2670 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2671 boolean doRemove = true;
2672 if (wasKept) {
2673 // check if any of the remaining requests for this network are for the
2674 // same legacy type - if so, don't remove the nai
2675 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2676 NetworkRequest otherRequest = nai.requestAt(i);
2677 if (otherRequest.legacyType == nri.request.legacyType &&
2678 otherRequest.isRequest()) {
2679 if (DBG) log(" still have other legacy request - leaving");
2680 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002681 }
2682 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002683 }
2684
Erik Klineacdd6392016-07-07 16:50:58 +09002685 if (doRemove) {
2686 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002687 }
2688 }
Erik Klineacdd6392016-07-07 16:50:58 +09002689
2690 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2691 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2692 nri.request);
2693 }
2694 } else {
2695 // listens don't have a singular affectedNetwork. Check all networks to see
2696 // if this listen request applies and remove it.
2697 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2698 nai.removeRequest(nri.request.requestId);
2699 if (nri.request.networkCapabilities.hasSignalStrength() &&
2700 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2701 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2702 }
2703 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002704 }
2705 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002706
Lorenzo Colitti18660282016-07-04 12:55:44 +09002707 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002708 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2709 enforceConnectivityInternalPermission();
2710 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002711 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002712 }
2713
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002714 @Override
2715 public void setAvoidUnvalidated(Network network) {
2716 enforceConnectivityInternalPermission();
2717 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2718 }
2719
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002720 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2721 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2722 " accept=" + accept + " always=" + always);
2723
2724 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2725 if (nai == null) {
2726 // Nothing to do.
2727 return;
2728 }
2729
2730 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002731 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002732 return;
2733 }
2734
2735 if (!nai.networkMisc.explicitlySelected) {
2736 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2737 }
2738
2739 if (accept != nai.networkMisc.acceptUnvalidated) {
2740 int oldScore = nai.getCurrentScore();
2741 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002742 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002743 sendUpdatedScoreToFactories(nai);
2744 }
2745
2746 if (always) {
2747 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002748 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002749 }
2750
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002751 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002752 // Tell the NetworkAgent to not automatically reconnect to the network.
2753 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2754 // Teardown the nework.
2755 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002756 }
2757
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002758 }
2759
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002760 private void handleSetAvoidUnvalidated(Network network) {
2761 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2762 if (nai == null || nai.lastValidated) {
2763 // Nothing to do. The network either disconnected or revalidated.
2764 return;
2765 }
2766 if (!nai.avoidUnvalidated) {
2767 int oldScore = nai.getCurrentScore();
2768 nai.avoidUnvalidated = true;
2769 rematchAllNetworksAndRequests(nai, oldScore);
2770 sendUpdatedScoreToFactories(nai);
2771 }
2772 }
2773
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002774 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002775 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002776 mHandler.sendMessageDelayed(
2777 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2778 PROMPT_UNVALIDATED_DELAY_MS);
2779 }
2780
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002781 @Override
2782 public void startCaptivePortalApp(Network network) {
2783 enforceConnectivityInternalPermission();
2784 mHandler.post(() -> {
2785 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2786 if (nai == null) return;
2787 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2788 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2789 });
2790 }
2791
Hugo Benichic8e9e122016-09-14 23:23:08 +00002792 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002793 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002794 }
2795
Erik Kline065ab6e2016-10-02 18:02:14 +09002796 private void rematchForAvoidBadWifiUpdate() {
2797 rematchAllNetworksAndRequests(null, 0);
2798 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2799 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2800 sendUpdatedScoreToFactories(nai);
2801 }
2802 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002803 }
2804
Erik Kline065ab6e2016-10-02 18:02:14 +09002805 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002806 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002807 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002808 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002809 if (!configRestrict) {
2810 pw.println("Bad Wi-Fi avoidance: unrestricted");
2811 return;
2812 }
2813
2814 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2815 pw.increaseIndent();
2816 pw.println("Config restrict: " + configRestrict);
2817
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002818 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002819 String description;
2820 // Can't use a switch statement because strings are legal case labels, but null is not.
2821 if ("0".equals(value)) {
2822 description = "get stuck";
2823 } else if (value == null) {
2824 description = "prompt";
2825 } else if ("1".equals(value)) {
2826 description = "avoid";
2827 } else {
2828 description = value + " (?)";
2829 }
2830 pw.println("User setting: " + description);
2831 pw.println("Network overrides:");
2832 pw.increaseIndent();
2833 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2834 if (nai.avoidUnvalidated) {
2835 pw.println(nai.name());
2836 }
2837 }
2838 pw.decreaseIndent();
2839 pw.decreaseIndent();
2840 }
2841
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002842 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2843 final String action;
2844 switch (type) {
2845 case NO_INTERNET:
2846 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2847 break;
2848 case LOST_INTERNET:
2849 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2850 break;
2851 default:
2852 Slog.wtf(TAG, "Unknown notification type " + type);
2853 return;
2854 }
2855
2856 Intent intent = new Intent(action);
2857 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2858 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2859 intent.setClassName("com.android.settings",
2860 "com.android.settings.wifi.WifiNoInternetDialog");
2861
2862 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2863 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2864 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2865 }
2866
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002867 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002868 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002869 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2870
2871 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2872 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002873 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002874 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002875 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2876 return;
2877 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002878 showValidationNotification(nai, NotificationType.NO_INTERNET);
2879 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002880
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002881 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2882 NetworkCapabilities nc = nai.networkCapabilities;
2883 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002884
Erik Kline065ab6e2016-10-02 18:02:14 +09002885 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002886 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002887 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2888 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002889 }
2890
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002891 @Override
2892 public int getMultipathPreference(Network network) {
2893 enforceAccessPermission();
2894
2895 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002896 if (nai != null && nai.networkCapabilities
2897 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002898 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2899 }
2900
2901 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2902 }
2903
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002904 private class InternalHandler extends Handler {
2905 public InternalHandler(Looper looper) {
2906 super(looper);
2907 }
2908
2909 @Override
2910 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002911 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002912 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002913 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002914 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002915 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002916 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002917 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002918 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002919 break;
2920 }
Jason Monkdecd2952013-10-10 14:02:51 -04002921 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002922 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002923 break;
2924 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002925 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002926 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2927 break;
2928 }
2929 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2930 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002931 break;
2932 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002933 case EVENT_REGISTER_NETWORK_AGENT: {
2934 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2935 break;
2936 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002937 case EVENT_REGISTER_NETWORK_REQUEST:
2938 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002939 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002940 break;
2941 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002942 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2943 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002944 handleRegisterNetworkRequestWithIntent(msg);
2945 break;
2946 }
Erik Kline57faba92015-11-25 12:49:38 +09002947 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2948 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2949 handleTimedOutNetworkRequest(nri);
2950 break;
2951 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002952 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2953 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2954 break;
2955 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002956 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002957 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002958 break;
2959 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002960 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002961 Network network = (Network) msg.obj;
2962 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002963 break;
2964 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002965 case EVENT_SET_AVOID_UNVALIDATED: {
2966 handleSetAvoidUnvalidated((Network) msg.obj);
2967 break;
2968 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002969 case EVENT_PROMPT_UNVALIDATED: {
2970 handlePromptUnvalidated((Network) msg.obj);
2971 break;
2972 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002973 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2974 handleMobileDataAlwaysOn();
2975 break;
2976 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002977 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2978 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2979 mKeepaliveTracker.handleStartKeepalive(msg);
2980 break;
2981 }
2982 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2983 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2984 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2985 int slot = msg.arg1;
2986 int reason = msg.arg2;
2987 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2988 break;
2989 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002990 case EVENT_SYSTEM_READY: {
2991 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2992 nai.networkMonitor.systemReady = true;
2993 }
2994 break;
2995 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002996 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002997 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002998 break;
2999 }
Erik Klinea24d4592018-01-11 21:07:29 +09003000 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3001 handlePrivateDnsSettingsChanged();
3002 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003 }
3004 }
3005 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003006
3007 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003008 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003009 public int tether(String iface, String callerPkg) {
3010 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003011 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003012 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003013 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003014 } else {
3015 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3016 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003017 }
3018
3019 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003020 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003021 public int untether(String iface, String callerPkg) {
3022 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003023
3024 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003025 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003026 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003027 } else {
3028 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3029 }
3030 }
3031
3032 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003033 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003034 public int getLastTetherError(String iface) {
3035 enforceTetherAccessPermission();
3036
3037 if (isTetheringSupported()) {
3038 return mTethering.getLastTetherError(iface);
3039 } else {
3040 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3041 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003042 }
3043
3044 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003045 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003046 public String[] getTetherableUsbRegexs() {
3047 enforceTetherAccessPermission();
3048 if (isTetheringSupported()) {
3049 return mTethering.getTetherableUsbRegexs();
3050 } else {
3051 return new String[0];
3052 }
3053 }
3054
Lorenzo Colitti18660282016-07-04 12:55:44 +09003055 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003056 public String[] getTetherableWifiRegexs() {
3057 enforceTetherAccessPermission();
3058 if (isTetheringSupported()) {
3059 return mTethering.getTetherableWifiRegexs();
3060 } else {
3061 return new String[0];
3062 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003063 }
3064
Lorenzo Colitti18660282016-07-04 12:55:44 +09003065 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003066 public String[] getTetherableBluetoothRegexs() {
3067 enforceTetherAccessPermission();
3068 if (isTetheringSupported()) {
3069 return mTethering.getTetherableBluetoothRegexs();
3070 } else {
3071 return new String[0];
3072 }
3073 }
3074
Lorenzo Colitti18660282016-07-04 12:55:44 +09003075 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003076 public int setUsbTethering(boolean enable, String callerPkg) {
3077 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003078 if (isTetheringSupported()) {
3079 return mTethering.setUsbTethering(enable);
3080 } else {
3081 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3082 }
3083 }
3084
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003085 // TODO - move iface listing, queries, etc to new module
3086 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003087 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003088 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003089 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003090 return mTethering.getTetherableIfaces();
3091 }
3092
Lorenzo Colitti18660282016-07-04 12:55:44 +09003093 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003094 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003095 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003096 return mTethering.getTetheredIfaces();
3097 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003098
Lorenzo Colitti18660282016-07-04 12:55:44 +09003099 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003100 public String[] getTetheringErroredIfaces() {
3101 enforceTetherAccessPermission();
3102 return mTethering.getErroredIfaces();
3103 }
3104
Lorenzo Colitti18660282016-07-04 12:55:44 +09003105 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003106 public String[] getTetheredDhcpRanges() {
3107 enforceConnectivityInternalPermission();
3108 return mTethering.getTetheredDhcpRanges();
3109 }
3110
Udam Sainic3b640c2017-06-07 12:06:28 -07003111 @Override
3112 public boolean isTetheringSupported(String callerPkg) {
3113 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3114 return isTetheringSupported();
3115 }
3116
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003117 // if ro.tether.denied = true we default to no tethering
3118 // gservices could set the secure setting to 1 though to enable it on a build where it
3119 // had previously been turned off.
Udam Sainic3b640c2017-06-07 12:06:28 -07003120 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003121 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3122 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3123 Settings.Global.TETHER_SUPPORTED, defaultVal));
3124 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003125 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003126
3127 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3128 boolean adminUser = false;
3129 final long token = Binder.clearCallingIdentity();
3130 try {
3131 adminUser = mUserManager.isAdminUser();
3132 } finally {
3133 Binder.restoreCallingIdentity(token);
3134 }
3135
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003136 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003137 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003138
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003139 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003140 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3141 String callerPkg) {
3142 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003143 if (!isTetheringSupported()) {
3144 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3145 return;
3146 }
3147 mTethering.startTethering(type, receiver, showProvisioningUi);
3148 }
3149
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003150 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003151 public void stopTethering(int type, String callerPkg) {
3152 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003153 mTethering.stopTethering(type);
3154 }
3155
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003156 // Called when we lose the default network and have no replacement yet.
3157 // This will automatically be cleared after X seconds or a new default network
3158 // becomes CONNECTED, whichever happens first. The timer is started by the
3159 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003160 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003161 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003162 if (mNetTransitionWakeLock.isHeld()) {
3163 return;
3164 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003165 mNetTransitionWakeLock.acquire();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003166 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3167 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003168 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003169 mWakelockLogs.log("ACQUIRE for " + forWhom);
3170 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3171 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003172 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003173
Hugo Benichi4c31b342017-03-30 23:18:10 +09003174 // Called when we gain a new default network to release the network transition wakelock in a
3175 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3176 // message is cancelled.
3177 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003178 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003179 if (!mNetTransitionWakeLock.isHeld()) {
3180 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003181 }
3182 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003183 // Cancel self timeout on wakelock hold.
3184 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3185 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3186 mHandler.sendMessageDelayed(msg, 1000);
3187 }
3188
3189 // Called when either message of ensureNetworkTransitionWakelock or
3190 // scheduleReleaseNetworkTransitionWakelock is processed.
3191 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3192 String event = eventName(eventId);
3193 synchronized (this) {
3194 if (!mNetTransitionWakeLock.isHeld()) {
3195 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3196 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3197 return;
3198 }
3199 mNetTransitionWakeLock.release();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003200 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3201 mTotalWakelockDurationMs += lockDuration;
3202 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3203 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003204 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003205 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003206 }
3207
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003208 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003209 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003210 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003211 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003212 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003213 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003214 }
3215
Lorenzo Colitti18660282016-07-04 12:55:44 +09003216 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003217 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003218 enforceAccessPermission();
3219 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003220 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003221 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003222 mHandler.sendMessage(
3223 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3224 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003225
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003226 private void handleReportNetworkConnectivity(
3227 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003228 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003229 if (network == null) {
3230 nai = getDefaultNetwork();
3231 } else {
3232 nai = getNetworkAgentInfoForNetwork(network);
3233 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003234 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3235 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3236 return;
3237 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003238 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003239 if (hasConnectivity == nai.lastValidated) {
3240 return;
3241 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003242 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003243 int netid = nai.network.netId;
3244 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003245 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003246 // Validating a network that has not yet connected could result in a call to
3247 // rematchNetworkAndRequests() which is not meant to work on such networks.
3248 if (!nai.everConnected) {
3249 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003250 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003251 LinkProperties lp = getLinkProperties(nai);
3252 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3253 return;
3254 }
3255 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003256 }
3257
Paul Jensencee9b512015-05-06 07:32:40 -04003258 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003259 // this information is already available as a world read/writable jvm property
3260 // so this API change wouldn't have a benifit. It also breaks the passing
3261 // of proxy info to all the JVMs.
3262 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003263 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003264 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003265 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3266 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003267 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003268 }
3269
Lorenzo Colitti18660282016-07-04 12:55:44 +09003270 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003271 public ProxyInfo getProxyForNetwork(Network network) {
3272 if (network == null) return getDefaultProxy();
3273 final ProxyInfo globalProxy = getGlobalProxy();
3274 if (globalProxy != null) return globalProxy;
3275 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3276 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3277 // caller may not have.
3278 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3279 if (nai == null) return null;
3280 synchronized (nai) {
3281 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3282 if (proxyInfo == null) return null;
3283 return new ProxyInfo(proxyInfo);
3284 }
3285 }
3286
Paul Jensene0bef712014-12-10 15:12:18 -05003287 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3288 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3289 // proxy is null then there is no proxy in place).
3290 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3291 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3292 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3293 proxy = null;
3294 }
3295 return proxy;
3296 }
3297
3298 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3299 // better for determining if a new proxy broadcast is necessary:
3300 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3301 // avoid unnecessary broadcasts.
3302 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3303 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3304 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3305 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3306 // all set.
3307 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3308 a = canonicalizeProxyInfo(a);
3309 b = canonicalizeProxyInfo(b);
3310 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3311 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3312 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3313 }
3314
Jason Monk207900c2014-04-25 15:00:09 -04003315 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003316 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003317
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003318 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003319 if (proxyProperties == mGlobalProxy) return;
3320 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3321 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3322
3323 String host = "";
3324 int port = 0;
3325 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003326 String pacFileUrl = "";
3327 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003328 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003329 if (!proxyProperties.isValid()) {
3330 if (DBG)
3331 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3332 return;
3333 }
Jason Monk207900c2014-04-25 15:00:09 -04003334 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003335 host = mGlobalProxy.getHost();
3336 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003337 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003338 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003339 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003340 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003341 } else {
3342 mGlobalProxy = null;
3343 }
3344 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003345 final long token = Binder.clearCallingIdentity();
3346 try {
3347 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3348 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3349 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3350 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003351 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003352 } finally {
3353 Binder.restoreCallingIdentity(token);
3354 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003355
Jason Monkcf0f97a2014-10-02 15:39:38 -04003356 if (mGlobalProxy == null) {
3357 proxyProperties = mDefaultProxy;
3358 }
3359 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003360 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003361 }
3362
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003363 private void loadGlobalProxy() {
3364 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003365 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3366 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3367 String exclList = Settings.Global.getString(res,
3368 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003369 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3370 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003371 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003372 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003373 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003374 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003375 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003376 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003377 if (!proxyProperties.isValid()) {
3378 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3379 return;
3380 }
3381
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003382 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003383 mGlobalProxy = proxyProperties;
3384 }
3385 }
3386 }
3387
Jason Monk207900c2014-04-25 15:00:09 -04003388 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003389 // this information is already available as a world read/writable jvm property
3390 // so this API change wouldn't have a benifit. It also breaks the passing
3391 // of proxy info to all the JVMs.
3392 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003393 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003394 return mGlobalProxy;
3395 }
3396 }
3397
Jason Monk207900c2014-04-25 15:00:09 -04003398 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003399 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003400 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003401 proxy = null;
3402 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003403 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003404 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003405 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003406 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003407 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3408 return;
3409 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003410
3411 // This call could be coming from the PacManager, containing the port of the local
3412 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3413 // global (to get the correct local port), and send a broadcast.
3414 // TODO: Switch PacManager to have its own message to send back rather than
3415 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003416 if ((mGlobalProxy != null) && (proxy != null)
3417 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003418 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3419 mGlobalProxy = proxy;
3420 sendProxyBroadcast(mGlobalProxy);
3421 return;
3422 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003423 mDefaultProxy = proxy;
3424
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003425 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003426 if (!mDefaultProxyDisabled) {
3427 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003428 }
3429 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003430 }
3431
Paul Jensene0bef712014-12-10 15:12:18 -05003432 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3433 // This method gets called when any network changes proxy, but the broadcast only ever contains
3434 // the default proxy (even if it hasn't changed).
3435 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3436 // world where an app might be bound to a non-default network.
3437 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3438 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3439 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3440
3441 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3442 sendProxyBroadcast(getDefaultProxy());
3443 }
3444 }
3445
Robert Greenwalt434203a2010-10-11 16:00:27 -07003446 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003447 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3448 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003449 if (!TextUtils.isEmpty(proxy)) {
3450 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003451 if (data.length == 0) {
3452 return;
3453 }
3454
Robert Greenwalt434203a2010-10-11 16:00:27 -07003455 String proxyHost = data[0];
3456 int proxyPort = 8080;
3457 if (data.length > 1) {
3458 try {
3459 proxyPort = Integer.parseInt(data[1]);
3460 } catch (NumberFormatException e) {
3461 return;
3462 }
3463 }
Jason Monk207900c2014-04-25 15:00:09 -04003464 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003465 setGlobalProxy(p);
3466 }
3467 }
3468
Jason Monk207900c2014-04-25 15:00:09 -04003469 private void sendProxyBroadcast(ProxyInfo proxy) {
3470 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003471 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003472 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003473 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003474 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3475 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003476 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003477 final long ident = Binder.clearCallingIdentity();
3478 try {
3479 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3480 } finally {
3481 Binder.restoreCallingIdentity(ident);
3482 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003483 }
3484
3485 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003486 final private HashMap<Uri, Integer> mUriEventMap;
3487 final private Context mContext;
3488 final private Handler mHandler;
3489
3490 SettingsObserver(Context context, Handler handler) {
3491 super(null);
3492 mUriEventMap = new HashMap<Uri, Integer>();
3493 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003494 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003495 }
3496
Erik Klineda4bfa82015-04-30 12:58:40 +09003497 void observe(Uri uri, int what) {
3498 mUriEventMap.put(uri, what);
3499 final ContentResolver resolver = mContext.getContentResolver();
3500 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003501 }
3502
3503 @Override
3504 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003505 Slog.wtf(TAG, "Should never be reached.");
3506 }
3507
3508 @Override
3509 public void onChange(boolean selfChange, Uri uri) {
3510 final Integer what = mUriEventMap.get(uri);
3511 if (what != null) {
3512 mHandler.obtainMessage(what.intValue()).sendToTarget();
3513 } else {
3514 loge("No matching event to send for URI=" + uri);
3515 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003516 }
3517 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003518
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003519 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003520 Slog.d(TAG, s);
3521 }
3522
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003523 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003524 Slog.e(TAG, s);
3525 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003526
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003527 private static void loge(String s, Throwable t) {
3528 Slog.e(TAG, s, t);
3529 }
3530
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003531 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003532 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003533 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3534 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3535 *
3536 * @param oldPackage Package name of the application which currently controls VPN, which will
3537 * be replaced. If there is no such application, this should should either be
3538 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3539 * @param newPackage Package name of the application which should gain control of VPN, or
3540 * {@code null} to disable.
3541 * @param userId User for whom to prepare the new VPN.
3542 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003543 * @hide
3544 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003545 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003546 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3547 int userId) {
3548 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003549
Hugo Benichi20035e02017-04-26 14:53:28 +09003550 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003551 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003552 Vpn vpn = mVpns.get(userId);
3553 if (vpn != null) {
3554 return vpn.prepare(oldPackage, newPackage);
3555 } else {
3556 return false;
3557 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003558 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003559 }
3560
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003561 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003562 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3563 * This method is used by system-privileged apps.
3564 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3565 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3566 *
3567 * @param packageName The package for which authorization state should change.
3568 * @param userId User for whom {@code packageName} is installed.
3569 * @param authorized {@code true} if this app should be able to start a VPN connection without
3570 * explicit user approval, {@code false} if not.
3571 *
Jeff Davidson05542602014-08-11 14:07:27 -07003572 * @hide
3573 */
3574 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003575 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3576 enforceCrossUserPermission(userId);
3577
Hugo Benichi20035e02017-04-26 14:53:28 +09003578 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003579 Vpn vpn = mVpns.get(userId);
3580 if (vpn != null) {
3581 vpn.setPackageAuthorization(packageName, authorized);
3582 }
Jeff Davidson05542602014-08-11 14:07:27 -07003583 }
3584 }
3585
3586 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003587 * Configure a TUN interface and return its file descriptor. Parameters
3588 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003589 * and not available in ConnectivityManager. Permissions are checked in
3590 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003591 * @hide
3592 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003593 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003594 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003595 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003596 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003597 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003598 return mVpns.get(user).establish(config);
3599 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003600 }
3601
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003602 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003603 * Start legacy VPN, controlling native daemons as needed. Creates a
3604 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003605 */
3606 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003607 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003608 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003609 final LinkProperties egress = getActiveLinkProperties();
3610 if (egress == null) {
3611 throw new IllegalStateException("Missing active network connection");
3612 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003613 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003614 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003615 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3616 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003617 }
3618
3619 /**
3620 * Return the information of the ongoing legacy VPN. This method is used
3621 * by VpnSettings and not available in ConnectivityManager. Permissions
3622 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003623 */
3624 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003625 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3626 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003627
Hugo Benichi20035e02017-04-26 14:53:28 +09003628 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003629 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003630 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003631 }
3632
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003633 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003634 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3635 * and not available in ConnectivityManager.
3636 */
3637 @Override
3638 public VpnInfo[] getAllVpnInfo() {
3639 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003640 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003641 if (mLockdownEnabled) {
3642 return new VpnInfo[0];
3643 }
3644
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003645 List<VpnInfo> infoList = new ArrayList<>();
3646 for (int i = 0; i < mVpns.size(); i++) {
3647 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3648 if (info != null) {
3649 infoList.add(info);
3650 }
3651 }
3652 return infoList.toArray(new VpnInfo[infoList.size()]);
3653 }
3654 }
3655
3656 /**
3657 * @return VPN information for accounting, or null if we can't retrieve all required
3658 * information, e.g primary underlying iface.
3659 */
3660 @Nullable
3661 private VpnInfo createVpnInfo(Vpn vpn) {
3662 VpnInfo info = vpn.getVpnInfo();
3663 if (info == null) {
3664 return null;
3665 }
3666 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3667 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3668 // the underlyingNetworks list.
3669 if (underlyingNetworks == null) {
3670 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3671 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3672 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3673 }
3674 } else if (underlyingNetworks.length > 0) {
3675 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3676 if (linkProperties != null) {
3677 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3678 }
3679 }
3680 return info.primaryUnderlyingIface == null ? null : info;
3681 }
3682
3683 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003684 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3685 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003686 * Permissions are checked in Vpn class.
3687 * @hide
3688 */
3689 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003690 public VpnConfig getVpnConfig(int userId) {
3691 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003692 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003693 Vpn vpn = mVpns.get(userId);
3694 if (vpn != null) {
3695 return vpn.getVpnConfig();
3696 } else {
3697 return null;
3698 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003699 }
3700 }
3701
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003702 @Override
3703 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003704 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3705 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3706 return false;
3707 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003708
Hugo Benichi69744342017-11-27 10:57:16 +09003709 synchronized (mVpns) {
3710 // Tear down existing lockdown if profile was removed
3711 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3712 if (mLockdownEnabled) {
3713 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3714 if (profileTag == null) {
3715 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3716 return false;
3717 }
3718 String profileName = new String(profileTag);
3719 final VpnProfile profile = VpnProfile.decode(
3720 profileName, mKeyStore.get(Credentials.VPN + profileName));
3721 if (profile == null) {
3722 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3723 setLockdownTracker(null);
3724 return true;
3725 }
3726 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003727 Vpn vpn = mVpns.get(user);
3728 if (vpn == null) {
3729 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3730 return false;
3731 }
3732 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003733 } else {
3734 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003735 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003736 }
3737
3738 return true;
3739 }
3740
3741 /**
3742 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3743 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3744 */
Hugo Benichi69744342017-11-27 10:57:16 +09003745 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003746 private void setLockdownTracker(LockdownVpnTracker tracker) {
3747 // Shutdown any existing tracker
3748 final LockdownVpnTracker existing = mLockdownTracker;
3749 mLockdownTracker = null;
3750 if (existing != null) {
3751 existing.shutdown();
3752 }
3753
Robin Leec3736bc2017-03-10 16:19:54 +00003754 if (tracker != null) {
3755 mLockdownTracker = tracker;
3756 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003757 }
3758 }
3759
Hugo Benichi69744342017-11-27 10:57:16 +09003760 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003761 private void throwIfLockdownEnabled() {
3762 if (mLockdownEnabled) {
3763 throw new IllegalStateException("Unavailable in lockdown mode");
3764 }
3765 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003766
Robin Lee244ce8e2016-01-05 18:03:46 +00003767 /**
Robin Lee17e61832016-05-09 13:46:28 +01003768 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3769 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003770 *
Robin Lee17e61832016-05-09 13:46:28 +01003771 * @return {@code true} if the service was started, the service was already connected, or there
3772 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003773 */
Robin Lee17e61832016-05-09 13:46:28 +01003774 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003775 synchronized (mVpns) {
3776 Vpn vpn = mVpns.get(userId);
3777 if (vpn == null) {
3778 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3779 // exists already.
3780 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3781 return false;
3782 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003783
Robin Lee812800c2016-05-13 15:38:08 +01003784 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003785 }
3786 }
3787
3788 @Override
Charles Hea0a87e82017-05-15 17:07:18 +01003789 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3790 enforceSettingsPermission();
3791 enforceCrossUserPermission(userId);
3792
3793 synchronized (mVpns) {
3794 Vpn vpn = mVpns.get(userId);
3795 if (vpn == null) {
3796 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3797 return false;
3798 }
3799 return vpn.isAlwaysOnPackageSupported(packageName);
3800 }
3801 }
3802
3803 @Override
Robin Leedc679712016-05-03 13:23:03 +01003804 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003805 enforceConnectivityInternalPermission();
3806 enforceCrossUserPermission(userId);
3807
Robin Lee244ce8e2016-01-05 18:03:46 +00003808 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003809 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3810 if (LockdownVpnTracker.isEnabled()) {
3811 return false;
3812 }
3813
Robin Lee244ce8e2016-01-05 18:03:46 +00003814 Vpn vpn = mVpns.get(userId);
3815 if (vpn == null) {
3816 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3817 return false;
3818 }
Robin Lee17e61832016-05-09 13:46:28 +01003819 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003820 return false;
3821 }
Robin Lee17e61832016-05-09 13:46:28 +01003822 if (!startAlwaysOnVpn(userId)) {
3823 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003824 return false;
3825 }
3826 }
3827 return true;
3828 }
3829
3830 @Override
3831 public String getAlwaysOnVpnPackage(int userId) {
3832 enforceConnectivityInternalPermission();
3833 enforceCrossUserPermission(userId);
3834
3835 synchronized (mVpns) {
3836 Vpn vpn = mVpns.get(userId);
3837 if (vpn == null) {
3838 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3839 return null;
3840 }
3841 return vpn.getAlwaysOnPackage();
3842 }
3843 }
3844
Wink Savilleab9321d2013-06-29 21:10:57 -07003845 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003846 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003847 // TODO: Remove? Any reason to trigger a provisioning check?
3848 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003849 }
3850
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003851 /** Location to an updatable file listing carrier provisioning urls.
3852 * An example:
3853 *
3854 * <?xml version="1.0" encoding="utf-8"?>
3855 * <provisioningUrls>
3856 * <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 -07003857 * </provisioningUrls>
3858 */
3859 private static final String PROVISIONING_URL_PATH =
3860 "/data/misc/radio/provisioning_urls.xml";
3861 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003862
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003863 /** XML tag for root element. */
3864 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3865 /** XML tag for individual url */
3866 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003867 /** XML attribute for mcc */
3868 private static final String ATTR_MCC = "mcc";
3869 /** XML attribute for mnc */
3870 private static final String ATTR_MNC = "mnc";
3871
Paul Jensen434dde82015-06-11 09:43:30 -04003872 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003873 FileReader fileReader = null;
3874 XmlPullParser parser = null;
3875 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003876
3877 try {
3878 fileReader = new FileReader(mProvisioningUrlFile);
3879 parser = Xml.newPullParser();
3880 parser.setInput(fileReader);
3881 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3882
3883 while (true) {
3884 XmlUtils.nextElement(parser);
3885
3886 String element = parser.getName();
3887 if (element == null) break;
3888
Paul Jensen434dde82015-06-11 09:43:30 -04003889 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003890 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3891 try {
3892 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3893 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3894 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3895 parser.next();
3896 if (parser.getEventType() == XmlPullParser.TEXT) {
3897 return parser.getText();
3898 }
3899 }
3900 }
3901 } catch (NumberFormatException e) {
3902 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3903 }
3904 }
3905 }
3906 return null;
3907 } catch (FileNotFoundException e) {
3908 loge("Carrier Provisioning Urls file not found");
3909 } catch (XmlPullParserException e) {
3910 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3911 } catch (IOException e) {
3912 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3913 } finally {
3914 if (fileReader != null) {
3915 try {
3916 fileReader.close();
3917 } catch (IOException e) {}
3918 }
3919 }
3920 return null;
3921 }
3922
Wink Saville42d4f082013-07-20 20:31:59 -07003923 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003924 public String getMobileProvisioningUrl() {
3925 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003926 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003927 if (TextUtils.isEmpty(url)) {
3928 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003929 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003930 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003931 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003932 }
Wink Saville8cf35602013-07-10 23:00:07 -07003933 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003934 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003935 String phoneNumber = mTelephonyManager.getLine1Number();
3936 if (TextUtils.isEmpty(phoneNumber)) {
3937 phoneNumber = "0000000000";
3938 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003939 url = String.format(url,
3940 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3941 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003942 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003943 }
3944
Wink Savilleab9321d2013-06-29 21:10:57 -07003945 return url;
3946 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003947
Wink Saville948282b2013-08-29 08:55:16 -07003948 @Override
3949 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003950 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003951 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003952 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3953 return;
3954 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003955 final long ident = Binder.clearCallingIdentity();
3956 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003957 // Concatenate the range of types onto the range of NetIDs.
3958 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3959 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003960 } finally {
3961 Binder.restoreCallingIdentity(ident);
3962 }
Wink Saville948282b2013-08-29 08:55:16 -07003963 }
Wink Saville7788c612013-08-29 14:57:08 -07003964
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003965 @Override
3966 public void setAirplaneMode(boolean enable) {
3967 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003968 final long ident = Binder.clearCallingIdentity();
3969 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003970 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003971 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003972 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3973 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003974 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003975 } finally {
3976 Binder.restoreCallingIdentity(ident);
3977 }
3978 }
3979
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003980 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003981 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003982 Vpn userVpn = mVpns.get(userId);
3983 if (userVpn != null) {
3984 loge("Starting user already has a VPN");
3985 return;
3986 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003987 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003988 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09003989 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3990 updateLockdownVpn();
3991 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003992 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003993 }
3994
3995 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003996 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003997 Vpn userVpn = mVpns.get(userId);
3998 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003999 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004000 return;
4001 }
Robin Lee17e61832016-05-09 13:46:28 +01004002 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004003 mVpns.delete(userId);
4004 }
4005 }
4006
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004007 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004008 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004009 final int vpnsSize = mVpns.size();
4010 for (int i = 0; i < vpnsSize; i++) {
4011 Vpn vpn = mVpns.valueAt(i);
4012 vpn.onUserAdded(userId);
4013 }
4014 }
4015 }
4016
4017 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004018 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004019 final int vpnsSize = mVpns.size();
4020 for (int i = 0; i < vpnsSize; i++) {
4021 Vpn vpn = mVpns.valueAt(i);
4022 vpn.onUserRemoved(userId);
4023 }
4024 }
4025 }
4026
Robin Lee89e7a692016-02-29 14:38:17 +00004027 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004028 synchronized (mVpns) {
4029 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4030 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4031 updateLockdownVpn();
4032 } else {
4033 startAlwaysOnVpn(userId);
4034 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004035 }
4036 }
4037
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004038 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4039 @Override
4040 public void onReceive(Context context, Intent intent) {
4041 final String action = intent.getAction();
4042 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4043 if (userId == UserHandle.USER_NULL) return;
4044
Robin Lee323f29d2016-05-04 16:38:06 +01004045 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004046 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004047 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004048 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004049 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4050 onUserAdded(userId);
4051 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4052 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004053 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4054 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004055 }
4056 }
4057 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004058
Robin Lee95204e02017-01-27 11:59:22 +00004059 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4060 @Override
4061 public void onReceive(Context context, Intent intent) {
4062 // Try creating lockdown tracker, since user present usually means
4063 // unlocked keystore.
4064 updateLockdownVpn();
4065 mContext.unregisterReceiver(this);
4066 }
4067 };
4068
Robert Greenwalta67be032014-05-16 15:49:14 -07004069 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4070 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004071 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4072 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004073
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004074 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4075 // Map from UID to number of NetworkRequests that UID has filed.
4076 @GuardedBy("mUidToNetworkRequestCount")
4077 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4078
Robert Greenwalta67be032014-05-16 15:49:14 -07004079 private static class NetworkFactoryInfo {
4080 public final String name;
4081 public final Messenger messenger;
4082 public final AsyncChannel asyncChannel;
4083
4084 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4085 this.name = name;
4086 this.messenger = messenger;
4087 this.asyncChannel = asyncChannel;
4088 }
4089 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004090
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004091 private void ensureNetworkRequestHasType(NetworkRequest request) {
4092 if (request.type == NetworkRequest.Type.NONE) {
4093 throw new IllegalArgumentException(
4094 "All NetworkRequests in ConnectivityService must have a type");
4095 }
4096 }
4097
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004098 /**
4099 * Tracks info about the requester.
4100 * Also used to notice when the calling process dies so we can self-expire
4101 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004102 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004103 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004104 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004105 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004106 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004107 final int mPid;
4108 final int mUid;
4109 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004110
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004111 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004112 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004113 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004114 mPendingIntent = pi;
4115 messenger = null;
4116 mBinder = null;
4117 mPid = getCallingPid();
4118 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004119 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004120 }
4121
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004122 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004123 super();
4124 messenger = m;
4125 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004126 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004127 mBinder = binder;
4128 mPid = getCallingPid();
4129 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004130 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004131 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004132
4133 try {
4134 mBinder.linkToDeath(this, 0);
4135 } catch (RemoteException e) {
4136 binderDied();
4137 }
4138 }
4139
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004140 private void enforceRequestCountLimit() {
4141 synchronized (mUidToNetworkRequestCount) {
4142 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4143 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004144 throw new ServiceSpecificException(
4145 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004146 }
4147 mUidToNetworkRequestCount.put(mUid, networkRequests);
4148 }
4149 }
4150
Robert Greenwalt9258c642014-03-26 16:47:06 -07004151 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004152 if (mBinder != null) {
4153 mBinder.unlinkToDeath(this, 0);
4154 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004155 }
4156
4157 public void binderDied() {
4158 log("ConnectivityService NetworkRequestInfo binderDied(" +
4159 request + ", " + mBinder + ")");
4160 releaseNetworkRequest(request);
4161 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004162
4163 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004164 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004165 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004166 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004167 }
4168
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004169 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4170 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4171 if (badCapability != null) {
4172 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004173 }
4174 }
4175
Erik Kline9d598e12015-07-13 16:37:51 +09004176 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004177 final SortedSet<Integer> thresholds = new TreeSet();
4178 synchronized (nai) {
4179 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4180 if (nri.request.networkCapabilities.hasSignalStrength() &&
4181 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4182 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4183 }
4184 }
4185 }
Erik Kline9d598e12015-07-13 16:37:51 +09004186 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004187 }
4188
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004189 private void updateSignalStrengthThresholds(
4190 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4191 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004192 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004193 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4194
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004195 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004196 String detail;
4197 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4198 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4199 } else {
4200 detail = reason;
4201 }
4202 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4203 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4204 }
4205
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004206 nai.asyncChannel.sendMessage(
4207 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004208 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004209 }
4210
Etan Cohen859748f2017-04-03 17:42:34 -07004211 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4212 if (nc == null) {
4213 return;
4214 }
4215 NetworkSpecifier ns = nc.getNetworkSpecifier();
4216 if (ns == null) {
4217 return;
4218 }
4219 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4220 ns.assertValidFromUid(Binder.getCallingUid());
4221 }
4222
Robert Greenwalt9258c642014-03-26 16:47:06 -07004223 @Override
4224 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004225 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004226 final NetworkRequest.Type type = (networkCapabilities == null)
4227 ? NetworkRequest.Type.TRACK_DEFAULT
4228 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004229 // If the requested networkCapabilities is null, take them instead from
4230 // the default network request. This allows callers to keep track of
4231 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004232 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004233 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004234 networkCapabilities.removeCapability(NET_CAPABILITY_NOT_VPN);
Erik Klinea2d29402016-03-16 15:31:39 +09004235 enforceAccessPermission();
4236 } else {
4237 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4238 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004239 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4240 // of the app when the request is filed, but we never change the request if the app
4241 // changes network state. http://b/29964605
4242 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004243 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004244 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004245 // Set the UID range for this request to the single UID of the requester, or to an empty
4246 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004247 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4248 // are no visible methods to set the UIDs, an app could use reflection to try and get
4249 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004250 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004251
Etan Cohenba07c8c2017-02-05 10:42:27 -08004252 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004253 throw new IllegalArgumentException("Bad timeout specified");
4254 }
Etan Cohen859748f2017-04-03 17:42:34 -07004255 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004256
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004257 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004258 nextNetworkRequestId(), type);
4259 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004260 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004261
4262 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004263 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004264 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004265 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004266 }
4267 return networkRequest;
4268 }
4269
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004270 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004271 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004272 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004273 } else {
4274 enforceChangePermission();
4275 }
4276 }
4277
fenglub15e72b2015-03-20 11:29:56 -07004278 @Override
fengludb571472015-04-21 17:12:05 -07004279 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004280 enforceAccessPermission();
4281 NetworkAgentInfo nai = null;
4282 if (network == null) {
4283 return false;
4284 }
4285 synchronized (mNetworkForNetId) {
4286 nai = mNetworkForNetId.get(network.netId);
4287 }
4288 if (nai != null) {
4289 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4290 return true;
4291 }
4292 return false;
4293 }
4294
Felipe Lemeee27cab2016-06-20 16:36:29 -07004295 private boolean isSystem(int uid) {
4296 return uid < Process.FIRST_APPLICATION_UID;
4297 }
fenglub15e72b2015-03-20 11:29:56 -07004298
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004299 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004300 final int uid = Binder.getCallingUid();
4301 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004302 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004303 return;
4304 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004305 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4306 // Policy already enforced.
4307 return;
4308 }
4309 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4310 // If UID is restricted, don't allow them to bring up metered APNs.
4311 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004312 }
4313 }
4314
Robert Greenwalt9258c642014-03-26 16:47:06 -07004315 @Override
4316 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4317 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004318 checkNotNull(operation, "PendingIntent cannot be null.");
4319 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4320 enforceNetworkRequestPermissions(networkCapabilities);
4321 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004322 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004323 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004324 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004325
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004326 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004327 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4328 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004329 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004330 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4331 nri));
4332 return networkRequest;
4333 }
4334
Jeremy Joslin79294842014-12-03 17:15:28 -08004335 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4336 mHandler.sendMessageDelayed(
4337 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4338 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4339 }
4340
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004341 @Override
4342 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004343 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004344 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4345 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004346 }
4347
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004348 // In order to implement the compatibility measure for pre-M apps that call
4349 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4350 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4351 // This ensures it has permission to do so.
4352 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4353 if (nc == null) {
4354 return false;
4355 }
4356 int[] transportTypes = nc.getTransportTypes();
4357 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4358 return false;
4359 }
4360 try {
4361 mContext.enforceCallingOrSelfPermission(
4362 android.Manifest.permission.ACCESS_WIFI_STATE,
4363 "ConnectivityService");
4364 } catch (SecurityException e) {
4365 return false;
4366 }
4367 return true;
4368 }
4369
Robert Greenwalt9258c642014-03-26 16:47:06 -07004370 @Override
4371 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4372 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004373 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4374 enforceAccessPermission();
4375 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004376
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004377 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004378 restrictRequestUidsForCaller(nc);
Chalard Jean1d738002018-03-20 19:13:57 +09004379 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4380 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4381 // onLost and onAvailable callbacks when networks move in and out of the background.
4382 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4383 // can't request networks.
4384 restrictBackgroundRequestForCaller(nc);
4385 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004386
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004387 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004388 NetworkRequest.Type.LISTEN);
4389 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004390 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004391
4392 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4393 return networkRequest;
4394 }
4395
4396 @Override
4397 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4398 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004399 checkNotNull(operation, "PendingIntent cannot be null.");
4400 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4401 enforceAccessPermission();
4402 }
Etan Cohen859748f2017-04-03 17:42:34 -07004403 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004404
Chalard Jeandda156a2018-01-10 21:19:32 +09004405 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004406 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004407
4408 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004409 NetworkRequest.Type.LISTEN);
4410 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004411 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004412
4413 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004414 }
4415
Erik Klineacdd6392016-07-07 16:50:58 +09004416 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004417 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004418 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004419 mHandler.sendMessage(mHandler.obtainMessage(
4420 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004421 }
4422
4423 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004424 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004425 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004426 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4427 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004428 }
4429
Robert Greenwalta67be032014-05-16 15:49:14 -07004430 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004431 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004432 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4433 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4434 }
4435
4436 @Override
4437 public void unregisterNetworkFactory(Messenger messenger) {
4438 enforceConnectivityInternalPermission();
4439 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4440 }
4441
4442 private void handleUnregisterNetworkFactory(Messenger messenger) {
4443 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4444 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004445 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004446 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004447 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004448 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004449 }
4450
Robert Greenwalt7b816022014-04-18 15:25:25 -07004451 /**
4452 * NetworkAgentInfo supporting a request by requestId.
4453 * These have already been vetted (their Capabilities satisfy the request)
4454 * and the are the highest scored network available.
4455 * the are keyed off the Requests requestId.
4456 */
Hugo Benichicd952782017-09-20 11:20:14 +09004457 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4458 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004459 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4460 new SparseArray<NetworkAgentInfo>();
4461
Paul Jensen31a94f42015-02-13 14:18:39 -05004462 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4463 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004464 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4465 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004466 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4467 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4468 // there may not be a strict 1:1 correlation between the two.
4469 @GuardedBy("mNetworkForNetId")
4470 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004471
Robert Greenwalt7b816022014-04-18 15:25:25 -07004472 // NetworkAgentInfo keyed off its connecting messenger
4473 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004474 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004475 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4476 new HashMap<Messenger, NetworkAgentInfo>();
4477
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004478 @GuardedBy("mBlockedAppUids")
4479 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4480
Paul Jensen2c311d62014-11-17 12:34:51 -05004481 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004482 private final NetworkRequest mDefaultRequest;
4483
Erik Klineda4bfa82015-04-30 12:58:40 +09004484 // Request used to optionally keep mobile data active even when higher
4485 // priority networks like Wi-Fi are active.
4486 private final NetworkRequest mDefaultMobileDataRequest;
4487
Hugo Benichicd952782017-09-20 11:20:14 +09004488 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4489 synchronized (mNetworkForRequestId) {
4490 return mNetworkForRequestId.get(requestId);
4491 }
4492 }
4493
4494 private void clearNetworkForRequest(int requestId) {
4495 synchronized (mNetworkForRequestId) {
4496 mNetworkForRequestId.remove(requestId);
4497 }
4498 }
4499
4500 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4501 synchronized (mNetworkForRequestId) {
4502 mNetworkForRequestId.put(requestId, nai);
4503 }
4504 }
4505
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004506 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004507 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004508 }
4509
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004510 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004511 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004512 }
4513
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004514 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4515 return nri.request.requestId == mDefaultRequest.requestId;
4516 }
4517
Paul Jensen31a94f42015-02-13 14:18:39 -05004518 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004519 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004520 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004521 enforceConnectivityInternalPermission();
4522
Rubin Xu1bb5c082017-09-05 18:40:49 +01004523 LinkProperties lp = new LinkProperties(linkProperties);
4524 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004525 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4526 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004527 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004528 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004529 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004530 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004531 // Make sure the network capabilities reflect what the agent info says.
4532 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004533 synchronized (this) {
4534 nai.networkMonitor.systemReady = mSystemReady;
4535 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004536 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4537 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004538 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004539 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004540 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004541 }
4542
Erik Klinee5dac902018-03-04 21:01:01 +09004543 private void handleRegisterNetworkAgent(NetworkAgentInfo nai) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004544 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09004545 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004546 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09004547 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004548 }
Erik Klinee5dac902018-03-04 21:01:01 +09004549 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
4550 NetworkInfo networkInfo = nai.networkInfo;
4551 nai.networkInfo = null;
4552 updateNetworkInfo(nai, networkInfo);
4553 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004554 }
4555
4556 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4557 LinkProperties newLp = networkAgent.linkProperties;
4558 int netId = networkAgent.network.netId;
4559
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004560 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4561 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004562 if (networkAgent.clatd != null) {
4563 networkAgent.clatd.fixupLinkProperties(oldLp);
4564 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004565
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004566 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004567 updateMtu(newLp, oldLp);
4568 // TODO - figure out what to do for clat
4569// for (LinkProperties lp : newLp.getStackedLinks()) {
4570// updateMtu(lp, null);
4571// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004572 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004573
Erik Kline94887872016-04-05 13:30:49 +09004574 updateRoutes(newLp, oldLp, netId);
4575 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004576
Hugo Benichib577d652017-06-27 15:13:20 +09004577 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004578 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004579 if (isDefaultNetwork(networkAgent)) {
4580 handleApplyDefaultProxy(newLp.getHttpProxy());
4581 } else {
4582 updateProxy(newLp, oldLp, networkAgent);
4583 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004584 // TODO - move this check to cover the whole function
4585 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004586 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004587 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4588 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004589
4590 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004591 }
4592
Joel Scherpelz668370b2017-06-08 15:35:21 +09004593 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004594 // Marks are only available on WiFi interaces. Checking for
4595 // marks on unsupported interfaces is harmless.
4596 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4597 return;
4598 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004599
Joel Scherpelz668370b2017-06-08 15:35:21 +09004600 int mark = mContext.getResources().getInteger(
4601 com.android.internal.R.integer.config_networkWakeupPacketMark);
4602 int mask = mContext.getResources().getInteger(
4603 com.android.internal.R.integer.config_networkWakeupPacketMask);
4604
4605 // Mask/mark of zero will not detect anything interesting.
4606 // Don't install rules unless both values are nonzero.
4607 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004608 return;
4609 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004610
4611 final String prefix = "iface:" + iface;
4612 try {
4613 if (add) {
4614 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4615 } else {
4616 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4617 }
4618 } catch (Exception e) {
4619 loge("Exception modifying wakeup packet monitoring: " + e);
4620 }
4621
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004622 }
4623
4624 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4625 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004626 CompareResult<String> interfaceDiff = new CompareResult<String>(
4627 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4628 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004629 for (String iface : interfaceDiff.added) {
4630 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004631 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004632 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004633 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004634 } catch (Exception e) {
4635 loge("Exception adding interface: " + e);
4636 }
4637 }
4638 for (String iface : interfaceDiff.removed) {
4639 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004640 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004641 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004642 mNetd.removeInterfaceFromNetwork(iface, netId);
4643 } catch (Exception e) {
4644 loge("Exception removing interface: " + e);
4645 }
4646 }
4647 }
4648
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004649 /**
4650 * Have netd update routes from oldLp to newLp.
4651 * @return true if routes changed between oldLp and newLp
4652 */
4653 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004654 // Compare the route diff to determine which routes should be added and removed.
4655 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4656 oldLp != null ? oldLp.getAllRoutes() : null,
4657 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004658
4659 // add routes before removing old in case it helps with continuous connectivity
4660
4661 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4662 for (RouteInfo route : routeDiff.added) {
4663 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004664 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004665 try {
4666 mNetd.addRoute(netId, route);
4667 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004668 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4669 loge("Exception in addRoute for non-gateway: " + e);
4670 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004671 }
4672 }
4673 for (RouteInfo route : routeDiff.added) {
4674 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004675 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004676 try {
4677 mNetd.addRoute(netId, route);
4678 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004679 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4680 loge("Exception in addRoute for gateway: " + e);
4681 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004682 }
4683 }
4684
4685 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004686 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004687 try {
4688 mNetd.removeRoute(netId, route);
4689 } catch (Exception e) {
4690 loge("Exception in removeRoute: " + e);
4691 }
4692 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004693 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004694 }
Erik Kline41368502015-06-17 13:19:54 +09004695
Erik Kline94887872016-04-05 13:30:49 +09004696 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4697 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4698 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004699 }
Erik Kline94887872016-04-05 13:30:49 +09004700
Erik Kline1742fe12017-12-13 19:40:49 +09004701 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4702 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4703
Erik Klinea24d4592018-01-11 21:07:29 +09004704 if (DBG) {
4705 final Collection<InetAddress> dnses = newLp.getDnsServers();
4706 log("Setting DNS servers for network " + netId + " to " + dnses);
4707 }
Erik Kline94887872016-04-05 13:30:49 +09004708 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004709 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004710 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004711 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004712 }
Erik Kline4edba012017-04-07 15:29:29 +09004713 }
4714
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004715 private String getNetworkPermission(NetworkCapabilities nc) {
4716 // TODO: make these permission strings AIDL constants instead.
4717 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4718 return NetworkManagementService.PERMISSION_SYSTEM;
4719 }
4720 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4721 return NetworkManagementService.PERMISSION_NETWORK;
4722 }
4723 return null;
4724 }
4725
Paul Jensen3d194ea2015-06-16 14:27:36 -04004726 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004727 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4728 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4729 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004730 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004731 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004732 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004733 if (nai.everConnected &&
4734 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4735 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichibae105a2017-08-16 13:19:04 +09004736 // does not cause any request (that is not a listen) currently matching that agent to
4737 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004738 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichieae7a222017-07-25 11:40:56 +09004739 if (!TextUtils.isEmpty(diff)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004740 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichieae7a222017-07-25 11:40:56 +09004741 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004742 }
4743
Paul Jensen3d194ea2015-06-16 14:27:36 -04004744 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004745 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004746 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004747 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004748 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004749 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004750 }
Paul Jensene0988542015-06-25 15:30:08 -04004751 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004752 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004753 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004754 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004755 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004756 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004757 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004758 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004759 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004760 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004761 if (nai.isSuspended()) {
4762 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4763 } else {
4764 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4765 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004766
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004767 return newNc;
4768 }
4769
4770 /**
4771 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4772 *
4773 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4774 * capabilities we manage and store in {@code nai}, such as validated status and captive
4775 * portal status)
4776 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4777 * potentially triggers rematches.
4778 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4779 * change.)
4780 *
4781 * @param oldScore score of the network before any of the changes that prompted us
4782 * to call this function.
4783 * @param nai the network having its capabilities updated.
4784 * @param nc the new network capabilities.
4785 */
4786 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4787 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4788
4789 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004790
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004791 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004792 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004793 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004794 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004795 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004796 } catch (RemoteException e) {
4797 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004798 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004799 }
4800
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004801 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004802 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004803 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004804 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004805 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004806
Chalard Jeanf213ca12018-01-16 18:43:05 +09004807 updateUids(nai, prevNc, newNc);
4808
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004809 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004810 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4811 // the change we're processing can't affect any requests, it can only affect the listens
4812 // on this network. We might have been called by rematchNetworkAndRequests when a
4813 // network changed foreground state.
4814 processListenRequests(nai, true);
4815 } else {
4816 // If the requestable capabilities have changed or the score changed, we can't have been
4817 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004818 rematchAllNetworksAndRequests(nai, oldScore);
4819 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004820 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004821
4822 // Report changes that are interesting for network statistics tracking.
4823 if (prevNc != null) {
4824 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004825 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004826 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004827 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004828 if (meteredChanged || roamingChanged) {
4829 notifyIfacesChangedForNetworkStats();
4830 }
4831 }
4832
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004833 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004834 // Tell VPNs about updated capabilities, since they may need to
4835 // bubble those changes through.
4836 synchronized (mVpns) {
4837 for (int i = 0; i < mVpns.size(); i++) {
4838 final Vpn vpn = mVpns.valueAt(i);
4839 vpn.updateCapabilities();
4840 }
4841 }
4842 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004843 }
4844
Chalard Jeanf213ca12018-01-16 18:43:05 +09004845 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4846 NetworkCapabilities newNc) {
4847 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4848 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4849 if (null == prevRanges) prevRanges = new ArraySet<>();
4850 if (null == newRanges) newRanges = new ArraySet<>();
4851 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4852
4853 prevRanges.removeAll(newRanges);
4854 newRanges.removeAll(prevRangesCopy);
4855
4856 try {
4857 if (!newRanges.isEmpty()) {
4858 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4859 newRanges.toArray(addedRangesArray);
4860 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4861 }
4862 if (!prevRanges.isEmpty()) {
4863 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4864 prevRanges.toArray(removedRangesArray);
4865 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4866 }
4867 } catch (Exception e) {
4868 // Never crash!
4869 loge("Exception in updateUids: " + e);
4870 }
4871 }
4872
Hugo Benichief502882017-09-01 01:23:32 +00004873 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
4874 if (mNetworkForNetId.get(nai.network.netId) != nai) {
4875 // Ignore updates for disconnected networks
4876 return;
4877 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004878 // newLp is already a defensive copy.
4879 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004880 if (VDBG) {
4881 log("Update of LinkProperties for " + nai.name() +
4882 "; created=" + nai.created +
4883 "; everConnected=" + nai.everConnected);
4884 }
4885 LinkProperties oldLp = nai.linkProperties;
4886 synchronized (nai) {
4887 nai.linkProperties = newLp;
4888 }
4889 if (nai.everConnected) {
4890 updateLinkProperties(nai, oldLp);
4891 }
4892 }
4893
Paul Jensenc8b9a742014-09-30 15:37:41 -04004894 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004895 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4896 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004897 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004898 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004899 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4900 }
4901 }
4902
Robert Greenwalt7b816022014-04-18 15:25:25 -07004903 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4904 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004905 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004906 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4907 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004908 }
4909 }
4910
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004911 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4912 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004913 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004914 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004915 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4916 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004917 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004918 sendIntent(nri.mPendingIntent, intent);
4919 }
4920 // else not handled
4921 }
4922
4923 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4924 mPendingIntentWakeLock.acquire();
4925 try {
4926 if (DBG) log("Sending " + pendingIntent);
4927 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4928 } catch (PendingIntent.CanceledException e) {
4929 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4930 mPendingIntentWakeLock.release();
4931 releasePendingNetworkRequest(pendingIntent);
4932 }
4933 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4934 }
4935
4936 @Override
4937 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4938 String resultData, Bundle resultExtras) {
4939 if (DBG) log("Finished sending " + pendingIntent);
4940 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004941 // Release with a delay so the receiving client has an opportunity to put in its
4942 // own request.
4943 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004944 }
4945
Chalard Jeanf19db372018-01-26 19:24:40 +09004946 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004947 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004948 if (nri.messenger == null) {
4949 return; // Default request has no msgr
4950 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004951 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004952 // TODO: check if defensive copies of data is needed.
4953 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004954 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004955 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4956 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004957 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004958 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09004959 case ConnectivityManager.CALLBACK_AVAILABLE: {
4960 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
4961 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
4962 break;
4963 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004964 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004965 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004966 break;
4967 }
4968 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09004969 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb552c462018-02-21 18:43:54 +09004970 final NetworkCapabilities nc = networkCapabilitiesWithoutUidsUnlessAllowed(
4971 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09004972 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004973 break;
4974 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004975 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004976 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004977 break;
4978 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004979 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004980 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004981 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004982 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004983 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004984 String notification = ConnectivityManager.getCallbackName(notificationType);
4985 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004986 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004987 nri.messenger.send(msg);
4988 } catch (RemoteException e) {
4989 // may occur naturally in the race of binder death.
4990 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4991 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004992 }
4993
Hugo Benichidba33db2017-03-23 22:40:44 +09004994 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4995 bundle.putParcelable(t.getClass().getSimpleName(), t);
4996 }
4997
Paul Jensenc8b9a742014-09-30 15:37:41 -04004998 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004999 if (nai.numRequestNetworkRequests() != 0) {
5000 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5001 NetworkRequest nr = nai.requestAt(i);
5002 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005003 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005004 loge("Dead network still had at least " + nr);
5005 break;
5006 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005007 }
5008 nai.asyncChannel.disconnect();
5009 }
5010
Robert Greenwalt7b816022014-04-18 15:25:25 -07005011 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5012 if (oldNetwork == null) {
5013 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5014 return;
5015 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005016 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005017
5018 // If we get here it means that the last linger timeout for this network expired. So there
5019 // must be no other active linger timers, and we must stop lingering.
5020 oldNetwork.clearLingerState();
5021
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005022 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005023 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005024 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005025 } else {
5026 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005027 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5028 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005029 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005030 }
5031
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005032 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005033 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005034 setupDataActivityTracking(newNetwork);
5035 try {
5036 mNetd.setDefaultNetId(newNetwork.network.netId);
5037 } catch (Exception e) {
5038 loge("Exception setting default network :" + e);
5039 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005040
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005041 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005042 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005043 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005044 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005045 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005046 }
5047
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005048 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005049 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5050 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5051 NetworkRequest nr = nri.request;
5052 if (!nr.isListen()) continue;
5053 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5054 nai.removeRequest(nri.request.requestId);
5055 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5056 }
5057 }
5058
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005059 if (capabilitiesChanged) {
5060 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5061 }
5062
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005063 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5064 NetworkRequest nr = nri.request;
5065 if (!nr.isListen()) continue;
5066 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5067 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005068 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005069 }
5070 }
5071 }
5072
Paul Jensen2161a8e2014-09-11 11:00:39 -04005073 // Handles a network appearing or improving its score.
5074 //
5075 // - Evaluates all current NetworkRequests that can be
5076 // satisfied by newNetwork, and reassigns to newNetwork
5077 // any such requests for which newNetwork is the best.
5078 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005079 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005080 // needed. A network is needed if it is the best network for
5081 // one or more NetworkRequests, or if it is a VPN.
5082 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005083 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005084 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005085 //
5086 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5087 // networks that have no chance (i.e. even if validated)
5088 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005089 //
5090 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5091 // it does not remove NetworkRequests that other Networks could better satisfy.
5092 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5093 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5094 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005095 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005096 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005097 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5098 // performed to tear down unvalidated networks that have no chance (i.e. even if
5099 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005100 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005101 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005102 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005103 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005104 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005105 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005106
5107 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5108 final int score = newNetwork.getCurrentScore();
5109
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005110 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005111
Paul Jensen2161a8e2014-09-11 11:00:39 -04005112 // Find and migrate to this Network any NetworkRequests for
5113 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07005114 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04005115 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005116 NetworkCapabilities nc = newNetwork.networkCapabilities;
5117 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005118 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005119 // Process requests in the first pass and listens in the second pass. This allows us to
5120 // change a network's capabilities depending on which requests it has. This is only
5121 // correct if the change in capabilities doesn't affect whether the network satisfies
5122 // requests or not, and doesn't affect the network's score.
5123 if (nri.request.isListen()) continue;
5124
Hugo Benichicd952782017-09-20 11:20:14 +09005125 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005126 final boolean satisfies = newNetwork.satisfies(nri.request);
5127 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005128 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005129 log("Network " + newNetwork.name() + " was already satisfying" +
5130 " request " + nri.request.requestId + ". No change.");
5131 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005132 keep = true;
5133 continue;
5134 }
5135
5136 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005137 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005138 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005139 // next check if it's better than any current network we're using for
5140 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005141 if (VDBG) {
5142 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005143 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005144 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005145 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005146 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005147 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005148 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005149 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005150 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005151 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005152 affectedNetworks.add(currentNetwork);
5153 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005154 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005155 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005156 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005157 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005158 if (!newNetwork.addRequest(nri.request)) {
5159 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5160 }
5161 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005162 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005163 // Tell NetworkFactories about the new score, so they can stop
5164 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005165 // TODO - this could get expensive if we have alot of requests for this
5166 // network. Think about if there is a way to reduce this. Push
5167 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005168 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005169 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005170 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005171 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005172 if (currentNetwork != null) {
5173 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5174 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005175 }
5176 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005177 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005178 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5179 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005180 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005181 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5182 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5183 // This means this code doesn't have to handle the case where "currentNetwork" no
5184 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5185 if (DBG) {
5186 log("Network " + newNetwork.name() + " stopped satisfying" +
5187 " request " + nri.request.requestId);
5188 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005189 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005190 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005191 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005192 sendUpdatedScoreToFactories(nri.request, 0);
5193 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005194 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5195 newNetwork.name() +
5196 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005197 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005198 // TODO: Technically, sending CALLBACK_LOST here is
5199 // incorrect if there is a replacement network currently
5200 // connected that can satisfy nri, which is a request
5201 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005202 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5203 // so this code is only incorrect for a network that loses
5204 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005205 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005206 }
5207 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005208 if (isNewDefault) {
5209 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005210 makeDefault(newNetwork);
5211 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005212 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005213 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005214 // Have a new default network, release the transition wakelock in
5215 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005216 }
5217
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005218 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5219 Slog.wtf(TAG, String.format(
5220 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005221 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005222 }
5223 if (newNetwork.getCurrentScore() != score) {
5224 Slog.wtf(TAG, String.format(
5225 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005226 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005227 }
5228
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005229 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005230 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5231 // If the network went from background to foreground or vice versa, we need to update
5232 // its foreground state. It is safe to do this after rematching the requests because
5233 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5234 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005235 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005236 } else {
5237 processListenRequests(newNetwork, false);
5238 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005239
Paul Jensencf4c2c62015-07-01 14:16:32 -04005240 // do this after the default net is switched, but
5241 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005242 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005243
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005244 // Linger any networks that are no longer needed. This should be done after sending the
5245 // available callback for newNetwork.
5246 for (NetworkAgentInfo nai : affectedNetworks) {
5247 updateLingerState(nai, now);
5248 }
5249 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5250 // does not need to be done in any particular order.
5251 updateLingerState(newNetwork, now);
5252
Paul Jensencf4c2c62015-07-01 14:16:32 -04005253 if (isNewDefault) {
5254 // Maintain the illusion: since the legacy API only
5255 // understands one network at a time, we must pretend
5256 // that the current default network disconnected before
5257 // the new one connected.
5258 if (oldDefaultNetwork != null) {
5259 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5260 oldDefaultNetwork, true);
5261 }
5262 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5263 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5264 notifyLockdownVpn(newNetwork);
5265 }
5266
Robert Greenwalt7b816022014-04-18 15:25:25 -07005267 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005268 // Notify battery stats service about this network, both the normal
5269 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005270 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005271 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005272 final IBatteryStats bs = BatteryStatsService.getService();
5273 final int type = newNetwork.networkInfo.getType();
5274
5275 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5276 bs.noteNetworkInterfaceType(baseIface, type);
5277 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5278 final String stackedIface = stacked.getInterfaceName();
5279 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005280 }
5281 } catch (RemoteException ignored) {
5282 }
5283
Robert Greenwalt152ed372014-12-17 17:19:53 -08005284 // This has to happen after the notifyNetworkCallbacks as that tickles each
5285 // ConnectivityManager instance so that legacy requests correctly bind dns
5286 // requests to this network. The legacy users are listening for this bcast
5287 // and will generally do a dns request so they can ensureRouteToHost and if
5288 // they do that before the callbacks happen they'll use the default network.
5289 //
5290 // TODO: Is there still a race here? We send the broadcast
5291 // after sending the callback, but if the app can receive the
5292 // broadcast before the callback, it might still break.
5293 //
5294 // This *does* introduce a race where if the user uses the new api
5295 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5296 // they may get old info. Reverse this after the old startUsing api is removed.
5297 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005298 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5299 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005300 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005301 // legacy type tracker filters out repeat adds
5302 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5303 }
5304 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005305
5306 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5307 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5308 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5309 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5310 if (newNetwork.isVPN()) {
5311 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5312 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005313 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005314 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5315 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005316 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005317 if (nai.getLingerExpiry() > 0) {
5318 // This network has active linger timers and no requests, but is not
5319 // lingering. Linger it.
5320 //
5321 // One way (the only way?) this can happen if this network is unvalidated
5322 // and became unneeded due to another network improving its score to the
5323 // point where this network will no longer be able to satisfy any requests
5324 // even if it validates.
5325 updateLingerState(nai, now);
5326 } else {
5327 if (DBG) log("Reaping " + nai.name());
5328 teardownUnneededNetwork(nai);
5329 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005330 }
5331 }
5332 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005333 }
5334
Paul Jensen1c7ba022015-06-16 14:27:36 -04005335 /**
5336 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5337 * being disconnected.
5338 * @param changed If only one Network's score or capabilities have been modified since the last
5339 * time this function was called, pass this Network in this argument, otherwise pass
5340 * null.
5341 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5342 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5343 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5344 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5345 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005346 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005347 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005348 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5349 // to avoid the slowness. It is not simply enough to process just "changed", for
5350 // example in the case where "changed"'s score decreases and another network should begin
5351 // satifying a NetworkRequest that "changed" currently satisfies.
5352
5353 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5354 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5355 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005356 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005357 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005358 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005359 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005360 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5361 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5362 // Rematch higher scoring networks first to prevent requests first matching a lower
5363 // scoring network and then a higher scoring network, which could produce multiple
5364 // callbacks and inadvertently unlinger networks.
5365 Arrays.sort(nais);
5366 for (NetworkAgentInfo nai : nais) {
5367 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005368 // Only reap the last time through the loop. Reaping before all rematching
5369 // is complete could incorrectly teardown a network that hasn't yet been
5370 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005371 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005372 : ReapUnvalidatedNetworks.REAP,
5373 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005374 }
5375 }
5376 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005377
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005378 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005379 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005380 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005381 // For now only update icons for default connection.
5382 // TODO: Update WiFi and cellular icons separately. b/17237507
5383 if (!isDefaultNetwork(nai)) return;
5384
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005385 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005386 // Don't repeat publish.
5387 if (newInetCondition == mDefaultInetConditionPublished) return;
5388
5389 mDefaultInetConditionPublished = newInetCondition;
5390 sendInetConditionBroadcast(nai.networkInfo);
5391 }
5392
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005393 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005394 synchronized (mVpns) {
5395 if (mLockdownTracker != null) {
5396 if (nai != null && nai.isVPN()) {
5397 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5398 } else {
5399 mLockdownTracker.onNetworkInfoChanged();
5400 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005401 }
5402 }
5403 }
5404
Robert Greenwalt7b816022014-04-18 15:25:25 -07005405 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005406 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005407 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005408 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005409 synchronized (networkAgent) {
5410 oldInfo = networkAgent.networkInfo;
5411 networkAgent.networkInfo = newInfo;
5412 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005413 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005414
Robert Greenwalt7b816022014-04-18 15:25:25 -07005415 if (DBG) {
5416 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5417 (oldInfo == null ? "null" : oldInfo.getState()) +
5418 " to " + state);
5419 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005420
Robin Lee585e2482016-05-01 23:00:00 +01005421 if (!networkAgent.created
5422 && (state == NetworkInfo.State.CONNECTED
5423 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005424
5425 // A network that has just connected has zero requests and is thus a foreground network.
5426 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5427
Robert Greenwalt7b816022014-04-18 15:25:25 -07005428 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005429 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005430 if (networkAgent.isVPN()) {
5431 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005432 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5433 (networkAgent.networkMisc == null ||
5434 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005435 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005436 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005437 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005438 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005439 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005440 loge("Error creating network " + networkAgent.network.netId + ": "
5441 + e.getMessage());
5442 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005443 }
Paul Jenseneec75412014-08-04 12:21:19 -04005444 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005445 }
5446
5447 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5448 networkAgent.everConnected = true;
5449
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09005450 if (networkAgent.linkProperties == null) {
5451 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
5452 }
5453
Robert Greenwalt7b816022014-04-18 15:25:25 -07005454 updateLinkProperties(networkAgent, null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005455
Paul Jensenca8f16a2014-05-09 12:47:55 -04005456 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005457 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005458
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005459 if (networkAgent.isVPN()) {
5460 // Temporarily disable the default proxy (not global).
5461 synchronized (mProxyLock) {
5462 if (!mDefaultProxyDisabled) {
5463 mDefaultProxyDisabled = true;
5464 if (mGlobalProxy == null && mDefaultProxy != null) {
5465 sendProxyBroadcast(null);
5466 }
5467 }
5468 }
5469 // TODO: support proxy per network.
5470 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005471
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005472 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5473 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5474 // capabilities, so it only needs to be done once on initial connect, not every time the
5475 // network's capabilities change. Note that we do this before rematching the network,
5476 // so we could decide to tear it down immediately afterwards. That's fine though - on
5477 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5478 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005479 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005480
Paul Jensen2161a8e2014-09-11 11:00:39 -04005481 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005482 final long now = SystemClock.elapsedRealtime();
5483 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005484
5485 // This has to happen after matching the requests, because callbacks are just requests.
5486 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005487 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005488 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005489 if (networkAgent.isVPN()) {
5490 synchronized (mProxyLock) {
5491 if (mDefaultProxyDisabled) {
5492 mDefaultProxyDisabled = false;
5493 if (mGlobalProxy == null && mDefaultProxy != null) {
5494 sendProxyBroadcast(mDefaultProxy);
5495 }
5496 }
5497 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005498 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005499 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005500 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5501 state == NetworkInfo.State.SUSPENDED) {
5502 // going into or coming out of SUSPEND: rescore and notify
5503 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005504 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005505 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005506 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5507 networkAgent.networkCapabilities);
5508 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5509 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005510 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5511 ConnectivityManager.CALLBACK_SUSPENDED :
5512 ConnectivityManager.CALLBACK_RESUMED));
5513 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005514 }
5515 }
5516
Robert Greenwaltac96c522014-06-03 16:43:57 -07005517 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005518 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005519 if (score < 0) {
5520 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5521 "). Bumping score to min of 0");
5522 score = 0;
5523 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005524
Paul Jensen2161a8e2014-09-11 11:00:39 -04005525 final int oldScore = nai.getCurrentScore();
5526 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005527
Paul Jensen85cf78e2015-06-25 13:25:07 -04005528 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005529
Paul Jensenc8b9a742014-09-30 15:37:41 -04005530 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005531 }
5532
Erik Klinec75d4fa2017-02-15 19:59:17 +09005533 // Notify only this one new request of the current state. Transfer all the
5534 // current state by calling NetworkCapabilities and LinkProperties callbacks
5535 // so that callers can be guaranteed to have as close to atomicity in state
5536 // transfer as can be supported by this current API.
5537 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005538 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005539 if (nri.mPendingIntent != null) {
5540 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5541 // Attempt no subsequent state pushes where intents are involved.
5542 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005543 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005544
5545 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005546 }
5547
Robert Greenwalt8d482522015-06-24 13:23:42 -07005548 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005549 // The NetworkInfo we actually send out has no bearing on the real
5550 // state of affairs. For example, if the default connection is mobile,
5551 // and a request for HIPRI has just gone away, we need to pretend that
5552 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5553 // the state to DISCONNECTED, even though the network is of type MOBILE
5554 // and is still connected.
5555 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5556 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005557 if (state != DetailedState.DISCONNECTED) {
5558 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005559 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005560 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005561 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005562 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5563 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5564 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5565 if (info.isFailover()) {
5566 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5567 nai.networkInfo.setFailover(false);
5568 }
5569 if (info.getReason() != null) {
5570 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5571 }
5572 if (info.getExtraInfo() != null) {
5573 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5574 }
5575 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005576 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005577 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005578 if (newDefaultAgent != null) {
5579 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5580 newDefaultAgent.networkInfo);
5581 } else {
5582 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5583 }
5584 }
5585 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5586 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005587 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005588 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005589 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005590 }
5591 }
5592 }
5593
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005594 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005595 if (VDBG) {
5596 String notification = ConnectivityManager.getCallbackName(notifyType);
5597 log("notifyType " + notification + " for " + networkAgent.name());
5598 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005599 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5600 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005601 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5602 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005603 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5604 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005605 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005606 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005607 } else {
5608 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5609 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005610 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005611 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005612
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005613 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5614 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5615 }
5616
Jeff Sharkey69736342014-12-08 14:50:12 -08005617 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005618 * Returns the list of all interfaces that could be used by network traffic that does not
5619 * explicitly specify a network. This includes the default network, but also all VPNs that are
5620 * currently connected.
5621 *
5622 * Must be called on the handler thread.
5623 */
5624 private Network[] getDefaultNetworks() {
5625 ArrayList<Network> defaultNetworks = new ArrayList<>();
5626 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5627 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5628 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5629 defaultNetworks.add(nai.network);
5630 }
5631 }
5632 return defaultNetworks.toArray(new Network[0]);
5633 }
5634
5635 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005636 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5637 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005638 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005639 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005640 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005641 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005642 } catch (Exception ignored) {
5643 }
5644 }
5645
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005646 @Override
5647 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005648 int user = UserHandle.getUserId(Binder.getCallingUid());
5649 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005650 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005651 return mVpns.get(user).addAddress(address, prefixLength);
5652 }
5653 }
5654
5655 @Override
5656 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005657 int user = UserHandle.getUserId(Binder.getCallingUid());
5658 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005659 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005660 return mVpns.get(user).removeAddress(address, prefixLength);
5661 }
5662 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005663
5664 @Override
5665 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005666 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005667 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005668 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005669 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005670 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005671 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005672 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005673 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005674 }
5675 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005676 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005677
5678 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005679 public String getCaptivePortalServerUrl() {
Udam Sainic3b640c2017-06-07 12:06:28 -07005680 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005681 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005682 }
5683
5684 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005685 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5686 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5687 enforceKeepalivePermission();
5688 mKeepaliveTracker.startNattKeepalive(
5689 getNetworkAgentInfoForNetwork(network),
5690 intervalSeconds, messenger, binder,
5691 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5692 }
5693
5694 @Override
5695 public void stopKeepalive(Network network, int slot) {
5696 mHandler.sendMessage(mHandler.obtainMessage(
5697 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5698 }
5699
5700 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005701 public void factoryReset() {
5702 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005703
5704 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5705 return;
5706 }
5707
Robin Lee3b3dd942015-05-12 18:14:58 +01005708 final int userId = UserHandle.getCallingUserId();
5709
Stuart Scottf1fb3972015-04-02 18:00:02 -07005710 // Turn airplane mode off
5711 setAirplaneMode(false);
5712
Stuart Scotte3e314d2015-04-20 14:07:45 -07005713 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5714 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005715 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005716 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005717 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005718 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005719 }
5720
Stuart Scotte3e314d2015-04-20 14:07:45 -07005721 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005722 // Remove always-on package
5723 synchronized (mVpns) {
5724 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5725 if (alwaysOnPackage != null) {
5726 setAlwaysOnVpnPackage(userId, null, false);
5727 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5728 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005729
Hugo Benichi69744342017-11-27 10:57:16 +09005730 // Turn Always-on VPN off
5731 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5732 final long ident = Binder.clearCallingIdentity();
5733 try {
5734 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5735 mLockdownEnabled = false;
5736 setLockdownTracker(null);
5737 } finally {
5738 Binder.restoreCallingIdentity(ident);
5739 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005740 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005741
Hugo Benichi69744342017-11-27 10:57:16 +09005742 // Turn VPN off
5743 VpnConfig vpnConfig = getVpnConfig(userId);
5744 if (vpnConfig != null) {
5745 if (vpnConfig.legacy) {
5746 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5747 } else {
5748 // Prevent this app (packagename = vpnConfig.user) from initiating
5749 // VPN connections in the future without user intervention.
5750 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005751
Hugo Benichi69744342017-11-27 10:57:16 +09005752 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5753 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005754 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005755 }
5756 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005757
5758 Settings.Global.putString(mContext.getContentResolver(),
5759 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005760 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005761
5762 @VisibleForTesting
5763 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5764 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5765 return new NetworkMonitor(context, handler, nai, defaultRequest);
5766 }
Erik Kline48f12f22016-04-14 17:30:59 +09005767
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005768 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005769 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5770 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005771 }
5772
5773 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005774 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5775 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5776 }
5777
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005778 @VisibleForTesting
5779 public boolean hasService(String name) {
5780 return ServiceManager.checkService(name) != null;
5781 }
5782
Hugo Benichi64901e52017-10-19 14:42:40 +09005783 @VisibleForTesting
5784 protected IpConnectivityMetrics.Logger metricsLogger() {
5785 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5786 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005787 }
5788
5789 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005790 int[] transports = nai.networkCapabilities.getTransportTypes();
5791 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005792 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005793
5794 private static boolean toBool(int encodedBoolean) {
5795 return encodedBoolean != 0; // Only 0 means false.
5796 }
5797
5798 private static int encodeBool(boolean b) {
5799 return b ? 1 : 0;
5800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005801}