blob: 6c24e947c90e145c02434b89b8246ad55874fd24 [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.
881 final TetheringDependencies deps = new TetheringDependencies();
882 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
883 IoThread.get().getLooper(), new MockableSystemProperties(),
884 deps);
885 }
886
Chalard Jeandda156a2018-01-10 21:19:32 +0900887 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900888 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900889 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900890 netCap.addCapability(NET_CAPABILITY_INTERNET);
891 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900892 if (transportType > -1) {
893 netCap.addTransportType(transportType);
894 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900895 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900896 }
897
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900898 // Used only for testing.
899 // TODO: Delete this and either:
900 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
901 // changing ContentResolver to make registerContentObserver non-final).
902 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
903 // by subclassing SettingsObserver.
904 @VisibleForTesting
905 void updateMobileDataAlwaysOn() {
906 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
907 }
908
Erik Klineda4bfa82015-04-30 12:58:40 +0900909 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900910 final boolean enable = toBool(Settings.Global.getInt(
911 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900912 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
913 if (enable == isEnabled) {
914 return; // Nothing to do.
915 }
916
917 if (enable) {
918 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900919 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900920 } else {
921 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
922 }
923 }
924
925 private void registerSettingsCallbacks() {
926 // Watch for global HTTP proxy changes.
927 mSettingsObserver.observe(
928 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
929 EVENT_APPLY_GLOBAL_HTTP_PROXY);
930
931 // Watch for whether or not to keep mobile data always on.
932 mSettingsObserver.observe(
933 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
934 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
935 }
936
Erik Klinea24d4592018-01-11 21:07:29 +0900937 private void registerPrivateDnsSettingsCallbacks() {
938 for (Uri u : DnsManager.getPrivateDnsSettingsUris()) {
939 mSettingsObserver.observe(u, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
940 }
941 }
942
Robert Greenwalt34524f02014-05-18 16:22:10 -0700943 private synchronized int nextNetworkRequestId() {
944 return mNextNetworkRequestId++;
945 }
946
Paul Jensen67b0b072015-06-10 11:22:17 -0400947 @VisibleForTesting
948 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400949 synchronized (mNetworkForNetId) {
950 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
951 int netId = mNextNetId;
952 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
953 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500954 if (!mNetIdInUse.get(netId)) {
955 mNetIdInUse.put(netId, true);
956 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400957 }
958 }
959 }
960 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700961 }
962
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600963 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800964 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600965 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
966 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800967 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600968 state = nai.getNetworkState();
969 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800970 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600971 final NetworkInfo info = new NetworkInfo(networkType, 0,
972 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800973 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
974 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -0700975 final NetworkCapabilities capabilities = new NetworkCapabilities();
976 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
977 !info.isRoaming());
978 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600979 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800980 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600981 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600982 return state;
983 } else {
984 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800985 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400986 }
987
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800988 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
989 if (network == null) {
990 return null;
991 }
992 synchronized (mNetworkForNetId) {
993 return mNetworkForNetId.get(network.netId);
994 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600995 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800996
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900997 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +0900998 synchronized (mVpns) {
999 if (!mLockdownEnabled) {
1000 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001001 Vpn vpn = mVpns.get(user);
1002 if (vpn != null && vpn.appliesToUid(uid)) {
1003 return vpn.getUnderlyingNetworks();
1004 }
1005 }
1006 }
1007 return null;
1008 }
1009
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001010 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001011 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001012
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001013 final Network[] networks = getVpnUnderlyingNetworks(uid);
1014 if (networks != null) {
1015 // getUnderlyingNetworks() returns:
1016 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1017 // empty array => the VPN explicitly said "no default network".
1018 // non-empty array => the VPN specified one or more default networks; we use the
1019 // first one.
1020 if (networks.length > 0) {
1021 nai = getNetworkAgentInfoForNetwork(networks[0]);
1022 } else {
1023 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001024 }
1025 }
1026
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001027 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001028 return nai.getNetworkState();
1029 } else {
1030 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001031 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001032 }
1033
1034 /**
1035 * Check if UID should be blocked from using the network with the given LinkProperties.
1036 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001037 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1038 boolean ignoreBlocked) {
1039 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001040 if (ignoreBlocked) {
1041 return false;
1042 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001043 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001044 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1045 if (isSystem(uid)) {
1046 return false;
1047 }
Robin Lee17e61832016-05-09 13:46:28 +01001048 synchronized (mVpns) {
1049 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1050 if (vpn != null && vpn.isBlockingUid(uid)) {
1051 return true;
1052 }
1053 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001054 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001055 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001056 }
1057
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001058 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001059 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1060 return;
1061 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001062 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001063 synchronized (mBlockedAppUids) {
1064 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001065 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001066 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001067 blocked = false;
1068 } else {
1069 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001070 }
1071 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001072 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1073 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1074 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001075 }
1076
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001077 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001078 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1079 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001080 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001081 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001082 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001083 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1084
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001085 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001086 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001087 }
Hugo Benichi69744342017-11-27 10:57:16 +09001088 synchronized (mVpns) {
1089 if (mLockdownTracker != null) {
1090 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1091 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001092 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001093 }
1094
1095 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 * Return NetworkInfo for the active (i.e., connected) network interface.
1097 * It is assumed that at most one network is active at a time. If more
1098 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001099 * @return the info for the active network, or {@code null} if none is
1100 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001102 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001104 enforceAccessPermission();
1105 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001106 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001107 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001108 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1109 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 }
1111
Paul Jensen31a94f42015-02-13 14:18:39 -05001112 @Override
1113 public Network getActiveNetwork() {
1114 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001115 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001116 }
1117
1118 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001119 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001120 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001121 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001122 }
1123
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001124 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001125 final int user = UserHandle.getUserId(uid);
1126 int vpnNetId = NETID_UNSET;
1127 synchronized (mVpns) {
1128 final Vpn vpn = mVpns.get(user);
1129 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1130 }
1131 NetworkAgentInfo nai;
1132 if (vpnNetId != NETID_UNSET) {
1133 synchronized (mNetworkForNetId) {
1134 nai = mNetworkForNetId.get(vpnNetId);
1135 }
1136 if (nai != null) return nai.network;
1137 }
1138 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001139 if (nai != null
1140 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1141 nai = null;
1142 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001143 return nai != null ? nai.network : null;
1144 }
1145
Lorenzo Colitti18660282016-07-04 12:55:44 +09001146 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001147 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1148 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001149 final int uid = Binder.getCallingUid();
1150 NetworkState state = getUnfilteredActiveNetworkState(uid);
1151 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001152 }
1153
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001154 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001155 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001156 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001157 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001158 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001159 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001160 }
1161
1162 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 public NetworkInfo getNetworkInfo(int networkType) {
1164 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001165 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001166 if (getVpnUnderlyingNetworks(uid) != null) {
1167 // A VPN is active, so we may need to return one of its underlying networks. This
1168 // information is not available in LegacyTypeTracker, so we have to get it from
1169 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001170 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001171 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001172 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001173 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001174 }
1175 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001176 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001177 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 }
1179
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001180 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001181 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001182 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001183 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001184 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001185 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001186 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001187 return state.networkInfo;
1188 } else {
1189 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001190 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001191 }
1192
1193 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 public NetworkInfo[] getAllNetworkInfo() {
1195 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001196 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001197 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1198 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001199 NetworkInfo info = getNetworkInfo(networkType);
1200 if (info != null) {
1201 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001204 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 }
1206
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001207 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001208 public Network getNetworkForType(int networkType) {
1209 enforceAccessPermission();
1210 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001211 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1212 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001213 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001214 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001215 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001216 }
1217
1218 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001219 public Network[] getAllNetworks() {
1220 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001221 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001222 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001223 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001224 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001225 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001226 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001227 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001228 }
1229
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001230 @Override
1231 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1232 // The basic principle is: if an app's traffic could possibly go over a
1233 // network, without the app doing anything multinetwork-specific,
1234 // (hence, by "default"), then include that network's capabilities in
1235 // the array.
1236 //
1237 // In the normal case, app traffic only goes over the system's default
1238 // network connection, so that's the only network returned.
1239 //
1240 // With a VPN in force, some app traffic may go into the VPN, and thus
1241 // over whatever underlying networks the VPN specifies, while other app
1242 // traffic may go over the system default network (e.g.: a split-tunnel
1243 // VPN, or an app disallowed by the VPN), so the set of networks
1244 // returned includes the VPN's underlying networks and the system
1245 // default.
1246 enforceAccessPermission();
1247
1248 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1249
1250 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001251 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001252 if (nc != null) {
1253 result.put(nai.network, nc);
1254 }
1255
Hugo Benichi69744342017-11-27 10:57:16 +09001256 synchronized (mVpns) {
1257 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001258 Vpn vpn = mVpns.get(userId);
1259 if (vpn != null) {
1260 Network[] networks = vpn.getUnderlyingNetworks();
1261 if (networks != null) {
1262 for (Network network : networks) {
1263 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001264 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001265 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001266 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001267 }
1268 }
1269 }
1270 }
1271 }
1272 }
1273
1274 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1275 out = result.values().toArray(out);
1276 return out;
1277 }
1278
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001279 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001280 public boolean isNetworkSupported(int networkType) {
1281 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001282 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001283 }
1284
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001285 /**
1286 * Return LinkProperties for the active (i.e., connected) default
1287 * network interface. It is assumed that at most one default network
1288 * is active at a time. If more than one is active, it is indeterminate
1289 * which will be returned.
1290 * @return the ip properties for the active network, or {@code null} if
1291 * none is active
1292 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001293 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001294 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001295 enforceAccessPermission();
1296 final int uid = Binder.getCallingUid();
1297 NetworkState state = getUnfilteredActiveNetworkState(uid);
1298 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001299 }
1300
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001301 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001302 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001303 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001304 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1305 if (nai != null) {
1306 synchronized (nai) {
1307 return new LinkProperties(nai.linkProperties);
1308 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001309 }
1310 return null;
1311 }
1312
Robert Greenwalt12e67352014-05-13 21:41:06 -07001313 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001314 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001315 public LinkProperties getLinkProperties(Network network) {
1316 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001317 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1318 }
1319
1320 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1321 if (nai == null) {
1322 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001323 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001324 synchronized (nai) {
1325 return new LinkProperties(nai.linkProperties);
1326 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001327 }
1328
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001329 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001330 if (nai != null) {
1331 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001332 if (nai.networkCapabilities != null) {
Chalard Jeanb552c462018-02-21 18:43:54 +09001333 return networkCapabilitiesWithoutUidsUnlessAllowed(nai.networkCapabilities,
1334 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001335 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001336 }
1337 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001338 return null;
1339 }
1340
1341 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001342 public NetworkCapabilities getNetworkCapabilities(Network network) {
1343 enforceAccessPermission();
1344 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1345 }
1346
Chalard Jeanb552c462018-02-21 18:43:54 +09001347 private NetworkCapabilities networkCapabilitiesWithoutUidsUnlessAllowed(
1348 NetworkCapabilities nc, int callerPid, int callerUid) {
1349 if (checkSettingsPermission(callerPid, callerUid)) return new NetworkCapabilities(nc);
Chalard Jeanf19db372018-01-26 19:24:40 +09001350 return new NetworkCapabilities(nc).setUids(null);
1351 }
1352
Chalard Jeanb552c462018-02-21 18:43:54 +09001353 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1354 if (!checkSettingsPermission()) {
1355 nc.setSingleUid(Binder.getCallingUid());
1356 }
1357 }
1358
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001359 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001360 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001361 // Require internal since we're handing out IMSI details
1362 enforceConnectivityInternalPermission();
1363
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001364 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001365 for (Network network : getAllNetworks()) {
1366 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1367 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001368 // TODO (b/73321673) : NetworkState contains a copy of the
1369 // NetworkCapabilities, which may contain UIDs of apps to which the
1370 // network applies. Should the UIDs be cleared so as not to leak or
1371 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001372 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001373 }
1374 }
1375 return result.toArray(new NetworkState[result.size()]);
1376 }
1377
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001378 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001379 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001380 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001381 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1382 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1383 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001384 }
1385
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001386 @Override
1387 public boolean isActiveNetworkMetered() {
1388 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001389
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001390 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
1391 if (caps != null) {
1392 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1393 } else {
1394 // Always return the most conservative value
1395 return true;
1396 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001397 }
1398
Jeff Sharkey216c1812012-08-05 14:29:23 -07001399 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1400 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001401 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001402 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001403 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001404 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001405 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001406
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001407 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 * Ensure that a network route exists to deliver traffic to the specified
1409 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001410 * @param networkType the type of the network over which traffic to the
1411 * specified host is to be routed
1412 * @param hostAddress the IP address of the host to which the route is
1413 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 * @return {@code true} on success, {@code false} on failure
1415 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001416 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001417 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001419 if (mProtectedNetworks.contains(networkType)) {
1420 enforceConnectivityInternalPermission();
1421 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001422
Chad Brubakerc0234532014-02-14 13:24:29 -08001423 InetAddress addr;
1424 try {
1425 addr = InetAddress.getByAddress(hostAddress);
1426 } catch (UnknownHostException e) {
1427 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1428 return false;
1429 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001432 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 return false;
1434 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001435
1436 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1437 if (nai == null) {
1438 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1439 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1440 } else {
1441 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1442 }
1443 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001444 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001445
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001446 DetailedState netState;
1447 synchronized (nai) {
1448 netState = nai.networkInfo.getDetailedState();
1449 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001450
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001451 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001452 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001453 log("requestRouteToHostAddress on down network "
1454 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001455 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001456 }
1457 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001459
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001460 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001461 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001462 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001463 LinkProperties lp;
1464 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001465 synchronized (nai) {
1466 lp = nai.linkProperties;
1467 netId = nai.network.netId;
1468 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001469 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001470 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1471 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001472 } finally {
1473 Binder.restoreCallingIdentity(token);
1474 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001475 }
1476
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001477 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001478 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001479 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001480 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001481 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001482 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001483 if (bestRoute.getGateway().equals(addr)) {
1484 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001485 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001486 } else {
1487 // if we will connect to this through another route, add a direct route
1488 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001489 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001490 }
1491 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001492 if (DBG) log("Adding legacy route " + bestRoute +
1493 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001494 try {
1495 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1496 } catch (Exception e) {
1497 // never crash - catch them all
1498 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001499 return false;
1500 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001501 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 }
1503
Jeff Sharkey75d31892018-01-18 22:01:59 +09001504 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001505 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001506 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001507 // TODO: notify UID when it has requested targeted updates
1508 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001509 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001510 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001511 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001512 if (restrictBackground) {
1513 log("onRestrictBackgroundChanged(true): disabling tethering");
1514 mTethering.untetherAll();
1515 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001516 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001517 };
1518
Robin Lee3b3dd942015-05-12 18:14:58 +01001519 /**
1520 * Require that the caller is either in the same user or has appropriate permission to interact
1521 * across users.
1522 *
1523 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1524 */
1525 private void enforceCrossUserPermission(int userId) {
1526 if (userId == UserHandle.getCallingUserId()) {
1527 // Not a cross-user call.
1528 return;
1529 }
1530 mContext.enforceCallingOrSelfPermission(
1531 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1532 "ConnectivityService");
1533 }
1534
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001535 private void enforceInternetPermission() {
1536 mContext.enforceCallingOrSelfPermission(
1537 android.Manifest.permission.INTERNET,
1538 "ConnectivityService");
1539 }
1540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001542 mContext.enforceCallingOrSelfPermission(
1543 android.Manifest.permission.ACCESS_NETWORK_STATE,
1544 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 }
1546
1547 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001548 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 }
1550
Charles Hea0a87e82017-05-15 17:07:18 +01001551 private void enforceSettingsPermission() {
1552 mContext.enforceCallingOrSelfPermission(
1553 android.Manifest.permission.NETWORK_SETTINGS,
1554 "ConnectivityService");
1555 }
1556
Chalard Jeanb552c462018-02-21 18:43:54 +09001557 private boolean checkSettingsPermission() {
1558 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1559 android.Manifest.permission.NETWORK_SETTINGS);
1560 }
1561
1562 private boolean checkSettingsPermission(int pid, int uid) {
1563 return PERMISSION_GRANTED == mContext.checkPermission(
1564 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1565 }
1566
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001567 private void enforceTetherAccessPermission() {
1568 mContext.enforceCallingOrSelfPermission(
1569 android.Manifest.permission.ACCESS_NETWORK_STATE,
1570 "ConnectivityService");
1571 }
1572
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001573 private void enforceConnectivityInternalPermission() {
1574 mContext.enforceCallingOrSelfPermission(
1575 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1576 "ConnectivityService");
1577 }
1578
Hugo Benichi514da602016-07-19 15:59:27 +09001579 private void enforceConnectivityRestrictedNetworksPermission() {
1580 try {
1581 mContext.enforceCallingOrSelfPermission(
1582 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1583 "ConnectivityService");
1584 return;
1585 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1586 enforceConnectivityInternalPermission();
1587 }
1588
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001589 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001590 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001591 }
1592
Lorenzo Colitti18660282016-07-04 12:55:44 +09001593 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001594 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001595 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001596 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001597 }
1598
1599 private void sendInetConditionBroadcast(NetworkInfo info) {
1600 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1601 }
1602
Wink Saville628b0852011-08-04 15:01:58 -07001603 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001604 synchronized (mVpns) {
1605 if (mLockdownTracker != null) {
1606 info = new NetworkInfo(info);
1607 mLockdownTracker.augmentNetworkInfo(info);
1608 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001609 }
1610
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001611 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001612 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001613 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 if (info.isFailover()) {
1615 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1616 info.setFailover(false);
1617 }
1618 if (info.getReason() != null) {
1619 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1620 }
1621 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001622 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1623 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001625 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001626 return intent;
1627 }
1628
1629 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1630 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1631 }
1632
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001633 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001634 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1635 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1636 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001637 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001638 final long ident = Binder.clearCallingIdentity();
1639 try {
1640 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1641 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1642 } finally {
1643 Binder.restoreCallingIdentity(ident);
1644 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001645 }
1646
Mike Lockwood0f79b542009-08-14 14:18:49 -04001647 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001648 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001649 if (!mSystemReady) {
1650 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001651 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001652 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001653 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001654 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001655 }
1656
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001657 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001658 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001659 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001660 final NetworkInfo ni = intent.getParcelableExtra(
1661 ConnectivityManager.EXTRA_NETWORK_INFO);
1662 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1663 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1664 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001665 } else {
1666 BroadcastOptions opts = BroadcastOptions.makeBasic();
1667 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1668 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001669 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001670 final IBatteryStats bs = BatteryStatsService.getService();
1671 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001672 bs.noteConnectivityChanged(intent.getIntExtra(
1673 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1674 ni != null ? ni.getState().toString() : "?");
1675 } catch (RemoteException e) {
1676 }
1677 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001678 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001679 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001680 } finally {
1681 Binder.restoreCallingIdentity(ident);
1682 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001683 }
1684 }
1685
1686 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001687 loadGlobalProxy();
1688
Hugo Benichi20035e02017-04-26 14:53:28 +09001689 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001690 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001691 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001692 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001693 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001694 }
1695 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001696 // load the global proxy at startup
1697 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001698
Robin Lee244ce8e2016-01-05 18:03:46 +00001699 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1700 // for user to unlock device too.
1701 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001702
Erik Klineda4bfa82015-04-30 12:58:40 +09001703 // Configure whether mobile data is always on.
1704 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1705
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001706 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001707
1708 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 }
1710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001712 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001713 *
1714 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001715 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001716 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001717 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1718 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001719
1720 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001721 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001722
Robert Greenwalt7b816022014-04-18 15:25:25 -07001723 if (networkAgent.networkCapabilities.hasTransport(
1724 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001725 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1726 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001727 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001728 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001729 } else if (networkAgent.networkCapabilities.hasTransport(
1730 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001731 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1732 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001733 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001734 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001735 } else {
1736 // do not track any other networks
1737 timeout = 0;
1738 }
1739
Robert Greenwalt7b816022014-04-18 15:25:25 -07001740 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001741 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001742 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001743 } catch (Exception e) {
1744 // You shall not crash!
1745 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001746 }
1747 }
1748 }
1749
1750 /**
1751 * Remove data activity tracking when network disconnects.
1752 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001753 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1754 final String iface = networkAgent.linkProperties.getInterfaceName();
1755 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001756
Robert Greenwalt7b816022014-04-18 15:25:25 -07001757 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1758 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001759 try {
1760 // the call fails silently if no idletimer setup for this interface
1761 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001762 } catch (Exception e) {
1763 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001764 }
1765 }
1766 }
1767
1768 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001769 * Reads the network specific MTU size from reources.
1770 * and set it on it's iface.
1771 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001772 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1773 final String iface = newLp.getInterfaceName();
1774 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001775 if (oldLp == null && mtu == 0) {
1776 // Silently ignore unset MTU value.
1777 return;
1778 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001779 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1780 if (VDBG) log("identical MTU - not setting");
1781 return;
1782 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001783 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001784 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001785 return;
1786 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001787
w1997615afd812014-08-05 15:18:11 -07001788 // Cannot set MTU without interface name
1789 if (TextUtils.isEmpty(iface)) {
1790 loge("Setting MTU size with null iface.");
1791 return;
1792 }
1793
Robert Greenwalt7b816022014-04-18 15:25:25 -07001794 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001795 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001796 mNetd.setMtu(iface, mtu);
1797 } catch (Exception e) {
1798 Slog.e(TAG, "exception in setMtu()" + e);
1799 }
1800 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001801
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001802 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001803 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1804
1805 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001806 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001807 protected MockableSystemProperties getSystemProperties() {
1808 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001809 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001810
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001811 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1812 if (isDefaultNetwork(nai) == false) {
1813 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001814 }
1815
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001816 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1817 String[] values = null;
1818 if (tcpBufferSizes != null) {
1819 values = tcpBufferSizes.split(",");
1820 }
1821
1822 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001823 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001824 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1825 values = tcpBufferSizes.split(",");
1826 }
1827
1828 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1829
1830 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001831 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001832
1833 final String prefix = "/sys/kernel/ipv4/tcp_";
1834 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1835 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1836 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1837 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1838 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1839 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1840 mCurrentTcpBufferSizes = tcpBufferSizes;
1841 } catch (IOException e) {
1842 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001843 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001844
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001845 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001846 Settings.Global.TCP_DEFAULT_INIT_RWND,
1847 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001848 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1849 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001850 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001851 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001852 }
1853
Robert Greenwalt562cc542014-05-15 18:07:26 -07001854 @Override
1855 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001856 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001857 NETWORK_RESTORE_DELAY_PROP_NAME);
1858 if(restoreDefaultNetworkDelayStr != null &&
1859 restoreDefaultNetworkDelayStr.length() != 0) {
1860 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001861 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001862 } catch (NumberFormatException e) {
1863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001865 // if the system property isn't set, use the value for the apn type
1866 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1867
1868 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1869 (mNetConfigs[networkType] != null)) {
1870 ret = mNetConfigs[networkType].restoreTime;
1871 }
1872 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 }
1874
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001875 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001876 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001877 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001878 }
1879 return false;
1880 }
1881
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001882 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1883 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1884 final long DIAG_TIME_MS = 5000;
1885 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1886 // Start gathering diagnostic information.
1887 netDiags.add(new NetworkDiagnostics(
1888 nai.network,
1889 new LinkProperties(nai.linkProperties), // Must be a copy.
1890 DIAG_TIME_MS));
1891 }
1892
1893 for (NetworkDiagnostics netDiag : netDiags) {
1894 pw.println();
1895 netDiag.waitForMeasurements();
1896 netDiag.dump(pw);
1897 }
1898 }
1899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001901 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1902 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001903 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001904
Erik Kline7747fd42017-05-12 16:52:48 +09001905 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001906 dumpNetworkDiagnostics(pw);
1907 return;
Erik Klineee363c42017-05-29 09:11:03 +09001908 } else if (argsContain(args, TETHERING_ARG)) {
1909 mTethering.dump(fd, pw, args);
1910 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001911 }
Erik Kline379747a2015-06-05 17:47:34 +09001912
Lorenzo Colittie3805462015-06-03 11:18:24 +09001913 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001914 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001915 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001916 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001917 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001918 pw.println();
1919
Paul Jensen85cf78e2015-06-25 13:25:07 -04001920 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001921 pw.print("Active default network: ");
1922 if (defaultNai == null) {
1923 pw.println("none");
1924 } else {
1925 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001927 pw.println();
1928
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001929 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001930 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001931 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1932 pw.println(nai.toString());
1933 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001934 pw.println(String.format(
1935 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1936 nai.numForegroundNetworkRequests(),
1937 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1938 nai.numBackgroundNetworkRequests(),
1939 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001940 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001941 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1942 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001943 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001944 pw.decreaseIndent();
1945 pw.println("Lingered:");
1946 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001947 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001948 pw.decreaseIndent();
1949 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001950 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001951 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001952 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001953
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001954 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001955 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001956 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1957 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001958 }
1959 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001960 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001961
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001962 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001963
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001964 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001965 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001966
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001967 pw.println();
1968 mKeepaliveTracker.dump(pw);
1969
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001970 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001971 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001972
Erik Kline7747fd42017-05-12 16:52:48 +09001973 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001974 pw.println();
1975 synchronized (mValidationLogs) {
1976 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001977 for (ValidationLog p : mValidationLogs) {
1978 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001979 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001980 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001981 pw.decreaseIndent();
1982 }
1983 }
Erik Kline7523eb32015-07-09 18:24:03 +09001984
1985 pw.println();
1986 pw.println("mNetworkRequestInfoLogs (most recent first):");
1987 pw.increaseIndent();
1988 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1989 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09001990
1991 pw.println();
1992 pw.println("mNetworkInfoBlockingLogs (most recent first):");
1993 pw.increaseIndent();
1994 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
1995 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001996
1997 pw.println();
1998 pw.println("NetTransition WakeLock activity (most recent first):");
1999 pw.increaseIndent();
Hugo Benichic3318aa2017-09-05 13:25:07 +09002000 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2001 pw.println("total releases: " + mTotalWakelockReleases);
2002 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2003 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2004 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2005 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2006 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2007 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002008 mWakelockLogs.reverseDump(fd, pw, args);
2009 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 }
2012
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002013 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002014 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002015 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002016 if (officialNai != null && officialNai.equals(nai)) return true;
2017 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002018 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002019 " - " + nai);
2020 }
2021 return false;
2022 }
2023
Robert Greenwalt42acef32009-08-12 16:08:25 -07002024 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002025 private class NetworkStateTrackerHandler extends Handler {
2026 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002027 super(looper);
2028 }
2029
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002030 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002032 default:
2033 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002034 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002035 handleAsyncChannelHalfConnect(msg);
2036 break;
2037 }
2038 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2039 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2040 if (nai != null) nai.asyncChannel.disconnect();
2041 break;
2042 }
2043 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2044 handleAsyncChannelDisconnected(msg);
2045 break;
2046 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002047 }
2048 return true;
2049 }
2050
2051 private void maybeHandleNetworkAgentMessage(Message msg) {
2052 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2053 if (nai == null) {
2054 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002055 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002056 }
2057 return;
2058 }
2059
2060 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002061 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002062 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2063 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002064 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2065 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002066 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002067 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002068 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002069 break;
2070 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002071 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002072 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002073 break;
2074 }
2075 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002076 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002077 updateNetworkInfo(nai, info);
2078 break;
2079 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002080 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002081 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002082 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002083 break;
2084 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002085 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002086 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2087 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002088 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002089 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002090 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002091 break;
2092 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002093 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002094 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2095 break;
2096 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002097 }
2098 }
2099
2100 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2101 switch (msg.what) {
2102 default:
2103 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002104 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002105 final NetworkAgentInfo nai;
2106 synchronized (mNetworkForNetId) {
2107 nai = mNetworkForNetId.get(msg.arg2);
2108 }
Erik Klinea24d4592018-01-11 21:07:29 +09002109 if (nai == null) break;
2110
2111 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2112 final boolean wasValidated = nai.lastValidated;
2113 final boolean wasDefault = isDefaultNetwork(nai);
2114
2115 final PrivateDnsConfig privateDnsCfg = (msg.obj instanceof PrivateDnsConfig)
2116 ? (PrivateDnsConfig) msg.obj : null;
2117 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2118
2119 final boolean reevaluationRequired;
2120 final String logMsg;
2121 if (valid) {
2122 reevaluationRequired = updatePrivateDns(nai, privateDnsCfg);
2123 logMsg = (DBG && (privateDnsCfg != null))
2124 ? " with " + privateDnsCfg.toString() : "";
2125 } else {
2126 reevaluationRequired = false;
2127 logMsg = (DBG && !TextUtils.isEmpty(redirectUrl))
2128 ? " with redirect to " + redirectUrl : "";
2129 }
2130 if (DBG) {
2131 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2132 }
2133 // If there is a change in Private DNS configuration,
2134 // trigger reevaluation of the network to test it.
2135 if (reevaluationRequired) {
2136 nai.networkMonitor.sendMessage(
2137 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2138 break;
2139 }
2140 if (valid != nai.lastValidated) {
2141 if (wasDefault) {
2142 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2143 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002144 }
Erik Klinea24d4592018-01-11 21:07:29 +09002145 final int oldScore = nai.getCurrentScore();
2146 nai.lastValidated = valid;
2147 nai.everValidated |= valid;
2148 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2149 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2150 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2151 }
2152 updateInetCondition(nai);
2153 // Let the NetworkAgent know the state of its network
2154 Bundle redirectUrlBundle = new Bundle();
2155 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2156 nai.asyncChannel.sendMessage(
2157 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2158 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2159 0, redirectUrlBundle);
2160 if (wasValidated && !nai.lastValidated) {
2161 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002162 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002163 break;
2164 }
Paul Jensen869868be2014-05-15 10:33:05 -04002165 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002166 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002167 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002168 final NetworkAgentInfo nai;
2169 synchronized (mNetworkForNetId) {
2170 nai = mNetworkForNetId.get(netId);
2171 }
Calvin Onbe96da12016-10-11 15:10:46 -07002172 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002173 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002174 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002175 nai.lastCaptivePortalDetected = visible;
2176 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002177 if (nai.lastCaptivePortalDetected &&
2178 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2179 if (DBG) log("Avoiding captive portal network: " + nai.name());
2180 nai.asyncChannel.sendMessage(
2181 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2182 teardownUnneededNetwork(nai);
2183 break;
2184 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002185 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002186 }
2187 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002188 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002189 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002190 if (nai == null) {
2191 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2192 break;
2193 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002194 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002195 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002196 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002197 }
Paul Jensen869868be2014-05-15 10:33:05 -04002198 }
Paul Jensen869868be2014-05-15 10:33:05 -04002199 break;
2200 }
Erik Klinea24d4592018-01-11 21:07:29 +09002201 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
2202 final NetworkAgentInfo nai;
2203 synchronized (mNetworkForNetId) {
2204 nai = mNetworkForNetId.get(msg.arg2);
2205 }
2206 if (nai == null) break;
2207
2208 final PrivateDnsConfig cfg = (PrivateDnsConfig) msg.obj;
2209 final boolean reevaluationRequired = updatePrivateDns(nai, cfg);
2210 if (nai.lastValidated && reevaluationRequired) {
2211 nai.networkMonitor.sendMessage(
2212 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2213 }
2214 break;
2215 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002216 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002217 return true;
2218 }
2219
Calvin Onbe96da12016-10-11 15:10:46 -07002220 private int getCaptivePortalMode() {
2221 return Settings.Global.getInt(mContext.getContentResolver(),
2222 Settings.Global.CAPTIVE_PORTAL_MODE,
2223 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2224 }
2225
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002226 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2227 switch (msg.what) {
2228 default:
2229 return false;
2230 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2231 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2232 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2233 handleLingerComplete(nai);
2234 }
2235 break;
2236 }
2237 }
2238 return true;
2239 }
2240
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002241 @Override
2242 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002243 if (!maybeHandleAsyncChannelMessage(msg) &&
2244 !maybeHandleNetworkMonitorMessage(msg) &&
2245 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002246 maybeHandleNetworkAgentMessage(msg);
2247 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002248 }
2249 }
2250
Erik Klinea24d4592018-01-11 21:07:29 +09002251 private void handlePrivateDnsSettingsChanged() {
2252 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2253
2254 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2255 // Private DNS only ever applies to networks that might provide
2256 // Internet access and therefore also require validation.
2257 if (!NetworkMonitor.isValidationRequired(
2258 mDefaultRequest.networkCapabilities, nai.networkCapabilities)) {
2259 continue;
2260 }
2261
2262 // Notify the NetworkMonitor thread in case it needs to cancel or
2263 // schedule DNS resolutions. If a DNS resolution is required the
2264 // result will be sent back to us.
2265 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2266
2267 if (!cfg.inStrictMode()) {
2268 // No strict mode hostname DNS resolution needed, so just update
2269 // DNS settings directly. In opportunistic and "off" modes this
2270 // just reprograms netd with the network-supplied DNS servers
2271 // (and of course the boolean of whether or not to attempt TLS).
2272 //
2273 // TODO: Consider code flow parity with strict mode, i.e. having
2274 // NetworkMonitor relay the PrivateDnsConfig back to us and then
2275 // performing this call at that time.
2276 updatePrivateDns(nai, cfg);
2277 }
2278 }
2279 }
2280
2281 private boolean updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2282 final boolean reevaluationRequired = true;
2283 final boolean dontReevaluate = false;
2284
2285 final PrivateDnsConfig oldCfg = mDnsManager.updatePrivateDns(nai.network, newCfg);
2286 updateDnses(nai.linkProperties, null, nai.network.netId);
2287
2288 if (newCfg == null) {
2289 if (oldCfg == null) return dontReevaluate;
2290 return oldCfg.useTls ? reevaluationRequired : dontReevaluate;
2291 }
2292
2293 if (oldCfg == null) {
2294 return newCfg.useTls ? reevaluationRequired : dontReevaluate;
2295 }
2296
2297 if (oldCfg.useTls != newCfg.useTls) {
2298 return reevaluationRequired;
2299 }
2300
2301 if (newCfg.inStrictMode() && !Objects.equals(oldCfg.hostname, newCfg.hostname)) {
2302 return reevaluationRequired;
2303 }
2304
2305 return dontReevaluate;
2306 }
2307
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002308 private void updateLingerState(NetworkAgentInfo nai, long now) {
2309 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2310 // 2. If the network was lingering and there are now requests, unlinger it.
2311 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2312 // one lingered request, start lingering.
2313 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002314 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002315 if (DBG) log("Unlingering " + nai.name());
2316 nai.unlinger();
2317 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002318 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002319 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002320 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002321 nai.linger();
2322 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2323 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2324 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002325 }
2326
Robert Greenwalt7b816022014-04-18 15:25:25 -07002327 private void handleAsyncChannelHalfConnect(Message msg) {
2328 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002329 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002330 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2331 if (VDBG) log("NetworkFactory connected");
2332 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002333 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002334 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002335 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002336 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002337 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002338 }
2339 } else {
2340 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002341 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002342 }
2343 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2344 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2345 if (VDBG) log("NetworkAgent connected");
2346 // A network agent has requested a connection. Establish the connection.
2347 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2348 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2349 } else {
2350 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002351 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002352 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002353 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002354 synchronized (mNetworkForNetId) {
2355 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002356 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002357 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002358 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002359 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002360 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002361 }
2362 }
2363 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002364
Robert Greenwalt7b816022014-04-18 15:25:25 -07002365 private void handleAsyncChannelDisconnected(Message msg) {
2366 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2367 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002368 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002369 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002370 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002371 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002372 // TODO - if we move the logic to the network agent (have them disconnect
2373 // because they lost all their requests or because their score isn't good)
2374 // then they would disconnect organically, report their new state and then
2375 // disconnect the channel.
2376 if (nai.networkInfo.isConnected()) {
2377 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2378 null, null);
2379 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002380 final boolean wasDefault = isDefaultNetwork(nai);
2381 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002382 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002383 // Log default network disconnection before required book-keeping.
2384 // Let rematchAllNetworksAndRequests() below record a new default network event
2385 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2386 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002387 long now = SystemClock.elapsedRealtime();
2388 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002389 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002390 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002391 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2392 // by other networks that are already connected. Perhaps that can be done by
2393 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2394 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002395 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002396 mKeepaliveTracker.handleStopAllKeepalives(nai,
2397 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002398 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2399 // Disable wakeup packet monitoring for each interface.
2400 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2401 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002402 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002403 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002404 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002405 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002406 // Remove the NetworkAgent, but don't mark the netId as
2407 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002408 mNetworkForNetId.remove(nai.network.netId);
2409 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002410 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002411 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2412 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002413 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002414 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002415 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002416 sendUpdatedScoreToFactories(request, 0);
2417 }
2418 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002419 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002420 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002421 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002422 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002423 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002424 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002425 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002426 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002427 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002428 if (nai.created) {
2429 // Tell netd to clean up the configuration for this network
2430 // (routing rules, DNS, etc).
2431 // This may be slow as it requires a lot of netd shelling out to ip and
2432 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2433 // after we've rematched networks with requests which should make a potential
2434 // fallback network the default or requested a new network from the
2435 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2436 // long time.
2437 try {
2438 mNetd.removeNetwork(nai.network.netId);
2439 } catch (Exception e) {
2440 loge("Exception removing network: " + e);
2441 }
Erik Klinea24d4592018-01-11 21:07:29 +09002442 mDnsManager.removeNetwork(nai.network);
Paul Jensen62d30802015-06-17 14:42:30 -04002443 }
2444 synchronized (mNetworkForNetId) {
2445 mNetIdInUse.delete(nai.network.netId);
2446 }
2447 } else {
2448 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2449 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002450 }
2451 }
2452
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002453 // If this method proves to be too slow then we can maintain a separate
2454 // pendingIntent => NetworkRequestInfo map.
2455 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2456 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2457 Intent intent = pendingIntent.getIntent();
2458 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2459 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2460 if (existingPendingIntent != null &&
2461 existingPendingIntent.getIntent().filterEquals(intent)) {
2462 return entry.getValue();
2463 }
2464 }
2465 return null;
2466 }
2467
2468 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2469 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2470
2471 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2472 if (existingRequest != null) { // remove the existing request.
2473 if (DBG) log("Replacing " + existingRequest.request + " with "
2474 + nri.request + " because their intents matched.");
2475 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2476 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002477 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002478 }
2479
Erik Klineda4bfa82015-04-30 12:58:40 +09002480 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002481 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002482 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002483 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002484 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002485 if (nri.request.networkCapabilities.hasSignalStrength() &&
2486 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2487 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002488 }
2489 }
2490 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002491 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002492 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002493 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002494 }
2495 }
2496
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002497 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2498 int callingUid) {
2499 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2500 if (nri != null) {
2501 handleReleaseNetworkRequest(nri.request, callingUid);
2502 }
2503 }
2504
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002505 // Determines whether the network is the best (or could become the best, if it validated), for
2506 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2507 // on the value of reason:
2508 //
2509 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2510 // then it should be torn down.
2511 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2512 // then it should be lingered.
2513 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2514 final int numRequests;
2515 switch (reason) {
2516 case TEARDOWN:
2517 numRequests = nai.numRequestNetworkRequests();
2518 break;
2519 case LINGER:
2520 numRequests = nai.numForegroundNetworkRequests();
2521 break;
2522 default:
2523 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2524 return true;
2525 }
2526
2527 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002528 return false;
2529 }
Paul Jensene0988542015-06-25 15:30:08 -04002530 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002531 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2532 // Background requests don't affect lingering.
2533 continue;
2534 }
2535
Paul Jensene0988542015-06-25 15:30:08 -04002536 // If this Network is already the highest scoring Network for a request, or if
2537 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002538 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002539 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002540 // Note that this catches two important cases:
2541 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2542 // is currently satisfying the request. This is desirable when
2543 // cellular ends up validating but WiFi does not.
2544 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002545 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002546 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002547 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002548 nai.getCurrentScoreAsValidated())) {
2549 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002550 }
2551 }
Paul Jensene0988542015-06-25 15:30:08 -04002552 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002553 }
2554
Erik Klineacdd6392016-07-07 16:50:58 +09002555 private NetworkRequestInfo getNriForAppRequest(
2556 NetworkRequest request, int callingUid, String requestedOperation) {
2557 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2558
Robert Greenwalt9258c642014-03-26 16:47:06 -07002559 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002560 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002561 log(String.format("UID %d attempted to %s for unowned request %s",
2562 callingUid, requestedOperation, nri));
2563 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002564 }
Erik Klineacdd6392016-07-07 16:50:58 +09002565 }
2566
2567 return nri;
2568 }
2569
Erik Kline57faba92015-11-25 12:49:38 +09002570 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002571 if (mNetworkRequests.get(nri.request) == null) {
2572 return;
Erik Kline57faba92015-11-25 12:49:38 +09002573 }
Hugo Benichicd952782017-09-20 11:20:14 +09002574 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002575 return;
2576 }
2577 if (VDBG || (DBG && nri.request.isRequest())) {
2578 log("releasing " + nri.request + " (timeout)");
2579 }
2580 handleRemoveNetworkRequest(nri);
2581 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002582 }
2583
Erik Klineacdd6392016-07-07 16:50:58 +09002584 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002585 final NetworkRequestInfo nri =
2586 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2587 if (nri == null) {
2588 return;
Erik Kline57faba92015-11-25 12:49:38 +09002589 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002590 if (VDBG || (DBG && nri.request.isRequest())) {
2591 log("releasing " + nri.request + " (release request)");
2592 }
2593 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002594 }
Erik Klineacdd6392016-07-07 16:50:58 +09002595
Hugo Benichidba33db2017-03-23 22:40:44 +09002596 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002597 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002598 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002599
Erik Klineacdd6392016-07-07 16:50:58 +09002600 synchronized (mUidToNetworkRequestCount) {
2601 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2602 if (requests < 1) {
2603 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2604 nri.mUid);
2605 } else if (requests == 1) {
2606 mUidToNetworkRequestCount.removeAt(
2607 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2608 } else {
2609 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2610 }
2611 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002612
Erik Klineacdd6392016-07-07 16:50:58 +09002613 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2614 if (nri.request.isRequest()) {
2615 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002616 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002617 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002618 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002619 nai.removeRequest(nri.request.requestId);
2620 if (VDBG) {
2621 log(" Removing from current network " + nai.name() +
2622 ", leaving " + nai.numNetworkRequests() + " requests.");
2623 }
2624 // If there are still lingered requests on this network, don't tear it down,
2625 // but resume lingering instead.
2626 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002627 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002628 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2629 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002630 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002631 wasKept = true;
2632 }
Hugo Benichicd952782017-09-20 11:20:14 +09002633 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002634 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2635 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002636 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002637 }
Erik Klineacdd6392016-07-07 16:50:58 +09002638 }
2639
2640 // TODO: remove this code once we know that the Slog.wtf is never hit.
2641 //
2642 // Find all networks that are satisfying this request and remove the request
2643 // from their request lists.
2644 // TODO - it's my understanding that for a request there is only a single
2645 // network satisfying it, so this loop is wasteful
2646 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2647 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2648 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2649 otherNai.name() + ", but mNetworkAgentInfos says " +
2650 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002651 }
2652 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002653
Erik Klineacdd6392016-07-07 16:50:58 +09002654 // Maintain the illusion. When this request arrived, we might have pretended
2655 // that a network connected to serve it, even though the network was already
2656 // connected. Now that this request has gone away, we might have to pretend
2657 // that the network disconnected. LegacyTypeTracker will generate that
2658 // phantom disconnect for this type.
2659 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2660 boolean doRemove = true;
2661 if (wasKept) {
2662 // check if any of the remaining requests for this network are for the
2663 // same legacy type - if so, don't remove the nai
2664 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2665 NetworkRequest otherRequest = nai.requestAt(i);
2666 if (otherRequest.legacyType == nri.request.legacyType &&
2667 otherRequest.isRequest()) {
2668 if (DBG) log(" still have other legacy request - leaving");
2669 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002670 }
2671 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002672 }
2673
Erik Klineacdd6392016-07-07 16:50:58 +09002674 if (doRemove) {
2675 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002676 }
2677 }
Erik Klineacdd6392016-07-07 16:50:58 +09002678
2679 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2680 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2681 nri.request);
2682 }
2683 } else {
2684 // listens don't have a singular affectedNetwork. Check all networks to see
2685 // if this listen request applies and remove it.
2686 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2687 nai.removeRequest(nri.request.requestId);
2688 if (nri.request.networkCapabilities.hasSignalStrength() &&
2689 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2690 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2691 }
2692 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002693 }
2694 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002695
Lorenzo Colitti18660282016-07-04 12:55:44 +09002696 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002697 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2698 enforceConnectivityInternalPermission();
2699 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002700 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002701 }
2702
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002703 @Override
2704 public void setAvoidUnvalidated(Network network) {
2705 enforceConnectivityInternalPermission();
2706 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2707 }
2708
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002709 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2710 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2711 " accept=" + accept + " always=" + always);
2712
2713 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2714 if (nai == null) {
2715 // Nothing to do.
2716 return;
2717 }
2718
2719 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002720 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002721 return;
2722 }
2723
2724 if (!nai.networkMisc.explicitlySelected) {
2725 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2726 }
2727
2728 if (accept != nai.networkMisc.acceptUnvalidated) {
2729 int oldScore = nai.getCurrentScore();
2730 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002731 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002732 sendUpdatedScoreToFactories(nai);
2733 }
2734
2735 if (always) {
2736 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002737 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002738 }
2739
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002740 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002741 // Tell the NetworkAgent to not automatically reconnect to the network.
2742 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2743 // Teardown the nework.
2744 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002745 }
2746
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002747 }
2748
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002749 private void handleSetAvoidUnvalidated(Network network) {
2750 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2751 if (nai == null || nai.lastValidated) {
2752 // Nothing to do. The network either disconnected or revalidated.
2753 return;
2754 }
2755 if (!nai.avoidUnvalidated) {
2756 int oldScore = nai.getCurrentScore();
2757 nai.avoidUnvalidated = true;
2758 rematchAllNetworksAndRequests(nai, oldScore);
2759 sendUpdatedScoreToFactories(nai);
2760 }
2761 }
2762
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002763 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002764 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002765 mHandler.sendMessageDelayed(
2766 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2767 PROMPT_UNVALIDATED_DELAY_MS);
2768 }
2769
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002770 @Override
2771 public void startCaptivePortalApp(Network network) {
2772 enforceConnectivityInternalPermission();
2773 mHandler.post(() -> {
2774 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2775 if (nai == null) return;
2776 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2777 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2778 });
2779 }
2780
Hugo Benichic8e9e122016-09-14 23:23:08 +00002781 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002782 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002783 }
2784
Erik Kline065ab6e2016-10-02 18:02:14 +09002785 private void rematchForAvoidBadWifiUpdate() {
2786 rematchAllNetworksAndRequests(null, 0);
2787 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2788 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2789 sendUpdatedScoreToFactories(nai);
2790 }
2791 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002792 }
2793
Erik Kline065ab6e2016-10-02 18:02:14 +09002794 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002795 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002796 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002797 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002798 if (!configRestrict) {
2799 pw.println("Bad Wi-Fi avoidance: unrestricted");
2800 return;
2801 }
2802
2803 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2804 pw.increaseIndent();
2805 pw.println("Config restrict: " + configRestrict);
2806
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002807 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002808 String description;
2809 // Can't use a switch statement because strings are legal case labels, but null is not.
2810 if ("0".equals(value)) {
2811 description = "get stuck";
2812 } else if (value == null) {
2813 description = "prompt";
2814 } else if ("1".equals(value)) {
2815 description = "avoid";
2816 } else {
2817 description = value + " (?)";
2818 }
2819 pw.println("User setting: " + description);
2820 pw.println("Network overrides:");
2821 pw.increaseIndent();
2822 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2823 if (nai.avoidUnvalidated) {
2824 pw.println(nai.name());
2825 }
2826 }
2827 pw.decreaseIndent();
2828 pw.decreaseIndent();
2829 }
2830
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002831 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2832 final String action;
2833 switch (type) {
2834 case NO_INTERNET:
2835 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2836 break;
2837 case LOST_INTERNET:
2838 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2839 break;
2840 default:
2841 Slog.wtf(TAG, "Unknown notification type " + type);
2842 return;
2843 }
2844
2845 Intent intent = new Intent(action);
2846 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2847 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2848 intent.setClassName("com.android.settings",
2849 "com.android.settings.wifi.WifiNoInternetDialog");
2850
2851 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2852 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2853 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2854 }
2855
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002856 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002857 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002858 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2859
2860 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2861 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002862 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002863 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002864 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2865 return;
2866 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002867 showValidationNotification(nai, NotificationType.NO_INTERNET);
2868 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002869
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002870 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2871 NetworkCapabilities nc = nai.networkCapabilities;
2872 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002873
Erik Kline065ab6e2016-10-02 18:02:14 +09002874 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002875 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002876 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2877 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002878 }
2879
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002880 @Override
2881 public int getMultipathPreference(Network network) {
2882 enforceAccessPermission();
2883
2884 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002885 if (nai != null && nai.networkCapabilities
2886 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002887 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2888 }
2889
2890 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2891 }
2892
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002893 private class InternalHandler extends Handler {
2894 public InternalHandler(Looper looper) {
2895 super(looper);
2896 }
2897
2898 @Override
2899 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002900 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002901 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002902 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002903 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002904 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002905 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002906 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002907 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002908 break;
2909 }
Jason Monkdecd2952013-10-10 14:02:51 -04002910 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002911 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002912 break;
2913 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002914 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002915 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2916 break;
2917 }
2918 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2919 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002920 break;
2921 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002922 case EVENT_REGISTER_NETWORK_AGENT: {
2923 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2924 break;
2925 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002926 case EVENT_REGISTER_NETWORK_REQUEST:
2927 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002928 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002929 break;
2930 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002931 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2932 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002933 handleRegisterNetworkRequestWithIntent(msg);
2934 break;
2935 }
Erik Kline57faba92015-11-25 12:49:38 +09002936 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2937 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2938 handleTimedOutNetworkRequest(nri);
2939 break;
2940 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002941 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2942 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2943 break;
2944 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002945 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002946 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002947 break;
2948 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002949 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002950 Network network = (Network) msg.obj;
2951 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002952 break;
2953 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002954 case EVENT_SET_AVOID_UNVALIDATED: {
2955 handleSetAvoidUnvalidated((Network) msg.obj);
2956 break;
2957 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002958 case EVENT_PROMPT_UNVALIDATED: {
2959 handlePromptUnvalidated((Network) msg.obj);
2960 break;
2961 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002962 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2963 handleMobileDataAlwaysOn();
2964 break;
2965 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002966 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2967 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2968 mKeepaliveTracker.handleStartKeepalive(msg);
2969 break;
2970 }
2971 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2972 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2973 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2974 int slot = msg.arg1;
2975 int reason = msg.arg2;
2976 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2977 break;
2978 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002979 case EVENT_SYSTEM_READY: {
2980 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2981 nai.networkMonitor.systemReady = true;
2982 }
2983 break;
2984 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002985 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002986 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002987 break;
2988 }
Erik Klinea24d4592018-01-11 21:07:29 +09002989 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
2990 handlePrivateDnsSettingsChanged();
2991 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 }
2993 }
2994 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002995
2996 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002997 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002998 public int tether(String iface, String callerPkg) {
2999 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003000 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003001 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003002 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003003 } else {
3004 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3005 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003006 }
3007
3008 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003009 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003010 public int untether(String iface, String callerPkg) {
3011 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003012
3013 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003014 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003015 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003016 } else {
3017 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3018 }
3019 }
3020
3021 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003022 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003023 public int getLastTetherError(String iface) {
3024 enforceTetherAccessPermission();
3025
3026 if (isTetheringSupported()) {
3027 return mTethering.getLastTetherError(iface);
3028 } else {
3029 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3030 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003031 }
3032
3033 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003034 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003035 public String[] getTetherableUsbRegexs() {
3036 enforceTetherAccessPermission();
3037 if (isTetheringSupported()) {
3038 return mTethering.getTetherableUsbRegexs();
3039 } else {
3040 return new String[0];
3041 }
3042 }
3043
Lorenzo Colitti18660282016-07-04 12:55:44 +09003044 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003045 public String[] getTetherableWifiRegexs() {
3046 enforceTetherAccessPermission();
3047 if (isTetheringSupported()) {
3048 return mTethering.getTetherableWifiRegexs();
3049 } else {
3050 return new String[0];
3051 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003052 }
3053
Lorenzo Colitti18660282016-07-04 12:55:44 +09003054 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003055 public String[] getTetherableBluetoothRegexs() {
3056 enforceTetherAccessPermission();
3057 if (isTetheringSupported()) {
3058 return mTethering.getTetherableBluetoothRegexs();
3059 } else {
3060 return new String[0];
3061 }
3062 }
3063
Lorenzo Colitti18660282016-07-04 12:55:44 +09003064 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003065 public int setUsbTethering(boolean enable, String callerPkg) {
3066 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003067 if (isTetheringSupported()) {
3068 return mTethering.setUsbTethering(enable);
3069 } else {
3070 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3071 }
3072 }
3073
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003074 // TODO - move iface listing, queries, etc to new module
3075 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003076 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003077 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003078 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003079 return mTethering.getTetherableIfaces();
3080 }
3081
Lorenzo Colitti18660282016-07-04 12:55:44 +09003082 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003083 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003084 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003085 return mTethering.getTetheredIfaces();
3086 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003087
Lorenzo Colitti18660282016-07-04 12:55:44 +09003088 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003089 public String[] getTetheringErroredIfaces() {
3090 enforceTetherAccessPermission();
3091 return mTethering.getErroredIfaces();
3092 }
3093
Lorenzo Colitti18660282016-07-04 12:55:44 +09003094 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003095 public String[] getTetheredDhcpRanges() {
3096 enforceConnectivityInternalPermission();
3097 return mTethering.getTetheredDhcpRanges();
3098 }
3099
Udam Sainic3b640c2017-06-07 12:06:28 -07003100 @Override
3101 public boolean isTetheringSupported(String callerPkg) {
3102 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3103 return isTetheringSupported();
3104 }
3105
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003106 // if ro.tether.denied = true we default to no tethering
3107 // gservices could set the secure setting to 1 though to enable it on a build where it
3108 // had previously been turned off.
Udam Sainic3b640c2017-06-07 12:06:28 -07003109 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003110 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3111 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3112 Settings.Global.TETHER_SUPPORTED, defaultVal));
3113 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003114 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003115
3116 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3117 boolean adminUser = false;
3118 final long token = Binder.clearCallingIdentity();
3119 try {
3120 adminUser = mUserManager.isAdminUser();
3121 } finally {
3122 Binder.restoreCallingIdentity(token);
3123 }
3124
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003125 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003126 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003127
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003128 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003129 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3130 String callerPkg) {
3131 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003132 if (!isTetheringSupported()) {
3133 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3134 return;
3135 }
3136 mTethering.startTethering(type, receiver, showProvisioningUi);
3137 }
3138
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003139 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003140 public void stopTethering(int type, String callerPkg) {
3141 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003142 mTethering.stopTethering(type);
3143 }
3144
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003145 // Called when we lose the default network and have no replacement yet.
3146 // This will automatically be cleared after X seconds or a new default network
3147 // becomes CONNECTED, whichever happens first. The timer is started by the
3148 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003149 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003150 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003151 if (mNetTransitionWakeLock.isHeld()) {
3152 return;
3153 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003154 mNetTransitionWakeLock.acquire();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003155 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3156 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003157 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003158 mWakelockLogs.log("ACQUIRE for " + forWhom);
3159 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3160 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003161 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003162
Hugo Benichi4c31b342017-03-30 23:18:10 +09003163 // Called when we gain a new default network to release the network transition wakelock in a
3164 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3165 // message is cancelled.
3166 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003167 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003168 if (!mNetTransitionWakeLock.isHeld()) {
3169 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003170 }
3171 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003172 // Cancel self timeout on wakelock hold.
3173 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3174 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3175 mHandler.sendMessageDelayed(msg, 1000);
3176 }
3177
3178 // Called when either message of ensureNetworkTransitionWakelock or
3179 // scheduleReleaseNetworkTransitionWakelock is processed.
3180 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3181 String event = eventName(eventId);
3182 synchronized (this) {
3183 if (!mNetTransitionWakeLock.isHeld()) {
3184 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3185 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3186 return;
3187 }
3188 mNetTransitionWakeLock.release();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003189 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3190 mTotalWakelockDurationMs += lockDuration;
3191 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3192 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003193 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003194 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003195 }
3196
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003197 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003198 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003199 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003200 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003201 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003202 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003203 }
3204
Lorenzo Colitti18660282016-07-04 12:55:44 +09003205 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003206 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003207 enforceAccessPermission();
3208 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003209 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003210 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003211 mHandler.sendMessage(
3212 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3213 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003214
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003215 private void handleReportNetworkConnectivity(
3216 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003217 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003218 if (network == null) {
3219 nai = getDefaultNetwork();
3220 } else {
3221 nai = getNetworkAgentInfoForNetwork(network);
3222 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003223 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3224 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3225 return;
3226 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003227 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003228 if (hasConnectivity == nai.lastValidated) {
3229 return;
3230 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003231 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003232 int netid = nai.network.netId;
3233 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003234 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003235 // Validating a network that has not yet connected could result in a call to
3236 // rematchNetworkAndRequests() which is not meant to work on such networks.
3237 if (!nai.everConnected) {
3238 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003239 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003240 LinkProperties lp = getLinkProperties(nai);
3241 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3242 return;
3243 }
3244 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003245 }
3246
Paul Jensencee9b512015-05-06 07:32:40 -04003247 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003248 // this information is already available as a world read/writable jvm property
3249 // so this API change wouldn't have a benifit. It also breaks the passing
3250 // of proxy info to all the JVMs.
3251 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003252 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003253 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003254 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3255 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003256 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003257 }
3258
Lorenzo Colitti18660282016-07-04 12:55:44 +09003259 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003260 public ProxyInfo getProxyForNetwork(Network network) {
3261 if (network == null) return getDefaultProxy();
3262 final ProxyInfo globalProxy = getGlobalProxy();
3263 if (globalProxy != null) return globalProxy;
3264 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3265 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3266 // caller may not have.
3267 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3268 if (nai == null) return null;
3269 synchronized (nai) {
3270 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3271 if (proxyInfo == null) return null;
3272 return new ProxyInfo(proxyInfo);
3273 }
3274 }
3275
Paul Jensene0bef712014-12-10 15:12:18 -05003276 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3277 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3278 // proxy is null then there is no proxy in place).
3279 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3280 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3281 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3282 proxy = null;
3283 }
3284 return proxy;
3285 }
3286
3287 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3288 // better for determining if a new proxy broadcast is necessary:
3289 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3290 // avoid unnecessary broadcasts.
3291 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3292 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3293 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3294 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3295 // all set.
3296 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3297 a = canonicalizeProxyInfo(a);
3298 b = canonicalizeProxyInfo(b);
3299 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3300 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3301 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3302 }
3303
Jason Monk207900c2014-04-25 15:00:09 -04003304 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003305 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003306
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003307 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003308 if (proxyProperties == mGlobalProxy) return;
3309 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3310 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3311
3312 String host = "";
3313 int port = 0;
3314 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003315 String pacFileUrl = "";
3316 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003317 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003318 if (!proxyProperties.isValid()) {
3319 if (DBG)
3320 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3321 return;
3322 }
Jason Monk207900c2014-04-25 15:00:09 -04003323 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003324 host = mGlobalProxy.getHost();
3325 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003326 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003327 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003328 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003329 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003330 } else {
3331 mGlobalProxy = null;
3332 }
3333 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003334 final long token = Binder.clearCallingIdentity();
3335 try {
3336 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3337 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3338 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3339 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003340 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003341 } finally {
3342 Binder.restoreCallingIdentity(token);
3343 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003344
Jason Monkcf0f97a2014-10-02 15:39:38 -04003345 if (mGlobalProxy == null) {
3346 proxyProperties = mDefaultProxy;
3347 }
3348 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003349 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003350 }
3351
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003352 private void loadGlobalProxy() {
3353 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003354 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3355 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3356 String exclList = Settings.Global.getString(res,
3357 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003358 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3359 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003360 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003361 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003362 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003363 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003364 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003365 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003366 if (!proxyProperties.isValid()) {
3367 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3368 return;
3369 }
3370
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003371 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003372 mGlobalProxy = proxyProperties;
3373 }
3374 }
3375 }
3376
Jason Monk207900c2014-04-25 15:00:09 -04003377 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003378 // this information is already available as a world read/writable jvm property
3379 // so this API change wouldn't have a benifit. It also breaks the passing
3380 // of proxy info to all the JVMs.
3381 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003382 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003383 return mGlobalProxy;
3384 }
3385 }
3386
Jason Monk207900c2014-04-25 15:00:09 -04003387 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003388 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003389 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003390 proxy = null;
3391 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003392 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003393 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003394 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003395 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003396 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3397 return;
3398 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003399
3400 // This call could be coming from the PacManager, containing the port of the local
3401 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3402 // global (to get the correct local port), and send a broadcast.
3403 // TODO: Switch PacManager to have its own message to send back rather than
3404 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003405 if ((mGlobalProxy != null) && (proxy != null)
3406 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003407 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3408 mGlobalProxy = proxy;
3409 sendProxyBroadcast(mGlobalProxy);
3410 return;
3411 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003412 mDefaultProxy = proxy;
3413
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003414 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003415 if (!mDefaultProxyDisabled) {
3416 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003417 }
3418 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003419 }
3420
Paul Jensene0bef712014-12-10 15:12:18 -05003421 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3422 // This method gets called when any network changes proxy, but the broadcast only ever contains
3423 // the default proxy (even if it hasn't changed).
3424 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3425 // world where an app might be bound to a non-default network.
3426 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3427 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3428 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3429
3430 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3431 sendProxyBroadcast(getDefaultProxy());
3432 }
3433 }
3434
Robert Greenwalt434203a2010-10-11 16:00:27 -07003435 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003436 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3437 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003438 if (!TextUtils.isEmpty(proxy)) {
3439 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003440 if (data.length == 0) {
3441 return;
3442 }
3443
Robert Greenwalt434203a2010-10-11 16:00:27 -07003444 String proxyHost = data[0];
3445 int proxyPort = 8080;
3446 if (data.length > 1) {
3447 try {
3448 proxyPort = Integer.parseInt(data[1]);
3449 } catch (NumberFormatException e) {
3450 return;
3451 }
3452 }
Jason Monk207900c2014-04-25 15:00:09 -04003453 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003454 setGlobalProxy(p);
3455 }
3456 }
3457
Jason Monk207900c2014-04-25 15:00:09 -04003458 private void sendProxyBroadcast(ProxyInfo proxy) {
3459 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003460 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003461 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003462 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003463 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3464 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003465 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003466 final long ident = Binder.clearCallingIdentity();
3467 try {
3468 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3469 } finally {
3470 Binder.restoreCallingIdentity(ident);
3471 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003472 }
3473
3474 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003475 final private HashMap<Uri, Integer> mUriEventMap;
3476 final private Context mContext;
3477 final private Handler mHandler;
3478
3479 SettingsObserver(Context context, Handler handler) {
3480 super(null);
3481 mUriEventMap = new HashMap<Uri, Integer>();
3482 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003483 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003484 }
3485
Erik Klineda4bfa82015-04-30 12:58:40 +09003486 void observe(Uri uri, int what) {
3487 mUriEventMap.put(uri, what);
3488 final ContentResolver resolver = mContext.getContentResolver();
3489 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003490 }
3491
3492 @Override
3493 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003494 Slog.wtf(TAG, "Should never be reached.");
3495 }
3496
3497 @Override
3498 public void onChange(boolean selfChange, Uri uri) {
3499 final Integer what = mUriEventMap.get(uri);
3500 if (what != null) {
3501 mHandler.obtainMessage(what.intValue()).sendToTarget();
3502 } else {
3503 loge("No matching event to send for URI=" + uri);
3504 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003505 }
3506 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003507
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003508 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003509 Slog.d(TAG, s);
3510 }
3511
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003512 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003513 Slog.e(TAG, s);
3514 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003515
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003516 private static void loge(String s, Throwable t) {
3517 Slog.e(TAG, s, t);
3518 }
3519
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003520 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003521 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003522 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3523 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3524 *
3525 * @param oldPackage Package name of the application which currently controls VPN, which will
3526 * be replaced. If there is no such application, this should should either be
3527 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3528 * @param newPackage Package name of the application which should gain control of VPN, or
3529 * {@code null} to disable.
3530 * @param userId User for whom to prepare the new VPN.
3531 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003532 * @hide
3533 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003534 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003535 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3536 int userId) {
3537 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003538
Hugo Benichi20035e02017-04-26 14:53:28 +09003539 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003540 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003541 Vpn vpn = mVpns.get(userId);
3542 if (vpn != null) {
3543 return vpn.prepare(oldPackage, newPackage);
3544 } else {
3545 return false;
3546 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003547 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003548 }
3549
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003550 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003551 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3552 * This method is used by system-privileged apps.
3553 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3554 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3555 *
3556 * @param packageName The package for which authorization state should change.
3557 * @param userId User for whom {@code packageName} is installed.
3558 * @param authorized {@code true} if this app should be able to start a VPN connection without
3559 * explicit user approval, {@code false} if not.
3560 *
Jeff Davidson05542602014-08-11 14:07:27 -07003561 * @hide
3562 */
3563 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003564 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3565 enforceCrossUserPermission(userId);
3566
Hugo Benichi20035e02017-04-26 14:53:28 +09003567 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003568 Vpn vpn = mVpns.get(userId);
3569 if (vpn != null) {
3570 vpn.setPackageAuthorization(packageName, authorized);
3571 }
Jeff Davidson05542602014-08-11 14:07:27 -07003572 }
3573 }
3574
3575 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003576 * Configure a TUN interface and return its file descriptor. Parameters
3577 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003578 * and not available in ConnectivityManager. Permissions are checked in
3579 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003580 * @hide
3581 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003582 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003583 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003584 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003585 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003586 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003587 return mVpns.get(user).establish(config);
3588 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003589 }
3590
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003591 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003592 * Start legacy VPN, controlling native daemons as needed. Creates a
3593 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003594 */
3595 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003596 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003597 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003598 final LinkProperties egress = getActiveLinkProperties();
3599 if (egress == null) {
3600 throw new IllegalStateException("Missing active network connection");
3601 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003602 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003603 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003604 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3605 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003606 }
3607
3608 /**
3609 * Return the information of the ongoing legacy VPN. This method is used
3610 * by VpnSettings and not available in ConnectivityManager. Permissions
3611 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003612 */
3613 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003614 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3615 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003616
Hugo Benichi20035e02017-04-26 14:53:28 +09003617 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003618 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003619 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003620 }
3621
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003622 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003623 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3624 * and not available in ConnectivityManager.
3625 */
3626 @Override
3627 public VpnInfo[] getAllVpnInfo() {
3628 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003629 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003630 if (mLockdownEnabled) {
3631 return new VpnInfo[0];
3632 }
3633
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003634 List<VpnInfo> infoList = new ArrayList<>();
3635 for (int i = 0; i < mVpns.size(); i++) {
3636 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3637 if (info != null) {
3638 infoList.add(info);
3639 }
3640 }
3641 return infoList.toArray(new VpnInfo[infoList.size()]);
3642 }
3643 }
3644
3645 /**
3646 * @return VPN information for accounting, or null if we can't retrieve all required
3647 * information, e.g primary underlying iface.
3648 */
3649 @Nullable
3650 private VpnInfo createVpnInfo(Vpn vpn) {
3651 VpnInfo info = vpn.getVpnInfo();
3652 if (info == null) {
3653 return null;
3654 }
3655 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3656 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3657 // the underlyingNetworks list.
3658 if (underlyingNetworks == null) {
3659 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3660 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3661 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3662 }
3663 } else if (underlyingNetworks.length > 0) {
3664 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3665 if (linkProperties != null) {
3666 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3667 }
3668 }
3669 return info.primaryUnderlyingIface == null ? null : info;
3670 }
3671
3672 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003673 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3674 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003675 * Permissions are checked in Vpn class.
3676 * @hide
3677 */
3678 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003679 public VpnConfig getVpnConfig(int userId) {
3680 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003681 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003682 Vpn vpn = mVpns.get(userId);
3683 if (vpn != null) {
3684 return vpn.getVpnConfig();
3685 } else {
3686 return null;
3687 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003688 }
3689 }
3690
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003691 @Override
3692 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003693 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3694 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3695 return false;
3696 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003697
Hugo Benichi69744342017-11-27 10:57:16 +09003698 synchronized (mVpns) {
3699 // Tear down existing lockdown if profile was removed
3700 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3701 if (mLockdownEnabled) {
3702 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3703 if (profileTag == null) {
3704 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3705 return false;
3706 }
3707 String profileName = new String(profileTag);
3708 final VpnProfile profile = VpnProfile.decode(
3709 profileName, mKeyStore.get(Credentials.VPN + profileName));
3710 if (profile == null) {
3711 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3712 setLockdownTracker(null);
3713 return true;
3714 }
3715 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003716 Vpn vpn = mVpns.get(user);
3717 if (vpn == null) {
3718 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3719 return false;
3720 }
3721 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003722 } else {
3723 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003724 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003725 }
3726
3727 return true;
3728 }
3729
3730 /**
3731 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3732 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3733 */
Hugo Benichi69744342017-11-27 10:57:16 +09003734 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003735 private void setLockdownTracker(LockdownVpnTracker tracker) {
3736 // Shutdown any existing tracker
3737 final LockdownVpnTracker existing = mLockdownTracker;
3738 mLockdownTracker = null;
3739 if (existing != null) {
3740 existing.shutdown();
3741 }
3742
Robin Leec3736bc2017-03-10 16:19:54 +00003743 if (tracker != null) {
3744 mLockdownTracker = tracker;
3745 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003746 }
3747 }
3748
Hugo Benichi69744342017-11-27 10:57:16 +09003749 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003750 private void throwIfLockdownEnabled() {
3751 if (mLockdownEnabled) {
3752 throw new IllegalStateException("Unavailable in lockdown mode");
3753 }
3754 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003755
Robin Lee244ce8e2016-01-05 18:03:46 +00003756 /**
Robin Lee17e61832016-05-09 13:46:28 +01003757 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3758 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003759 *
Robin Lee17e61832016-05-09 13:46:28 +01003760 * @return {@code true} if the service was started, the service was already connected, or there
3761 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003762 */
Robin Lee17e61832016-05-09 13:46:28 +01003763 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003764 synchronized (mVpns) {
3765 Vpn vpn = mVpns.get(userId);
3766 if (vpn == null) {
3767 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3768 // exists already.
3769 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3770 return false;
3771 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003772
Robin Lee812800c2016-05-13 15:38:08 +01003773 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003774 }
3775 }
3776
3777 @Override
Charles Hea0a87e82017-05-15 17:07:18 +01003778 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3779 enforceSettingsPermission();
3780 enforceCrossUserPermission(userId);
3781
3782 synchronized (mVpns) {
3783 Vpn vpn = mVpns.get(userId);
3784 if (vpn == null) {
3785 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3786 return false;
3787 }
3788 return vpn.isAlwaysOnPackageSupported(packageName);
3789 }
3790 }
3791
3792 @Override
Robin Leedc679712016-05-03 13:23:03 +01003793 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003794 enforceConnectivityInternalPermission();
3795 enforceCrossUserPermission(userId);
3796
Robin Lee244ce8e2016-01-05 18:03:46 +00003797 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003798 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3799 if (LockdownVpnTracker.isEnabled()) {
3800 return false;
3801 }
3802
Robin Lee244ce8e2016-01-05 18:03:46 +00003803 Vpn vpn = mVpns.get(userId);
3804 if (vpn == null) {
3805 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3806 return false;
3807 }
Robin Lee17e61832016-05-09 13:46:28 +01003808 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003809 return false;
3810 }
Robin Lee17e61832016-05-09 13:46:28 +01003811 if (!startAlwaysOnVpn(userId)) {
3812 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003813 return false;
3814 }
3815 }
3816 return true;
3817 }
3818
3819 @Override
3820 public String getAlwaysOnVpnPackage(int userId) {
3821 enforceConnectivityInternalPermission();
3822 enforceCrossUserPermission(userId);
3823
3824 synchronized (mVpns) {
3825 Vpn vpn = mVpns.get(userId);
3826 if (vpn == null) {
3827 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3828 return null;
3829 }
3830 return vpn.getAlwaysOnPackage();
3831 }
3832 }
3833
Wink Savilleab9321d2013-06-29 21:10:57 -07003834 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003835 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003836 // TODO: Remove? Any reason to trigger a provisioning check?
3837 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003838 }
3839
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003840 /** Location to an updatable file listing carrier provisioning urls.
3841 * An example:
3842 *
3843 * <?xml version="1.0" encoding="utf-8"?>
3844 * <provisioningUrls>
3845 * <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 -07003846 * </provisioningUrls>
3847 */
3848 private static final String PROVISIONING_URL_PATH =
3849 "/data/misc/radio/provisioning_urls.xml";
3850 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003851
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003852 /** XML tag for root element. */
3853 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3854 /** XML tag for individual url */
3855 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003856 /** XML attribute for mcc */
3857 private static final String ATTR_MCC = "mcc";
3858 /** XML attribute for mnc */
3859 private static final String ATTR_MNC = "mnc";
3860
Paul Jensen434dde82015-06-11 09:43:30 -04003861 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003862 FileReader fileReader = null;
3863 XmlPullParser parser = null;
3864 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003865
3866 try {
3867 fileReader = new FileReader(mProvisioningUrlFile);
3868 parser = Xml.newPullParser();
3869 parser.setInput(fileReader);
3870 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3871
3872 while (true) {
3873 XmlUtils.nextElement(parser);
3874
3875 String element = parser.getName();
3876 if (element == null) break;
3877
Paul Jensen434dde82015-06-11 09:43:30 -04003878 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003879 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3880 try {
3881 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3882 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3883 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3884 parser.next();
3885 if (parser.getEventType() == XmlPullParser.TEXT) {
3886 return parser.getText();
3887 }
3888 }
3889 }
3890 } catch (NumberFormatException e) {
3891 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3892 }
3893 }
3894 }
3895 return null;
3896 } catch (FileNotFoundException e) {
3897 loge("Carrier Provisioning Urls file not found");
3898 } catch (XmlPullParserException e) {
3899 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3900 } catch (IOException e) {
3901 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3902 } finally {
3903 if (fileReader != null) {
3904 try {
3905 fileReader.close();
3906 } catch (IOException e) {}
3907 }
3908 }
3909 return null;
3910 }
3911
Wink Saville42d4f082013-07-20 20:31:59 -07003912 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003913 public String getMobileProvisioningUrl() {
3914 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003915 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003916 if (TextUtils.isEmpty(url)) {
3917 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003918 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003919 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003920 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003921 }
Wink Saville8cf35602013-07-10 23:00:07 -07003922 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003923 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003924 String phoneNumber = mTelephonyManager.getLine1Number();
3925 if (TextUtils.isEmpty(phoneNumber)) {
3926 phoneNumber = "0000000000";
3927 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003928 url = String.format(url,
3929 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3930 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003931 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003932 }
3933
Wink Savilleab9321d2013-06-29 21:10:57 -07003934 return url;
3935 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003936
Wink Saville948282b2013-08-29 08:55:16 -07003937 @Override
3938 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003939 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003940 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003941 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3942 return;
3943 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003944 final long ident = Binder.clearCallingIdentity();
3945 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003946 // Concatenate the range of types onto the range of NetIDs.
3947 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3948 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003949 } finally {
3950 Binder.restoreCallingIdentity(ident);
3951 }
Wink Saville948282b2013-08-29 08:55:16 -07003952 }
Wink Saville7788c612013-08-29 14:57:08 -07003953
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003954 @Override
3955 public void setAirplaneMode(boolean enable) {
3956 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003957 final long ident = Binder.clearCallingIdentity();
3958 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003959 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003960 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003961 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3962 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003963 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003964 } finally {
3965 Binder.restoreCallingIdentity(ident);
3966 }
3967 }
3968
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003969 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003970 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003971 Vpn userVpn = mVpns.get(userId);
3972 if (userVpn != null) {
3973 loge("Starting user already has a VPN");
3974 return;
3975 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003976 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003977 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09003978 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3979 updateLockdownVpn();
3980 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003981 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003982 }
3983
3984 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003985 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003986 Vpn userVpn = mVpns.get(userId);
3987 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003988 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003989 return;
3990 }
Robin Lee17e61832016-05-09 13:46:28 +01003991 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003992 mVpns.delete(userId);
3993 }
3994 }
3995
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003996 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003997 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003998 final int vpnsSize = mVpns.size();
3999 for (int i = 0; i < vpnsSize; i++) {
4000 Vpn vpn = mVpns.valueAt(i);
4001 vpn.onUserAdded(userId);
4002 }
4003 }
4004 }
4005
4006 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004007 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004008 final int vpnsSize = mVpns.size();
4009 for (int i = 0; i < vpnsSize; i++) {
4010 Vpn vpn = mVpns.valueAt(i);
4011 vpn.onUserRemoved(userId);
4012 }
4013 }
4014 }
4015
Robin Lee89e7a692016-02-29 14:38:17 +00004016 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004017 synchronized (mVpns) {
4018 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4019 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4020 updateLockdownVpn();
4021 } else {
4022 startAlwaysOnVpn(userId);
4023 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004024 }
4025 }
4026
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004027 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4028 @Override
4029 public void onReceive(Context context, Intent intent) {
4030 final String action = intent.getAction();
4031 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4032 if (userId == UserHandle.USER_NULL) return;
4033
Robin Lee323f29d2016-05-04 16:38:06 +01004034 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004035 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004036 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004037 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004038 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4039 onUserAdded(userId);
4040 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4041 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004042 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4043 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004044 }
4045 }
4046 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004047
Robin Lee95204e02017-01-27 11:59:22 +00004048 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4049 @Override
4050 public void onReceive(Context context, Intent intent) {
4051 // Try creating lockdown tracker, since user present usually means
4052 // unlocked keystore.
4053 updateLockdownVpn();
4054 mContext.unregisterReceiver(this);
4055 }
4056 };
4057
Robert Greenwalta67be032014-05-16 15:49:14 -07004058 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4059 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004060 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4061 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004062
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004063 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4064 // Map from UID to number of NetworkRequests that UID has filed.
4065 @GuardedBy("mUidToNetworkRequestCount")
4066 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4067
Robert Greenwalta67be032014-05-16 15:49:14 -07004068 private static class NetworkFactoryInfo {
4069 public final String name;
4070 public final Messenger messenger;
4071 public final AsyncChannel asyncChannel;
4072
4073 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4074 this.name = name;
4075 this.messenger = messenger;
4076 this.asyncChannel = asyncChannel;
4077 }
4078 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004079
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004080 private void ensureNetworkRequestHasType(NetworkRequest request) {
4081 if (request.type == NetworkRequest.Type.NONE) {
4082 throw new IllegalArgumentException(
4083 "All NetworkRequests in ConnectivityService must have a type");
4084 }
4085 }
4086
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004087 /**
4088 * Tracks info about the requester.
4089 * Also used to notice when the calling process dies so we can self-expire
4090 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004091 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004092 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004093 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004094 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004095 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004096 final int mPid;
4097 final int mUid;
4098 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004099
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004100 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004101 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004102 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004103 mPendingIntent = pi;
4104 messenger = null;
4105 mBinder = null;
4106 mPid = getCallingPid();
4107 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004108 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004109 }
4110
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004111 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004112 super();
4113 messenger = m;
4114 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004115 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004116 mBinder = binder;
4117 mPid = getCallingPid();
4118 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004119 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004120 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004121
4122 try {
4123 mBinder.linkToDeath(this, 0);
4124 } catch (RemoteException e) {
4125 binderDied();
4126 }
4127 }
4128
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004129 private void enforceRequestCountLimit() {
4130 synchronized (mUidToNetworkRequestCount) {
4131 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4132 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004133 throw new ServiceSpecificException(
4134 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004135 }
4136 mUidToNetworkRequestCount.put(mUid, networkRequests);
4137 }
4138 }
4139
Robert Greenwalt9258c642014-03-26 16:47:06 -07004140 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004141 if (mBinder != null) {
4142 mBinder.unlinkToDeath(this, 0);
4143 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004144 }
4145
4146 public void binderDied() {
4147 log("ConnectivityService NetworkRequestInfo binderDied(" +
4148 request + ", " + mBinder + ")");
4149 releaseNetworkRequest(request);
4150 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004151
4152 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004153 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004154 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004155 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004156 }
4157
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004158 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4159 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4160 if (badCapability != null) {
4161 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004162 }
4163 }
4164
Erik Kline9d598e12015-07-13 16:37:51 +09004165 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004166 final SortedSet<Integer> thresholds = new TreeSet();
4167 synchronized (nai) {
4168 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4169 if (nri.request.networkCapabilities.hasSignalStrength() &&
4170 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4171 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4172 }
4173 }
4174 }
Erik Kline9d598e12015-07-13 16:37:51 +09004175 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004176 }
4177
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004178 private void updateSignalStrengthThresholds(
4179 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4180 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004181 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004182 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4183
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004184 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004185 String detail;
4186 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4187 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4188 } else {
4189 detail = reason;
4190 }
4191 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4192 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4193 }
4194
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004195 nai.asyncChannel.sendMessage(
4196 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004197 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004198 }
4199
Etan Cohen859748f2017-04-03 17:42:34 -07004200 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4201 if (nc == null) {
4202 return;
4203 }
4204 NetworkSpecifier ns = nc.getNetworkSpecifier();
4205 if (ns == null) {
4206 return;
4207 }
4208 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4209 ns.assertValidFromUid(Binder.getCallingUid());
4210 }
4211
Robert Greenwalt9258c642014-03-26 16:47:06 -07004212 @Override
4213 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004214 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004215 final NetworkRequest.Type type = (networkCapabilities == null)
4216 ? NetworkRequest.Type.TRACK_DEFAULT
4217 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004218 // If the requested networkCapabilities is null, take them instead from
4219 // the default network request. This allows callers to keep track of
4220 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004221 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004222 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004223 networkCapabilities.removeCapability(NET_CAPABILITY_NOT_VPN);
Erik Klinea2d29402016-03-16 15:31:39 +09004224 enforceAccessPermission();
4225 } else {
4226 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4227 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004228 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4229 // of the app when the request is filed, but we never change the request if the app
4230 // changes network state. http://b/29964605
4231 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004232 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004233 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004234 // Set the UID range for this request to the single UID of the requester, or to an empty
4235 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004236 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4237 // are no visible methods to set the UIDs, an app could use reflection to try and get
4238 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004239 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004240
Etan Cohenba07c8c2017-02-05 10:42:27 -08004241 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004242 throw new IllegalArgumentException("Bad timeout specified");
4243 }
Etan Cohen859748f2017-04-03 17:42:34 -07004244 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004245
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004246 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004247 nextNetworkRequestId(), type);
4248 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004249 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004250
4251 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004252 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004253 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004254 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004255 }
4256 return networkRequest;
4257 }
4258
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004259 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004260 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004261 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004262 } else {
4263 enforceChangePermission();
4264 }
4265 }
4266
fenglub15e72b2015-03-20 11:29:56 -07004267 @Override
fengludb571472015-04-21 17:12:05 -07004268 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004269 enforceAccessPermission();
4270 NetworkAgentInfo nai = null;
4271 if (network == null) {
4272 return false;
4273 }
4274 synchronized (mNetworkForNetId) {
4275 nai = mNetworkForNetId.get(network.netId);
4276 }
4277 if (nai != null) {
4278 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4279 return true;
4280 }
4281 return false;
4282 }
4283
Felipe Lemeee27cab2016-06-20 16:36:29 -07004284 private boolean isSystem(int uid) {
4285 return uid < Process.FIRST_APPLICATION_UID;
4286 }
fenglub15e72b2015-03-20 11:29:56 -07004287
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004288 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004289 final int uid = Binder.getCallingUid();
4290 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004291 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004292 return;
4293 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004294 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4295 // Policy already enforced.
4296 return;
4297 }
4298 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4299 // If UID is restricted, don't allow them to bring up metered APNs.
4300 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004301 }
4302 }
4303
Robert Greenwalt9258c642014-03-26 16:47:06 -07004304 @Override
4305 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4306 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004307 checkNotNull(operation, "PendingIntent cannot be null.");
4308 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4309 enforceNetworkRequestPermissions(networkCapabilities);
4310 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004311 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004312 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004313 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004314
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004315 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004316 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4317 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004318 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004319 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4320 nri));
4321 return networkRequest;
4322 }
4323
Jeremy Joslin79294842014-12-03 17:15:28 -08004324 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4325 mHandler.sendMessageDelayed(
4326 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4327 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4328 }
4329
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004330 @Override
4331 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004332 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004333 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4334 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004335 }
4336
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004337 // In order to implement the compatibility measure for pre-M apps that call
4338 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4339 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4340 // This ensures it has permission to do so.
4341 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4342 if (nc == null) {
4343 return false;
4344 }
4345 int[] transportTypes = nc.getTransportTypes();
4346 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4347 return false;
4348 }
4349 try {
4350 mContext.enforceCallingOrSelfPermission(
4351 android.Manifest.permission.ACCESS_WIFI_STATE,
4352 "ConnectivityService");
4353 } catch (SecurityException e) {
4354 return false;
4355 }
4356 return true;
4357 }
4358
Robert Greenwalt9258c642014-03-26 16:47:06 -07004359 @Override
4360 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4361 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004362 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4363 enforceAccessPermission();
4364 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004365
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004366 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004367 restrictRequestUidsForCaller(nc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004368 if (!ConnectivityManager.checkChangePermission(mContext)) {
4369 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4370 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4371 // onLost and onAvailable callbacks when networks move in and out of the background.
4372 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4373 // can't request networks.
4374 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4375 }
Etan Cohen859748f2017-04-03 17:42:34 -07004376 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004377
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004378 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004379 NetworkRequest.Type.LISTEN);
4380 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004381 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004382
4383 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4384 return networkRequest;
4385 }
4386
4387 @Override
4388 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4389 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004390 checkNotNull(operation, "PendingIntent cannot be null.");
4391 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4392 enforceAccessPermission();
4393 }
Etan Cohen859748f2017-04-03 17:42:34 -07004394 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004395
Chalard Jeandda156a2018-01-10 21:19:32 +09004396 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004397 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004398
4399 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004400 NetworkRequest.Type.LISTEN);
4401 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004402 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004403
4404 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004405 }
4406
Erik Klineacdd6392016-07-07 16:50:58 +09004407 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004408 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004409 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004410 mHandler.sendMessage(mHandler.obtainMessage(
4411 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004412 }
4413
4414 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004415 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004416 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004417 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4418 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004419 }
4420
Robert Greenwalta67be032014-05-16 15:49:14 -07004421 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004422 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004423 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4424 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4425 }
4426
4427 @Override
4428 public void unregisterNetworkFactory(Messenger messenger) {
4429 enforceConnectivityInternalPermission();
4430 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4431 }
4432
4433 private void handleUnregisterNetworkFactory(Messenger messenger) {
4434 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4435 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004436 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004437 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004438 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004439 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004440 }
4441
Robert Greenwalt7b816022014-04-18 15:25:25 -07004442 /**
4443 * NetworkAgentInfo supporting a request by requestId.
4444 * These have already been vetted (their Capabilities satisfy the request)
4445 * and the are the highest scored network available.
4446 * the are keyed off the Requests requestId.
4447 */
Hugo Benichicd952782017-09-20 11:20:14 +09004448 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4449 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004450 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4451 new SparseArray<NetworkAgentInfo>();
4452
Paul Jensen31a94f42015-02-13 14:18:39 -05004453 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4454 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004455 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4456 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004457 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4458 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4459 // there may not be a strict 1:1 correlation between the two.
4460 @GuardedBy("mNetworkForNetId")
4461 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004462
Robert Greenwalt7b816022014-04-18 15:25:25 -07004463 // NetworkAgentInfo keyed off its connecting messenger
4464 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004465 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004466 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4467 new HashMap<Messenger, NetworkAgentInfo>();
4468
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004469 @GuardedBy("mBlockedAppUids")
4470 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4471
Paul Jensen2c311d62014-11-17 12:34:51 -05004472 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004473 private final NetworkRequest mDefaultRequest;
4474
Erik Klineda4bfa82015-04-30 12:58:40 +09004475 // Request used to optionally keep mobile data active even when higher
4476 // priority networks like Wi-Fi are active.
4477 private final NetworkRequest mDefaultMobileDataRequest;
4478
Hugo Benichicd952782017-09-20 11:20:14 +09004479 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4480 synchronized (mNetworkForRequestId) {
4481 return mNetworkForRequestId.get(requestId);
4482 }
4483 }
4484
4485 private void clearNetworkForRequest(int requestId) {
4486 synchronized (mNetworkForRequestId) {
4487 mNetworkForRequestId.remove(requestId);
4488 }
4489 }
4490
4491 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4492 synchronized (mNetworkForRequestId) {
4493 mNetworkForRequestId.put(requestId, nai);
4494 }
4495 }
4496
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004497 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004498 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004499 }
4500
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004501 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004502 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004503 }
4504
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004505 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4506 return nri.request.requestId == mDefaultRequest.requestId;
4507 }
4508
Paul Jensen31a94f42015-02-13 14:18:39 -05004509 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004510 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004511 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004512 enforceConnectivityInternalPermission();
4513
Rubin Xu1bb5c082017-09-05 18:40:49 +01004514 LinkProperties lp = new LinkProperties(linkProperties);
4515 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004516 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4517 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004518 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004519 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004520 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004521 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004522 // Make sure the network capabilities reflect what the agent info says.
4523 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004524 synchronized (this) {
4525 nai.networkMonitor.systemReady = mSystemReady;
4526 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004527 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4528 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004529 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004530 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004531 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004532 }
4533
4534 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4535 if (VDBG) log("Got NetworkAgent Messenger");
4536 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004537 synchronized (mNetworkForNetId) {
4538 mNetworkForNetId.put(na.network.netId, na);
4539 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004540 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4541 NetworkInfo networkInfo = na.networkInfo;
4542 na.networkInfo = null;
4543 updateNetworkInfo(na, networkInfo);
Chalard Jeanf213ca12018-01-16 18:43:05 +09004544 updateUids(na, null, na.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004545 }
4546
4547 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4548 LinkProperties newLp = networkAgent.linkProperties;
4549 int netId = networkAgent.network.netId;
4550
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004551 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4552 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004553 if (networkAgent.clatd != null) {
4554 networkAgent.clatd.fixupLinkProperties(oldLp);
4555 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004556
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004557 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004558 updateMtu(newLp, oldLp);
4559 // TODO - figure out what to do for clat
4560// for (LinkProperties lp : newLp.getStackedLinks()) {
4561// updateMtu(lp, null);
4562// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004563 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004564
Erik Kline94887872016-04-05 13:30:49 +09004565 updateRoutes(newLp, oldLp, netId);
4566 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004567
Hugo Benichib577d652017-06-27 15:13:20 +09004568 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004569 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004570 if (isDefaultNetwork(networkAgent)) {
4571 handleApplyDefaultProxy(newLp.getHttpProxy());
4572 } else {
4573 updateProxy(newLp, oldLp, networkAgent);
4574 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004575 // TODO - move this check to cover the whole function
4576 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004577 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004578 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4579 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004580
4581 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004582 }
4583
Joel Scherpelz668370b2017-06-08 15:35:21 +09004584 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004585 // Marks are only available on WiFi interaces. Checking for
4586 // marks on unsupported interfaces is harmless.
4587 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4588 return;
4589 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004590
Joel Scherpelz668370b2017-06-08 15:35:21 +09004591 int mark = mContext.getResources().getInteger(
4592 com.android.internal.R.integer.config_networkWakeupPacketMark);
4593 int mask = mContext.getResources().getInteger(
4594 com.android.internal.R.integer.config_networkWakeupPacketMask);
4595
4596 // Mask/mark of zero will not detect anything interesting.
4597 // Don't install rules unless both values are nonzero.
4598 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004599 return;
4600 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004601
4602 final String prefix = "iface:" + iface;
4603 try {
4604 if (add) {
4605 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4606 } else {
4607 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4608 }
4609 } catch (Exception e) {
4610 loge("Exception modifying wakeup packet monitoring: " + e);
4611 }
4612
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004613 }
4614
4615 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4616 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004617 CompareResult<String> interfaceDiff = new CompareResult<String>(
4618 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4619 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004620 for (String iface : interfaceDiff.added) {
4621 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004622 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004623 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004624 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004625 } catch (Exception e) {
4626 loge("Exception adding interface: " + e);
4627 }
4628 }
4629 for (String iface : interfaceDiff.removed) {
4630 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004631 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004632 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004633 mNetd.removeInterfaceFromNetwork(iface, netId);
4634 } catch (Exception e) {
4635 loge("Exception removing interface: " + e);
4636 }
4637 }
4638 }
4639
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004640 /**
4641 * Have netd update routes from oldLp to newLp.
4642 * @return true if routes changed between oldLp and newLp
4643 */
4644 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004645 // Compare the route diff to determine which routes should be added and removed.
4646 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4647 oldLp != null ? oldLp.getAllRoutes() : null,
4648 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004649
4650 // add routes before removing old in case it helps with continuous connectivity
4651
4652 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4653 for (RouteInfo route : routeDiff.added) {
4654 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004655 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004656 try {
4657 mNetd.addRoute(netId, route);
4658 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004659 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4660 loge("Exception in addRoute for non-gateway: " + e);
4661 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004662 }
4663 }
4664 for (RouteInfo route : routeDiff.added) {
4665 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004666 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004667 try {
4668 mNetd.addRoute(netId, route);
4669 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004670 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4671 loge("Exception in addRoute for gateway: " + e);
4672 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004673 }
4674 }
4675
4676 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004677 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004678 try {
4679 mNetd.removeRoute(netId, route);
4680 } catch (Exception e) {
4681 loge("Exception in removeRoute: " + e);
4682 }
4683 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004684 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004685 }
Erik Kline41368502015-06-17 13:19:54 +09004686
Erik Kline94887872016-04-05 13:30:49 +09004687 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4688 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4689 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004690 }
Erik Kline94887872016-04-05 13:30:49 +09004691
Erik Kline1742fe12017-12-13 19:40:49 +09004692 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4693 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4694
Erik Klinea24d4592018-01-11 21:07:29 +09004695 if (DBG) {
4696 final Collection<InetAddress> dnses = newLp.getDnsServers();
4697 log("Setting DNS servers for network " + netId + " to " + dnses);
4698 }
Erik Kline94887872016-04-05 13:30:49 +09004699 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004700 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004701 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004702 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004703 }
Erik Kline4edba012017-04-07 15:29:29 +09004704 }
4705
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004706 private String getNetworkPermission(NetworkCapabilities nc) {
4707 // TODO: make these permission strings AIDL constants instead.
4708 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4709 return NetworkManagementService.PERMISSION_SYSTEM;
4710 }
4711 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4712 return NetworkManagementService.PERMISSION_NETWORK;
4713 }
4714 return null;
4715 }
4716
Paul Jensen3d194ea2015-06-16 14:27:36 -04004717 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004718 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4719 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4720 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004721 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004722 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004723 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004724 if (nai.everConnected &&
4725 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4726 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichibae105a2017-08-16 13:19:04 +09004727 // does not cause any request (that is not a listen) currently matching that agent to
4728 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004729 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichieae7a222017-07-25 11:40:56 +09004730 if (!TextUtils.isEmpty(diff)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004731 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichieae7a222017-07-25 11:40:56 +09004732 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004733 }
4734
Paul Jensen3d194ea2015-06-16 14:27:36 -04004735 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004736 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004737 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004738 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004739 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004740 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004741 }
Paul Jensene0988542015-06-25 15:30:08 -04004742 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004743 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004744 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004745 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004746 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004747 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004748 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004749 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004750 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004751 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004752 if (nai.isSuspended()) {
4753 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4754 } else {
4755 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4756 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004757
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004758 return newNc;
4759 }
4760
4761 /**
4762 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4763 *
4764 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4765 * capabilities we manage and store in {@code nai}, such as validated status and captive
4766 * portal status)
4767 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4768 * potentially triggers rematches.
4769 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4770 * change.)
4771 *
4772 * @param oldScore score of the network before any of the changes that prompted us
4773 * to call this function.
4774 * @param nai the network having its capabilities updated.
4775 * @param nc the new network capabilities.
4776 */
4777 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4778 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4779
4780 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004781
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004782 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004783 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004784 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004785 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004786 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004787 } catch (RemoteException e) {
4788 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004789 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004790 }
4791
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004792 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004793 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004794 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004795 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004796 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004797
Chalard Jeanf213ca12018-01-16 18:43:05 +09004798 updateUids(nai, prevNc, newNc);
4799
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004800 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004801 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4802 // the change we're processing can't affect any requests, it can only affect the listens
4803 // on this network. We might have been called by rematchNetworkAndRequests when a
4804 // network changed foreground state.
4805 processListenRequests(nai, true);
4806 } else {
4807 // If the requestable capabilities have changed or the score changed, we can't have been
4808 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004809 rematchAllNetworksAndRequests(nai, oldScore);
4810 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004811 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004812
4813 // Report changes that are interesting for network statistics tracking.
4814 if (prevNc != null) {
4815 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004816 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004817 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004818 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004819 if (meteredChanged || roamingChanged) {
4820 notifyIfacesChangedForNetworkStats();
4821 }
4822 }
4823
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004824 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004825 // Tell VPNs about updated capabilities, since they may need to
4826 // bubble those changes through.
4827 synchronized (mVpns) {
4828 for (int i = 0; i < mVpns.size(); i++) {
4829 final Vpn vpn = mVpns.valueAt(i);
4830 vpn.updateCapabilities();
4831 }
4832 }
4833 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004834 }
4835
Chalard Jeanf213ca12018-01-16 18:43:05 +09004836 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4837 NetworkCapabilities newNc) {
4838 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4839 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4840 if (null == prevRanges) prevRanges = new ArraySet<>();
4841 if (null == newRanges) newRanges = new ArraySet<>();
4842 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4843
4844 prevRanges.removeAll(newRanges);
4845 newRanges.removeAll(prevRangesCopy);
4846
4847 try {
4848 if (!newRanges.isEmpty()) {
4849 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4850 newRanges.toArray(addedRangesArray);
4851 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4852 }
4853 if (!prevRanges.isEmpty()) {
4854 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4855 prevRanges.toArray(removedRangesArray);
4856 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4857 }
4858 } catch (Exception e) {
4859 // Never crash!
4860 loge("Exception in updateUids: " + e);
4861 }
4862 }
4863
Hugo Benichief502882017-09-01 01:23:32 +00004864 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
4865 if (mNetworkForNetId.get(nai.network.netId) != nai) {
4866 // Ignore updates for disconnected networks
4867 return;
4868 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004869 // newLp is already a defensive copy.
4870 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004871 if (VDBG) {
4872 log("Update of LinkProperties for " + nai.name() +
4873 "; created=" + nai.created +
4874 "; everConnected=" + nai.everConnected);
4875 }
4876 LinkProperties oldLp = nai.linkProperties;
4877 synchronized (nai) {
4878 nai.linkProperties = newLp;
4879 }
4880 if (nai.everConnected) {
4881 updateLinkProperties(nai, oldLp);
4882 }
4883 }
4884
Paul Jensenc8b9a742014-09-30 15:37:41 -04004885 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004886 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4887 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004888 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004889 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004890 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4891 }
4892 }
4893
Robert Greenwalt7b816022014-04-18 15:25:25 -07004894 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4895 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004896 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004897 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4898 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004899 }
4900 }
4901
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004902 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4903 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004904 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004905 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004906 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4907 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004908 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004909 sendIntent(nri.mPendingIntent, intent);
4910 }
4911 // else not handled
4912 }
4913
4914 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4915 mPendingIntentWakeLock.acquire();
4916 try {
4917 if (DBG) log("Sending " + pendingIntent);
4918 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4919 } catch (PendingIntent.CanceledException e) {
4920 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4921 mPendingIntentWakeLock.release();
4922 releasePendingNetworkRequest(pendingIntent);
4923 }
4924 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4925 }
4926
4927 @Override
4928 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4929 String resultData, Bundle resultExtras) {
4930 if (DBG) log("Finished sending " + pendingIntent);
4931 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004932 // Release with a delay so the receiving client has an opportunity to put in its
4933 // own request.
4934 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004935 }
4936
Chalard Jeanf19db372018-01-26 19:24:40 +09004937 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004938 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004939 if (nri.messenger == null) {
4940 return; // Default request has no msgr
4941 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004942 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004943 // TODO: check if defensive copies of data is needed.
4944 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004945 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004946 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4947 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004948 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004949 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09004950 case ConnectivityManager.CALLBACK_AVAILABLE: {
4951 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
4952 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
4953 break;
4954 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004955 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004956 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004957 break;
4958 }
4959 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09004960 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb552c462018-02-21 18:43:54 +09004961 final NetworkCapabilities nc = networkCapabilitiesWithoutUidsUnlessAllowed(
4962 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09004963 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004964 break;
4965 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004966 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004967 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004968 break;
4969 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004970 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004971 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004972 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004973 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004974 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004975 String notification = ConnectivityManager.getCallbackName(notificationType);
4976 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004977 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004978 nri.messenger.send(msg);
4979 } catch (RemoteException e) {
4980 // may occur naturally in the race of binder death.
4981 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4982 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004983 }
4984
Hugo Benichidba33db2017-03-23 22:40:44 +09004985 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4986 bundle.putParcelable(t.getClass().getSimpleName(), t);
4987 }
4988
Paul Jensenc8b9a742014-09-30 15:37:41 -04004989 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004990 if (nai.numRequestNetworkRequests() != 0) {
4991 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4992 NetworkRequest nr = nai.requestAt(i);
4993 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004994 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004995 loge("Dead network still had at least " + nr);
4996 break;
4997 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004998 }
4999 nai.asyncChannel.disconnect();
5000 }
5001
Robert Greenwalt7b816022014-04-18 15:25:25 -07005002 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5003 if (oldNetwork == null) {
5004 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5005 return;
5006 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005007 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005008
5009 // If we get here it means that the last linger timeout for this network expired. So there
5010 // must be no other active linger timers, and we must stop lingering.
5011 oldNetwork.clearLingerState();
5012
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005013 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005014 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005015 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005016 } else {
5017 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005018 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5019 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005020 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005021 }
5022
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005023 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005024 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005025 setupDataActivityTracking(newNetwork);
5026 try {
5027 mNetd.setDefaultNetId(newNetwork.network.netId);
5028 } catch (Exception e) {
5029 loge("Exception setting default network :" + e);
5030 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005031
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005032 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005033 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005034 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005035 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005036 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005037 }
5038
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005039 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005040 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5041 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5042 NetworkRequest nr = nri.request;
5043 if (!nr.isListen()) continue;
5044 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5045 nai.removeRequest(nri.request.requestId);
5046 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5047 }
5048 }
5049
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005050 if (capabilitiesChanged) {
5051 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5052 }
5053
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005054 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5055 NetworkRequest nr = nri.request;
5056 if (!nr.isListen()) continue;
5057 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5058 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005059 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005060 }
5061 }
5062 }
5063
Paul Jensen2161a8e2014-09-11 11:00:39 -04005064 // Handles a network appearing or improving its score.
5065 //
5066 // - Evaluates all current NetworkRequests that can be
5067 // satisfied by newNetwork, and reassigns to newNetwork
5068 // any such requests for which newNetwork is the best.
5069 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005070 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005071 // needed. A network is needed if it is the best network for
5072 // one or more NetworkRequests, or if it is a VPN.
5073 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005074 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005075 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005076 //
5077 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5078 // networks that have no chance (i.e. even if validated)
5079 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005080 //
5081 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5082 // it does not remove NetworkRequests that other Networks could better satisfy.
5083 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5084 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5085 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005086 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005087 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005088 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5089 // performed to tear down unvalidated networks that have no chance (i.e. even if
5090 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005091 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005092 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005093 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005094 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005095 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005096 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005097
5098 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5099 final int score = newNetwork.getCurrentScore();
5100
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005101 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005102
Paul Jensen2161a8e2014-09-11 11:00:39 -04005103 // Find and migrate to this Network any NetworkRequests for
5104 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07005105 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04005106 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005107 NetworkCapabilities nc = newNetwork.networkCapabilities;
5108 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005109 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005110 // Process requests in the first pass and listens in the second pass. This allows us to
5111 // change a network's capabilities depending on which requests it has. This is only
5112 // correct if the change in capabilities doesn't affect whether the network satisfies
5113 // requests or not, and doesn't affect the network's score.
5114 if (nri.request.isListen()) continue;
5115
Hugo Benichicd952782017-09-20 11:20:14 +09005116 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005117 final boolean satisfies = newNetwork.satisfies(nri.request);
5118 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005119 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005120 log("Network " + newNetwork.name() + " was already satisfying" +
5121 " request " + nri.request.requestId + ". No change.");
5122 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005123 keep = true;
5124 continue;
5125 }
5126
5127 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005128 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005129 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005130 // next check if it's better than any current network we're using for
5131 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005132 if (VDBG) {
5133 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005134 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005135 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005136 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005137 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005138 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005139 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005140 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005141 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005142 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005143 affectedNetworks.add(currentNetwork);
5144 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005145 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005146 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005147 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005148 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005149 if (!newNetwork.addRequest(nri.request)) {
5150 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5151 }
5152 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005153 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005154 // Tell NetworkFactories about the new score, so they can stop
5155 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005156 // TODO - this could get expensive if we have alot of requests for this
5157 // network. Think about if there is a way to reduce this. Push
5158 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005159 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005160 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005161 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005162 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005163 if (currentNetwork != null) {
5164 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5165 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005166 }
5167 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005168 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005169 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5170 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005171 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005172 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5173 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5174 // This means this code doesn't have to handle the case where "currentNetwork" no
5175 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5176 if (DBG) {
5177 log("Network " + newNetwork.name() + " stopped satisfying" +
5178 " request " + nri.request.requestId);
5179 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005180 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005181 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005182 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005183 sendUpdatedScoreToFactories(nri.request, 0);
5184 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005185 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5186 newNetwork.name() +
5187 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005188 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005189 // TODO: Technically, sending CALLBACK_LOST here is
5190 // incorrect if there is a replacement network currently
5191 // connected that can satisfy nri, which is a request
5192 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005193 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5194 // so this code is only incorrect for a network that loses
5195 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005196 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005197 }
5198 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005199 if (isNewDefault) {
5200 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005201 makeDefault(newNetwork);
5202 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005203 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005204 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005205 // Have a new default network, release the transition wakelock in
5206 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005207 }
5208
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005209 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5210 Slog.wtf(TAG, String.format(
5211 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005212 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005213 }
5214 if (newNetwork.getCurrentScore() != score) {
5215 Slog.wtf(TAG, String.format(
5216 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005217 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005218 }
5219
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005220 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005221 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5222 // If the network went from background to foreground or vice versa, we need to update
5223 // its foreground state. It is safe to do this after rematching the requests because
5224 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5225 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005226 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005227 } else {
5228 processListenRequests(newNetwork, false);
5229 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005230
Paul Jensencf4c2c62015-07-01 14:16:32 -04005231 // do this after the default net is switched, but
5232 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005233 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005234
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005235 // Linger any networks that are no longer needed. This should be done after sending the
5236 // available callback for newNetwork.
5237 for (NetworkAgentInfo nai : affectedNetworks) {
5238 updateLingerState(nai, now);
5239 }
5240 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5241 // does not need to be done in any particular order.
5242 updateLingerState(newNetwork, now);
5243
Paul Jensencf4c2c62015-07-01 14:16:32 -04005244 if (isNewDefault) {
5245 // Maintain the illusion: since the legacy API only
5246 // understands one network at a time, we must pretend
5247 // that the current default network disconnected before
5248 // the new one connected.
5249 if (oldDefaultNetwork != null) {
5250 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5251 oldDefaultNetwork, true);
5252 }
5253 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5254 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5255 notifyLockdownVpn(newNetwork);
5256 }
5257
Robert Greenwalt7b816022014-04-18 15:25:25 -07005258 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005259 // Notify battery stats service about this network, both the normal
5260 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005261 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005262 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005263 final IBatteryStats bs = BatteryStatsService.getService();
5264 final int type = newNetwork.networkInfo.getType();
5265
5266 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5267 bs.noteNetworkInterfaceType(baseIface, type);
5268 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5269 final String stackedIface = stacked.getInterfaceName();
5270 bs.noteNetworkInterfaceType(stackedIface, type);
5271 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5272 }
5273 } catch (RemoteException ignored) {
5274 }
5275
Robert Greenwalt152ed372014-12-17 17:19:53 -08005276 // This has to happen after the notifyNetworkCallbacks as that tickles each
5277 // ConnectivityManager instance so that legacy requests correctly bind dns
5278 // requests to this network. The legacy users are listening for this bcast
5279 // and will generally do a dns request so they can ensureRouteToHost and if
5280 // they do that before the callbacks happen they'll use the default network.
5281 //
5282 // TODO: Is there still a race here? We send the broadcast
5283 // after sending the callback, but if the app can receive the
5284 // broadcast before the callback, it might still break.
5285 //
5286 // This *does* introduce a race where if the user uses the new api
5287 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5288 // they may get old info. Reverse this after the old startUsing api is removed.
5289 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005290 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5291 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005292 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005293 // legacy type tracker filters out repeat adds
5294 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5295 }
5296 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005297
5298 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5299 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5300 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5301 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5302 if (newNetwork.isVPN()) {
5303 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5304 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005305 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005306 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5307 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005308 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005309 if (nai.getLingerExpiry() > 0) {
5310 // This network has active linger timers and no requests, but is not
5311 // lingering. Linger it.
5312 //
5313 // One way (the only way?) this can happen if this network is unvalidated
5314 // and became unneeded due to another network improving its score to the
5315 // point where this network will no longer be able to satisfy any requests
5316 // even if it validates.
5317 updateLingerState(nai, now);
5318 } else {
5319 if (DBG) log("Reaping " + nai.name());
5320 teardownUnneededNetwork(nai);
5321 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005322 }
5323 }
5324 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005325 }
5326
Paul Jensen1c7ba022015-06-16 14:27:36 -04005327 /**
5328 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5329 * being disconnected.
5330 * @param changed If only one Network's score or capabilities have been modified since the last
5331 * time this function was called, pass this Network in this argument, otherwise pass
5332 * null.
5333 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5334 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5335 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5336 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5337 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005338 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005339 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005340 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5341 // to avoid the slowness. It is not simply enough to process just "changed", for
5342 // example in the case where "changed"'s score decreases and another network should begin
5343 // satifying a NetworkRequest that "changed" currently satisfies.
5344
5345 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5346 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5347 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005348 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005349 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005350 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005351 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005352 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5353 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5354 // Rematch higher scoring networks first to prevent requests first matching a lower
5355 // scoring network and then a higher scoring network, which could produce multiple
5356 // callbacks and inadvertently unlinger networks.
5357 Arrays.sort(nais);
5358 for (NetworkAgentInfo nai : nais) {
5359 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005360 // Only reap the last time through the loop. Reaping before all rematching
5361 // is complete could incorrectly teardown a network that hasn't yet been
5362 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005363 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005364 : ReapUnvalidatedNetworks.REAP,
5365 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005366 }
5367 }
5368 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005369
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005370 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005371 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005372 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005373 // For now only update icons for default connection.
5374 // TODO: Update WiFi and cellular icons separately. b/17237507
5375 if (!isDefaultNetwork(nai)) return;
5376
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005377 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005378 // Don't repeat publish.
5379 if (newInetCondition == mDefaultInetConditionPublished) return;
5380
5381 mDefaultInetConditionPublished = newInetCondition;
5382 sendInetConditionBroadcast(nai.networkInfo);
5383 }
5384
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005385 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005386 synchronized (mVpns) {
5387 if (mLockdownTracker != null) {
5388 if (nai != null && nai.isVPN()) {
5389 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5390 } else {
5391 mLockdownTracker.onNetworkInfoChanged();
5392 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005393 }
5394 }
5395 }
5396
Robert Greenwalt7b816022014-04-18 15:25:25 -07005397 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005398 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005399 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005400 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005401 synchronized (networkAgent) {
5402 oldInfo = networkAgent.networkInfo;
5403 networkAgent.networkInfo = newInfo;
5404 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005405 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005406
Robert Greenwalt7b816022014-04-18 15:25:25 -07005407 if (DBG) {
5408 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5409 (oldInfo == null ? "null" : oldInfo.getState()) +
5410 " to " + state);
5411 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005412
Robin Lee585e2482016-05-01 23:00:00 +01005413 if (!networkAgent.created
5414 && (state == NetworkInfo.State.CONNECTED
5415 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005416
5417 // A network that has just connected has zero requests and is thus a foreground network.
5418 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5419
Robert Greenwalt7b816022014-04-18 15:25:25 -07005420 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005421 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005422 if (networkAgent.isVPN()) {
5423 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005424 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5425 (networkAgent.networkMisc == null ||
5426 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005427 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005428 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005429 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005430 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005431 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005432 loge("Error creating network " + networkAgent.network.netId + ": "
5433 + e.getMessage());
5434 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005435 }
Paul Jenseneec75412014-08-04 12:21:19 -04005436 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005437 }
5438
5439 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5440 networkAgent.everConnected = true;
5441
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09005442 if (networkAgent.linkProperties == null) {
5443 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
5444 }
5445
Robert Greenwalt7b816022014-04-18 15:25:25 -07005446 updateLinkProperties(networkAgent, null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005447
Paul Jensenca8f16a2014-05-09 12:47:55 -04005448 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005449 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005450
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005451 if (networkAgent.isVPN()) {
5452 // Temporarily disable the default proxy (not global).
5453 synchronized (mProxyLock) {
5454 if (!mDefaultProxyDisabled) {
5455 mDefaultProxyDisabled = true;
5456 if (mGlobalProxy == null && mDefaultProxy != null) {
5457 sendProxyBroadcast(null);
5458 }
5459 }
5460 }
5461 // TODO: support proxy per network.
5462 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005463
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005464 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5465 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5466 // capabilities, so it only needs to be done once on initial connect, not every time the
5467 // network's capabilities change. Note that we do this before rematching the network,
5468 // so we could decide to tear it down immediately afterwards. That's fine though - on
5469 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5470 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005471 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005472
Paul Jensen2161a8e2014-09-11 11:00:39 -04005473 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005474 final long now = SystemClock.elapsedRealtime();
5475 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005476
5477 // This has to happen after matching the requests, because callbacks are just requests.
5478 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005479 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005480 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005481 if (networkAgent.isVPN()) {
5482 synchronized (mProxyLock) {
5483 if (mDefaultProxyDisabled) {
5484 mDefaultProxyDisabled = false;
5485 if (mGlobalProxy == null && mDefaultProxy != null) {
5486 sendProxyBroadcast(mDefaultProxy);
5487 }
5488 }
5489 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005490 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005491 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005492 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5493 state == NetworkInfo.State.SUSPENDED) {
5494 // going into or coming out of SUSPEND: rescore and notify
5495 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005496 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005497 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005498 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5499 networkAgent.networkCapabilities);
5500 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5501 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005502 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5503 ConnectivityManager.CALLBACK_SUSPENDED :
5504 ConnectivityManager.CALLBACK_RESUMED));
5505 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005506 }
5507 }
5508
Robert Greenwaltac96c522014-06-03 16:43:57 -07005509 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005510 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005511 if (score < 0) {
5512 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5513 "). Bumping score to min of 0");
5514 score = 0;
5515 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005516
Paul Jensen2161a8e2014-09-11 11:00:39 -04005517 final int oldScore = nai.getCurrentScore();
5518 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005519
Paul Jensen85cf78e2015-06-25 13:25:07 -04005520 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005521
Paul Jensenc8b9a742014-09-30 15:37:41 -04005522 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005523 }
5524
Erik Klinec75d4fa2017-02-15 19:59:17 +09005525 // Notify only this one new request of the current state. Transfer all the
5526 // current state by calling NetworkCapabilities and LinkProperties callbacks
5527 // so that callers can be guaranteed to have as close to atomicity in state
5528 // transfer as can be supported by this current API.
5529 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005530 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005531 if (nri.mPendingIntent != null) {
5532 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5533 // Attempt no subsequent state pushes where intents are involved.
5534 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005535 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005536
5537 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005538 }
5539
Robert Greenwalt8d482522015-06-24 13:23:42 -07005540 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005541 // The NetworkInfo we actually send out has no bearing on the real
5542 // state of affairs. For example, if the default connection is mobile,
5543 // and a request for HIPRI has just gone away, we need to pretend that
5544 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5545 // the state to DISCONNECTED, even though the network is of type MOBILE
5546 // and is still connected.
5547 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5548 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005549 if (state != DetailedState.DISCONNECTED) {
5550 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005551 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005552 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005553 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005554 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5555 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5556 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5557 if (info.isFailover()) {
5558 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5559 nai.networkInfo.setFailover(false);
5560 }
5561 if (info.getReason() != null) {
5562 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5563 }
5564 if (info.getExtraInfo() != null) {
5565 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5566 }
5567 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005568 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005569 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005570 if (newDefaultAgent != null) {
5571 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5572 newDefaultAgent.networkInfo);
5573 } else {
5574 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5575 }
5576 }
5577 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5578 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005579 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005580 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005581 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005582 }
5583 }
5584 }
5585
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005586 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005587 if (VDBG) {
5588 String notification = ConnectivityManager.getCallbackName(notifyType);
5589 log("notifyType " + notification + " for " + networkAgent.name());
5590 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005591 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5592 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005593 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5594 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005595 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5596 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005597 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005598 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005599 } else {
5600 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5601 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005602 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005603 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005604
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005605 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5606 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5607 }
5608
Jeff Sharkey69736342014-12-08 14:50:12 -08005609 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005610 * Returns the list of all interfaces that could be used by network traffic that does not
5611 * explicitly specify a network. This includes the default network, but also all VPNs that are
5612 * currently connected.
5613 *
5614 * Must be called on the handler thread.
5615 */
5616 private Network[] getDefaultNetworks() {
5617 ArrayList<Network> defaultNetworks = new ArrayList<>();
5618 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5619 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5620 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5621 defaultNetworks.add(nai.network);
5622 }
5623 }
5624 return defaultNetworks.toArray(new Network[0]);
5625 }
5626
5627 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005628 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5629 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005630 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005631 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005632 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005633 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005634 } catch (Exception ignored) {
5635 }
5636 }
5637
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005638 @Override
5639 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005640 int user = UserHandle.getUserId(Binder.getCallingUid());
5641 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005642 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005643 return mVpns.get(user).addAddress(address, prefixLength);
5644 }
5645 }
5646
5647 @Override
5648 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005649 int user = UserHandle.getUserId(Binder.getCallingUid());
5650 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005651 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005652 return mVpns.get(user).removeAddress(address, prefixLength);
5653 }
5654 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005655
5656 @Override
5657 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005658 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005659 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005660 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005661 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005662 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005663 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005664 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005665 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005666 }
5667 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005668 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005669
5670 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005671 public String getCaptivePortalServerUrl() {
Udam Sainic3b640c2017-06-07 12:06:28 -07005672 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005673 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005674 }
5675
5676 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005677 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5678 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5679 enforceKeepalivePermission();
5680 mKeepaliveTracker.startNattKeepalive(
5681 getNetworkAgentInfoForNetwork(network),
5682 intervalSeconds, messenger, binder,
5683 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5684 }
5685
5686 @Override
5687 public void stopKeepalive(Network network, int slot) {
5688 mHandler.sendMessage(mHandler.obtainMessage(
5689 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5690 }
5691
5692 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005693 public void factoryReset() {
5694 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005695
5696 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5697 return;
5698 }
5699
Robin Lee3b3dd942015-05-12 18:14:58 +01005700 final int userId = UserHandle.getCallingUserId();
5701
Stuart Scottf1fb3972015-04-02 18:00:02 -07005702 // Turn airplane mode off
5703 setAirplaneMode(false);
5704
Stuart Scotte3e314d2015-04-20 14:07:45 -07005705 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5706 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005707 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005708 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005709 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005710 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005711 }
5712
Stuart Scotte3e314d2015-04-20 14:07:45 -07005713 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005714 // Remove always-on package
5715 synchronized (mVpns) {
5716 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5717 if (alwaysOnPackage != null) {
5718 setAlwaysOnVpnPackage(userId, null, false);
5719 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5720 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005721
Hugo Benichi69744342017-11-27 10:57:16 +09005722 // Turn Always-on VPN off
5723 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5724 final long ident = Binder.clearCallingIdentity();
5725 try {
5726 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5727 mLockdownEnabled = false;
5728 setLockdownTracker(null);
5729 } finally {
5730 Binder.restoreCallingIdentity(ident);
5731 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005732 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005733
Hugo Benichi69744342017-11-27 10:57:16 +09005734 // Turn VPN off
5735 VpnConfig vpnConfig = getVpnConfig(userId);
5736 if (vpnConfig != null) {
5737 if (vpnConfig.legacy) {
5738 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5739 } else {
5740 // Prevent this app (packagename = vpnConfig.user) from initiating
5741 // VPN connections in the future without user intervention.
5742 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005743
Hugo Benichi69744342017-11-27 10:57:16 +09005744 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5745 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005746 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005747 }
5748 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005749
5750 Settings.Global.putString(mContext.getContentResolver(),
5751 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005752 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005753
5754 @VisibleForTesting
5755 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5756 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5757 return new NetworkMonitor(context, handler, nai, defaultRequest);
5758 }
Erik Kline48f12f22016-04-14 17:30:59 +09005759
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005760 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005761 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5762 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005763 }
5764
5765 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005766 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5767 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5768 }
5769
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005770 @VisibleForTesting
5771 public boolean hasService(String name) {
5772 return ServiceManager.checkService(name) != null;
5773 }
5774
Hugo Benichi64901e52017-10-19 14:42:40 +09005775 @VisibleForTesting
5776 protected IpConnectivityMetrics.Logger metricsLogger() {
5777 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5778 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005779 }
5780
5781 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005782 int[] transports = nai.networkCapabilities.getTransportTypes();
5783 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005784 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005785
5786 private static boolean toBool(int encodedBoolean) {
5787 return encodedBoolean != 0; // Only 0 means false.
5788 }
5789
5790 private static int encodeBool(boolean b) {
5791 return b ? 1 : 0;
5792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005793}