blob: 6463bed639a97e056355f9f07cd2b79a2a07fccf [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;
dalyk1fcb7392018-03-05 12:42:22 -050055import android.net.IIpConnectivityMetrics;
56import android.net.INetdEventCallback;
Haoyu Baidb3c8672012-06-20 14:29:57 -070057import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070058import android.net.INetworkPolicyListener;
59import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070060import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080061import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070062import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010063import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070064import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070065import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070066import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070067import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070069import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070070import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090071import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070072import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070073import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070074import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070075import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070076import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +000077import android.net.NetworkWatchlistManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070078import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040079import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070080import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040081import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040082import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060083import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +090084import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090085import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090086import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080088import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070089import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040090import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070092import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070093import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070094import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.os.Looper;
96import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070097import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070098import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +090099import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700100import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -0700101import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700102import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800103import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900104import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900105import android.os.ServiceSpecificException;
mswest46386886f2018-03-12 10:34:34 -0700106import android.os.ShellCallback;
107import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900108import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700109import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400110import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700112import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700113import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700114import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700115import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900116import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700117import android.util.LocalLog;
118import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600119import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800120import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700121import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500122import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700123import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700124import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125
Wink Savilleab9321d2013-06-29 21:10:57 -0700126import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400127import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400128import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700129import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700130import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700131import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700132import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800133import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700134import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700135import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600136import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700137import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900138import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900139import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700140import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700141import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400142import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900143import com.android.server.connectivity.DnsManager;
Erik Klinea24d4592018-01-11 21:07:29 +0900144import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
dalyk1fcb7392018-03-05 12:42:22 -0500145import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900146import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900147import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100148import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700149import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900150import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700151import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600152import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400153import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900154import com.android.server.connectivity.NetworkNotificationManager;
155import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400156import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700157import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800158import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700159import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100160import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk1fcb7392018-03-05 12:42:22 -0500161import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700162import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700163import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900164import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700165import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600166
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700167import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700168
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700169import org.xmlpull.v1.XmlPullParser;
170import org.xmlpull.v1.XmlPullParserException;
171
172import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700174import java.io.FileNotFoundException;
175import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700176import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700178import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700179import java.net.InetAddress;
180import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700181import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700182import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700183import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700184import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700185import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700186import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700187import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700188import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700189import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900190import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600191import java.util.SortedSet;
192import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
194/**
195 * @hide
196 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800197public class ConnectivityService extends IConnectivityManager.Stub
198 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900199 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
Erik Kline7747fd42017-05-12 16:52:48 +0900201 public static final String DIAG_ARG = "--diag";
202 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900203 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900204
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900205 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700206 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207
Jake Hamby786e71a2014-02-06 14:43:50 -0800208 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900209 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700210
Jeff Sharkey899223b2012-08-04 15:24:58 -0700211 // TODO: create better separation between radio types and network types
212
Robert Greenwalt42acef32009-08-12 16:08:25 -0700213 // how long to wait before switching back to a radio's default network
214 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
215 // system property that can override the above value
216 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
217 "android.telephony.apn-restore";
218
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900219 // How long to wait before putting up a "This network doesn't have an Internet connection,
220 // connect anyway?" dialog after the user selects a network that doesn't validate.
221 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
222
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900223 // Default to 30s linger time-out. Modifiable only for testing.
224 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
225 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
226 @VisibleForTesting
227 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
228
Jeremy Joslin79294842014-12-03 17:15:28 -0800229 // How long to delay to removal of a pending intent based request.
230 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
231 private final int mReleasePendingIntentDelayMs;
232
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900233 private MockableSystemProperties mSystemProperties;
234
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800235 private Tethering mTethering;
236
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700237 private final PermissionMonitor mPermissionMonitor;
238
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700239 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700240
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700241 @GuardedBy("mVpns")
242 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700243
Hugo Benichi69744342017-11-27 10:57:16 +0900244 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
245 // a direct call to LockdownVpnTracker.isEnabled().
246 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700247 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900248 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700249 private LockdownVpnTracker mLockdownTracker;
250
Erik Klineda4bfa82015-04-30 12:58:40 +0900251 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700253 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700254 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700257 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700259 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800260 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700261 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900262 private NetworkPolicyManagerInternal mPolicyManagerInternal;
dalyk1fcb7392018-03-05 12:42:22 -0500263 private IIpConnectivityMetrics mIpConnectivityMetrics;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700264
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700265 private String mCurrentTcpBufferSizes;
266
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700267 private static final int ENABLED = 1;
268 private static final int DISABLED = 0;
269
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900270 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900271 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
272 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900273
Paul Jensenb10e37f2014-11-25 12:33:08 -0500274 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400275 // Tear down networks that have no chance (e.g. even if validated) of becoming
276 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500277 // all networks have been rematched against all NetworkRequests.
278 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400279 // Don't reap networks. This should be passed when some networks have not yet been
280 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500281 DONT_REAP
282 };
283
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900284 private enum UnneededFor {
285 LINGER, // Determine whether this network is unneeded and should be lingered.
286 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
287 }
288
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700289 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700290 * used internally to change our mobile data enabled flag
291 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700292 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700293
294 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700295 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700296 * from one net to another. Clear happens when we get a new
297 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
298 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700299 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700300 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700301
Robert Greenwalt434203a2010-10-11 16:00:27 -0700302 /**
303 * used internally to reload global proxy settings
304 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700305 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700306
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700307 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400308 * PAC manager has received new port.
309 */
310 private static final int EVENT_PROXY_HAS_CHANGED = 16;
311
Robert Greenwalte049c232014-04-11 15:53:27 -0700312 /**
313 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700314 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700315 */
316 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
317
Robert Greenwalt7b816022014-04-18 15:25:25 -0700318 /**
319 * used internally when registering NetworkAgents
320 * obj = Messenger
321 */
322 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
323
Robert Greenwalt9258c642014-03-26 16:47:06 -0700324 /**
325 * used to add a network request
326 * includes a NetworkRequestInfo
327 */
328 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
329
330 /**
331 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900332 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700333 * cancel it.
334 * includes a NetworkRequestInfo
335 */
336 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
337
338 /**
339 * used to add a network listener - no request
340 * includes a NetworkRequestInfo
341 */
342 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
343
344 /**
345 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400346 * arg1 = UID of caller
347 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700348 */
349 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
350
Robert Greenwalta67be032014-05-16 15:49:14 -0700351 /**
352 * used internally when registering NetworkFactories
353 * obj = Messenger
354 */
355 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
356
Robert Greenwalt27711812014-06-25 16:45:57 -0700357 /**
358 * used internally to expire a wakelock when transitioning
359 * from one net to another. Expire happens when we fail to find
360 * a new network (typically after 1 minute) -
361 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
362 * a replacement network.
363 */
364 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
365
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700366 /**
367 * Used internally to indicate the system is ready.
368 */
369 private static final int EVENT_SYSTEM_READY = 25;
370
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800371 /**
372 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400373 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800374 */
375 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
376
377 /**
378 * used to remove a pending intent and its associated network request.
379 * arg1 = UID of caller
380 * obj = PendingIntent
381 */
382 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
383
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900384 /**
385 * used to specify whether a network should be used even if unvalidated.
386 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
387 * arg2 = whether to remember this choice in the future (1 or 0)
388 * obj = network
389 */
390 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
391
392 /**
393 * used to ask the user to confirm a connection to an unvalidated network.
394 * obj = network
395 */
396 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700397
Erik Klineda4bfa82015-04-30 12:58:40 +0900398 /**
399 * used internally to (re)configure mobile data always-on settings.
400 */
401 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
402
Paul Jensen694f2b82015-06-17 14:15:39 -0400403 /**
404 * used to add a network listener with a pending intent
405 * obj = NetworkRequestInfo
406 */
407 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
408
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900409 /**
410 * used to specify whether a network should not be penalized when it becomes unvalidated.
411 */
412 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
413
414 /**
415 * used to trigger revalidation of a network.
416 */
417 private static final int EVENT_REVALIDATE_NETWORK = 36;
418
Erik Klinea24d4592018-01-11 21:07:29 +0900419 // Handle changes in Private DNS settings.
420 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
421
dalyk1fcb7392018-03-05 12:42:22 -0500422 // Handle private DNS validation status updates.
423 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
424
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900425 private static String eventName(int what) {
426 return sMagicDecoderRing.get(what, Integer.toString(what));
427 }
428
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900429 /** Handler thread used for both of the handlers below. */
430 @VisibleForTesting
431 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700432 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700433 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700434 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700435 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900436 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700437
Mike Lockwood0f79b542009-08-14 14:18:49 -0400438 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800439 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400440
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700441 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700442 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800443 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700444
Robert Greenwalt434203a2010-10-11 16:00:27 -0700445 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400446 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700447 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700448 private boolean mDefaultProxyDisabled = false;
449
Robert Greenwalt434203a2010-10-11 16:00:27 -0700450 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400451 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700452
Jason Monk602b2322013-07-03 17:04:33 -0400453 private PacManager mPacManager = null;
454
Erik Klineda4bfa82015-04-30 12:58:40 +0900455 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700456
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400457 private UserManager mUserManager;
458
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700459 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700460 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700461
Robert Greenwalt50393202011-06-21 17:26:14 -0700462 // the set of network types that can only be enabled by system/sig apps
463 List mProtectedNetworks;
464
John Spurlockbf991a82013-06-24 14:20:23 -0400465 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700466
Wink Savilleab9321d2013-06-29 21:10:57 -0700467 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400468
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900469 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900470 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900471 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900472
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700473 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800474 private static final int MIN_NET_ID = 100; // some reserved marks
475 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700476 private int mNextNetId = MIN_NET_ID;
477
Robert Greenwalt34524f02014-05-18 16:22:10 -0700478 // sequence number of NetworkRequests
479 private int mNextNetworkRequestId = 1;
480
Erik Kline7523eb32015-07-09 18:24:03 +0900481 // NetworkRequest activity String log entries.
482 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
483 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
484
Hugo Benichic2ae2872016-07-11 11:05:12 +0900485 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900486 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900487 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
488
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900489 private static final int MAX_WAKELOCK_LOGS = 20;
490 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900491 private int mTotalWakelockAcquisitions = 0;
492 private int mTotalWakelockReleases = 0;
493 private long mTotalWakelockDurationMs = 0;
494 private long mMaxWakelockDurationMs = 0;
495 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900496
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700497 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
498 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400499 private static class ValidationLog {
500 final Network mNetwork;
501 final String mNetworkExtraInfo;
502 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700503
Paul Jensen0808eb82016-06-03 13:51:21 -0400504 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
505 mNetwork = network;
506 mNetworkExtraInfo = networkExtraInfo;
507 mLog = log;
508 }
509 }
510 private final ArrayDeque<ValidationLog> mValidationLogs =
511 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
512
513 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900514 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700515 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
516 mValidationLogs.removeLast();
517 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400518 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700519 }
520 }
521
Hugo Benichif9fdf872016-07-28 17:53:06 +0900522 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900523
Erik Kline065ab6e2016-10-02 18:02:14 +0900524 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900525 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900526
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900527 @VisibleForTesting
528 final MultipathPolicyTracker mMultipathPolicyTracker;
529
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700530 /**
531 * Implements support for the legacy "one network per network type" model.
532 *
533 * We used to have a static array of NetworkStateTrackers, one for each
534 * network type, but that doesn't work any more now that we can have,
535 * for example, more that one wifi network. This class stores all the
536 * NetworkAgentInfo objects that support a given type, but the legacy
537 * API will only see the first one.
538 *
539 * It serves two main purposes:
540 *
541 * 1. Provide information about "the network for a given type" (since this
542 * API only supports one).
543 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
544 * the first network for a given type changes, or if the default network
545 * changes.
546 */
547 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900548
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900549 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900550 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900551
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700552 /**
553 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
554 * Each list holds references to all NetworkAgentInfos that are used to
555 * satisfy requests for that network type.
556 *
557 * This array is built out at startup such that an unsupported network
558 * doesn't get an ArrayList instance, making this a tristate:
559 * unsupported, supported but not active and active.
560 *
561 * The actual lists are populated when we scan the network types that
562 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900563 *
564 * Threading model:
565 * - addSupportedType() is only called in the constructor
566 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
567 * They are therefore not thread-safe with respect to each other.
568 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
569 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
570 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700571 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900572 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700573
574 public LegacyTypeTracker() {
575 mTypeLists = (ArrayList<NetworkAgentInfo>[])
576 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
577 }
578
579 public void addSupportedType(int type) {
580 if (mTypeLists[type] != null) {
581 throw new IllegalStateException(
582 "legacy list for type " + type + "already initialized");
583 }
584 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
585 }
586
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700587 public boolean isTypeSupported(int type) {
588 return isNetworkTypeValid(type) && mTypeLists[type] != null;
589 }
590
591 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900592 synchronized (mTypeLists) {
593 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
594 return mTypeLists[type].get(0);
595 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700596 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900597 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700598 }
599
Robert Greenwalt8d482522015-06-24 13:23:42 -0700600 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900601 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900602 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700603 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900604 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900605 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900606 }
607 }
608
609 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700610 public void add(int type, NetworkAgentInfo nai) {
611 if (!isTypeSupported(type)) {
612 return; // Invalid network type.
613 }
614 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
615
616 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
617 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700618 return;
619 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900620 synchronized (mTypeLists) {
621 list.add(nai);
622 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900623
624 // 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 +0900625 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900626 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700627 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
628 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700629 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700630 }
631
Lorenzo Colittia793a672014-07-31 23:20:17 +0900632 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900633 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900634 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
635 if (list == null || list.isEmpty()) {
636 return;
637 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900638 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900639
Hugo Benichi78caa2582016-06-21 09:48:07 +0900640 synchronized (mTypeLists) {
641 if (!list.remove(nai)) {
642 return;
643 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900644 }
645
Robert Greenwalt8d482522015-06-24 13:23:42 -0700646 final DetailedState state = DetailedState.DISCONNECTED;
647
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900648 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700649 maybeLogBroadcast(nai, state, type, wasDefault);
650 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900651 }
652
653 if (!list.isEmpty() && wasFirstNetwork) {
654 if (DBG) log("Other network available for type " + type +
655 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900656 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700657 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
658 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900659 }
660 }
661
662 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900663 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
664 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700665 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900666 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700667 }
668 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700669
Robert Greenwalt8d482522015-06-24 13:23:42 -0700670 // send out another legacy broadcast - currently only used for suspend/unsuspend
671 // toggle
672 public void update(NetworkAgentInfo nai) {
673 final boolean isDefault = isDefaultNetwork(nai);
674 final DetailedState state = nai.networkInfo.getDetailedState();
675 for (int type = 0; type < mTypeLists.length; type++) {
676 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700677 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900678 final boolean isFirst = contains && (nai == list.get(0));
679 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700680 maybeLogBroadcast(nai, state, type, isDefault);
681 sendLegacyNetworkBroadcast(nai, state, type);
682 }
683 }
684 }
685
Lorenzo Colittia793a672014-07-31 23:20:17 +0900686 private String naiToString(NetworkAgentInfo nai) {
687 String name = (nai != null) ? nai.name() : "null";
688 String state = (nai.networkInfo != null) ?
689 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
690 "???/???";
691 return name + " " + state;
692 }
693
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700694 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900695 pw.println("mLegacyTypeTracker:");
696 pw.increaseIndent();
697 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700698 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900699 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700700 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900701 pw.println();
702 pw.println("Current state:");
703 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900704 synchronized (mTypeLists) {
705 for (int type = 0; type < mTypeLists.length; type++) {
706 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
707 for (NetworkAgentInfo nai : mTypeLists[type]) {
708 pw.println(type + " " + naiToString(nai));
709 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900710 }
711 }
712 pw.decreaseIndent();
713 pw.decreaseIndent();
714 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700715 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700716 }
717 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
718
Vishnu Nair5c010902017-10-26 10:08:50 -0700719 /**
720 * Helper class which parses out priority arguments and dumps sections according to their
721 * priority. If priority arguments are omitted, function calls the legacy dump command.
722 */
723 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
724 @Override
725 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
726 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
727 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
728 }
729
730 @Override
731 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
732 doDump(fd, pw, args, asProto);
733 }
734
735 @Override
736 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
737 doDump(fd, pw, args, asProto);
738 }
739 };
740
Jeff Sharkey899223b2012-08-04 15:24:58 -0700741 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700742 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900743 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
744 }
745
746 @VisibleForTesting
747 protected ConnectivityService(Context context, INetworkManagementService netManager,
748 INetworkStatsService statsService, INetworkPolicyManager policyManager,
749 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800750 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800751
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900752 mSystemProperties = getSystemProperties();
753
Hugo Benichif9fdf872016-07-28 17:53:06 +0900754 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900755 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900756 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900757 mNetworkRequests.put(mDefaultRequest, defaultNRI);
758 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900759
Chalard Jeandda156a2018-01-10 21:19:32 +0900760 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900761 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700762
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900763 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900764 mHandlerThread.start();
765 mHandler = new InternalHandler(mHandlerThread.getLooper());
766 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700767
Jeremy Joslin79294842014-12-03 17:15:28 -0800768 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
769 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
770
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900771 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900772
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700773 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700774 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800775 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700776 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900777 mPolicyManagerInternal = checkNotNull(
778 LocalServices.getService(NetworkPolicyManagerInternal.class),
779 "missing NetworkPolicyManagerInternal");
780
Jeff Sharkey82f85212012-08-24 11:17:25 -0700781 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700782 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700783
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700784 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900785 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700786 } catch (RemoteException e) {
787 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700788 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700789 }
790
791 final PowerManager powerManager = (PowerManager) context.getSystemService(
792 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700793 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
794 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
795 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800796 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700797
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700798 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700799
Wink Saville51f456f2013-04-23 14:26:51 -0700800 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900801 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700802 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700803 String[] naStrings = context.getResources().getStringArray(
804 com.android.internal.R.array.networkAttributes);
805 for (String naString : naStrings) {
806 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700807 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700808 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700809 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800810 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700811 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700812 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700813 }
Wink Saville51f456f2013-04-23 14:26:51 -0700814 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
815 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
816 n.type);
817 continue;
818 }
Wink Saville975c8482011-04-07 14:23:45 -0700819 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800820 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700821 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700822 continue;
823 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700824 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700825
Wink Saville975c8482011-04-07 14:23:45 -0700826 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700827 mNetworksDefined++;
828 } catch(Exception e) {
829 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700830 }
831 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700832
833 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
834 if (mNetConfigs[TYPE_VPN] == null) {
835 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
836 // don't need to add TYPE_VPN to mNetConfigs.
837 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
838 mNetworksDefined++; // used only in the log() statement below.
839 }
840
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900841 // Do the same for Ethernet, since it's often not specified in the configs, although many
842 // devices can use it via USB host adapters.
843 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
844 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
845 mNetworksDefined++;
846 }
847
Wink Saville5e56bc52013-07-29 15:00:57 -0700848 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700849
Robert Greenwalt50393202011-06-21 17:26:14 -0700850 mProtectedNetworks = new ArrayList<Integer>();
851 int[] protectedNetworks = context.getResources().getIntArray(
852 com.android.internal.R.array.config_protectedNetworks);
853 for (int p : protectedNetworks) {
854 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
855 mProtectedNetworks.add(p);
856 } else {
857 if (DBG) loge("Ignoring protectedNetwork " + p);
858 }
859 }
860
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900861 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
862 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700863
Erik Kline47222fc2017-04-30 19:36:15 +0900864 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800865
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700866 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
867
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700868 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700869 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100870 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700871 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700872 intentFilter.addAction(Intent.ACTION_USER_ADDED);
873 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000874 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700875 mContext.registerReceiverAsUser(
876 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000877 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
878 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900879
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700880 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700881 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700882 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700883 } catch (RemoteException e) {
884 loge("Error registering observer :" + e);
885 }
886
Erik Klineda4bfa82015-04-30 12:58:40 +0900887 mSettingsObserver = new SettingsObserver(mContext, mHandler);
888 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800889
John Spurlockbf991a82013-06-24 14:20:23 -0400890 mDataConnectionStats = new DataConnectionStats(mContext);
891 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400892
Jason Monkdecd2952013-10-10 14:02:51 -0400893 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700894
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400895 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900896
897 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900898 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
899 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900900
901 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
902 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
903 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
904 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
905 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
906 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
907 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900908
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900909 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900910 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900911 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900912
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900913 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
914
Erik Kline1742fe12017-12-13 19:40:49 +0900915 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900916 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700918
Erik Kline47222fc2017-04-30 19:36:15 +0900919 private Tethering makeTethering() {
920 // TODO: Move other elements into @Overridden getters.
Erik Kline7a26ba32018-03-09 14:18:02 +0900921 final TetheringDependencies deps = new TetheringDependencies() {
922 @Override
923 public boolean isTetheringSupported() {
924 return ConnectivityService.this.isTetheringSupported();
925 }
926 };
Erik Kline47222fc2017-04-30 19:36:15 +0900927 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
928 IoThread.get().getLooper(), new MockableSystemProperties(),
929 deps);
930 }
931
Chalard Jeandda156a2018-01-10 21:19:32 +0900932 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900933 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900934 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900935 netCap.addCapability(NET_CAPABILITY_INTERNET);
936 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900937 if (transportType > -1) {
938 netCap.addTransportType(transportType);
939 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900940 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900941 }
942
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900943 // Used only for testing.
944 // TODO: Delete this and either:
Erik Kline79c6d052018-03-21 07:18:33 -0700945 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900946 // changing ContentResolver to make registerContentObserver non-final).
947 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
948 // by subclassing SettingsObserver.
949 @VisibleForTesting
950 void updateMobileDataAlwaysOn() {
951 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
952 }
953
Erik Kline79c6d052018-03-21 07:18:33 -0700954 // See FakeSettingsProvider comment above.
955 @VisibleForTesting
956 void updatePrivateDnsSettings() {
957 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
958 }
959
Erik Klineda4bfa82015-04-30 12:58:40 +0900960 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900961 final boolean enable = toBool(Settings.Global.getInt(
962 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900963 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
964 if (enable == isEnabled) {
965 return; // Nothing to do.
966 }
967
968 if (enable) {
969 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900970 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900971 } else {
972 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
973 }
974 }
975
976 private void registerSettingsCallbacks() {
977 // Watch for global HTTP proxy changes.
978 mSettingsObserver.observe(
979 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
980 EVENT_APPLY_GLOBAL_HTTP_PROXY);
981
982 // Watch for whether or not to keep mobile data always on.
983 mSettingsObserver.observe(
984 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
985 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
986 }
987
Erik Klinea24d4592018-01-11 21:07:29 +0900988 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline79c6d052018-03-21 07:18:33 -0700989 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
990 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +0900991 }
992 }
993
Robert Greenwalt34524f02014-05-18 16:22:10 -0700994 private synchronized int nextNetworkRequestId() {
995 return mNextNetworkRequestId++;
996 }
997
Paul Jensen67b0b072015-06-10 11:22:17 -0400998 @VisibleForTesting
999 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001000 synchronized (mNetworkForNetId) {
1001 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1002 int netId = mNextNetId;
1003 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1004 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001005 if (!mNetIdInUse.get(netId)) {
1006 mNetIdInUse.put(netId, true);
1007 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001008 }
1009 }
1010 }
1011 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001012 }
1013
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001014 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001015 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001016 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1017 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001018 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001019 state = nai.getNetworkState();
1020 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001021 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001022 final NetworkInfo info = new NetworkInfo(networkType, 0,
1023 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001024 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1025 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001026 final NetworkCapabilities capabilities = new NetworkCapabilities();
1027 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1028 !info.isRoaming());
1029 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001030 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001031 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001032 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001033 return state;
1034 } else {
1035 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001036 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001037 }
1038
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001039 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
1040 if (network == null) {
1041 return null;
1042 }
Erik Kline79c6d052018-03-21 07:18:33 -07001043 return getNetworkAgentInfoForNetId(network.netId);
1044 }
1045
1046 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001047 synchronized (mNetworkForNetId) {
Erik Kline79c6d052018-03-21 07:18:33 -07001048 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001049 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001050 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001051
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001052 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001053 synchronized (mVpns) {
1054 if (!mLockdownEnabled) {
1055 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001056 Vpn vpn = mVpns.get(user);
1057 if (vpn != null && vpn.appliesToUid(uid)) {
1058 return vpn.getUnderlyingNetworks();
1059 }
1060 }
1061 }
1062 return null;
1063 }
1064
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001065 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001066 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001067
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001068 final Network[] networks = getVpnUnderlyingNetworks(uid);
1069 if (networks != null) {
1070 // getUnderlyingNetworks() returns:
1071 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1072 // empty array => the VPN explicitly said "no default network".
1073 // non-empty array => the VPN specified one or more default networks; we use the
1074 // first one.
1075 if (networks.length > 0) {
1076 nai = getNetworkAgentInfoForNetwork(networks[0]);
1077 } else {
1078 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001079 }
1080 }
1081
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001082 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001083 return nai.getNetworkState();
1084 } else {
1085 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001086 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001087 }
1088
1089 /**
1090 * Check if UID should be blocked from using the network with the given LinkProperties.
1091 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001092 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1093 boolean ignoreBlocked) {
1094 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001095 if (ignoreBlocked) {
1096 return false;
1097 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001098 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001099 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1100 if (isSystem(uid)) {
1101 return false;
1102 }
Robin Lee17e61832016-05-09 13:46:28 +01001103 synchronized (mVpns) {
1104 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1105 if (vpn != null && vpn.isBlockingUid(uid)) {
1106 return true;
1107 }
1108 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001109 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001110 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001111 }
1112
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001113 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001114 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1115 return;
1116 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001117 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001118 synchronized (mBlockedAppUids) {
1119 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001120 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001121 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001122 blocked = false;
1123 } else {
1124 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001125 }
1126 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001127 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1128 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1129 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001130 }
1131
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001132 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001133 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1134 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001135 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001136 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001137 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001138 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1139
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001140 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001141 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001142 }
Hugo Benichi69744342017-11-27 10:57:16 +09001143 synchronized (mVpns) {
1144 if (mLockdownTracker != null) {
1145 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1146 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001147 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001148 }
1149
1150 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 * Return NetworkInfo for the active (i.e., connected) network interface.
1152 * It is assumed that at most one network is active at a time. If more
1153 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001154 * @return the info for the active network, or {@code null} if none is
1155 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001157 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001159 enforceAccessPermission();
1160 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001161 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001162 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001163 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1164 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 }
1166
Paul Jensen31a94f42015-02-13 14:18:39 -05001167 @Override
1168 public Network getActiveNetwork() {
1169 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001170 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001171 }
1172
1173 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001174 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001175 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001176 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001177 }
1178
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001179 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001180 final int user = UserHandle.getUserId(uid);
1181 int vpnNetId = NETID_UNSET;
1182 synchronized (mVpns) {
1183 final Vpn vpn = mVpns.get(user);
1184 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1185 }
1186 NetworkAgentInfo nai;
1187 if (vpnNetId != NETID_UNSET) {
Erik Kline79c6d052018-03-21 07:18:33 -07001188 nai = getNetworkAgentInfoForNetId(vpnNetId);
Paul Jensen31a94f42015-02-13 14:18:39 -05001189 if (nai != null) return nai.network;
1190 }
1191 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001192 if (nai != null
1193 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1194 nai = null;
1195 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001196 return nai != null ? nai.network : null;
1197 }
1198
Lorenzo Colitti18660282016-07-04 12:55:44 +09001199 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001200 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1201 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001202 final int uid = Binder.getCallingUid();
1203 NetworkState state = getUnfilteredActiveNetworkState(uid);
1204 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001205 }
1206
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001207 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001208 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001209 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001210 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001211 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001212 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001213 }
1214
1215 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 public NetworkInfo getNetworkInfo(int networkType) {
1217 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001218 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001219 if (getVpnUnderlyingNetworks(uid) != null) {
1220 // A VPN is active, so we may need to return one of its underlying networks. This
1221 // information is not available in LegacyTypeTracker, so we have to get it from
1222 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001223 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001224 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001225 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001226 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001227 }
1228 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001229 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001230 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 }
1232
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001233 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001234 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001235 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001236 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001237 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001238 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001239 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001240 return state.networkInfo;
1241 } else {
1242 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001243 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001244 }
1245
1246 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 public NetworkInfo[] getAllNetworkInfo() {
1248 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001249 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001250 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1251 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001252 NetworkInfo info = getNetworkInfo(networkType);
1253 if (info != null) {
1254 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001257 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 }
1259
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001260 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001261 public Network getNetworkForType(int networkType) {
1262 enforceAccessPermission();
1263 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001264 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1265 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001266 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001267 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001268 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001269 }
1270
1271 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001272 public Network[] getAllNetworks() {
1273 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001274 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001275 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001276 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001277 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001278 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001279 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001280 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001281 }
1282
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001283 @Override
1284 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1285 // The basic principle is: if an app's traffic could possibly go over a
1286 // network, without the app doing anything multinetwork-specific,
1287 // (hence, by "default"), then include that network's capabilities in
1288 // the array.
1289 //
1290 // In the normal case, app traffic only goes over the system's default
1291 // network connection, so that's the only network returned.
1292 //
1293 // With a VPN in force, some app traffic may go into the VPN, and thus
1294 // over whatever underlying networks the VPN specifies, while other app
1295 // traffic may go over the system default network (e.g.: a split-tunnel
1296 // VPN, or an app disallowed by the VPN), so the set of networks
1297 // returned includes the VPN's underlying networks and the system
1298 // default.
1299 enforceAccessPermission();
1300
1301 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1302
1303 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001304 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001305 if (nc != null) {
1306 result.put(nai.network, nc);
1307 }
1308
Hugo Benichi69744342017-11-27 10:57:16 +09001309 synchronized (mVpns) {
1310 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001311 Vpn vpn = mVpns.get(userId);
1312 if (vpn != null) {
1313 Network[] networks = vpn.getUnderlyingNetworks();
1314 if (networks != null) {
1315 for (Network network : networks) {
1316 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001317 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001318 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001319 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001320 }
1321 }
1322 }
1323 }
1324 }
1325 }
1326
1327 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1328 out = result.values().toArray(out);
1329 return out;
1330 }
1331
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001332 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001333 public boolean isNetworkSupported(int networkType) {
1334 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001335 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001336 }
1337
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001338 /**
1339 * Return LinkProperties for the active (i.e., connected) default
1340 * network interface. It is assumed that at most one default network
1341 * is active at a time. If more than one is active, it is indeterminate
1342 * which will be returned.
1343 * @return the ip properties for the active network, or {@code null} if
1344 * none is active
1345 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001346 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001347 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001348 enforceAccessPermission();
1349 final int uid = Binder.getCallingUid();
1350 NetworkState state = getUnfilteredActiveNetworkState(uid);
1351 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001352 }
1353
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001354 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001355 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001356 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001357 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1358 if (nai != null) {
1359 synchronized (nai) {
1360 return new LinkProperties(nai.linkProperties);
1361 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001362 }
1363 return null;
1364 }
1365
Robert Greenwalt12e67352014-05-13 21:41:06 -07001366 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001367 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001368 public LinkProperties getLinkProperties(Network network) {
1369 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001370 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1371 }
1372
1373 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1374 if (nai == null) {
1375 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001376 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001377 synchronized (nai) {
1378 return new LinkProperties(nai.linkProperties);
1379 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001380 }
1381
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001382 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001383 if (nai != null) {
1384 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001385 if (nai.networkCapabilities != null) {
Chalard Jeanb552c462018-02-21 18:43:54 +09001386 return networkCapabilitiesWithoutUidsUnlessAllowed(nai.networkCapabilities,
1387 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001388 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001389 }
1390 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001391 return null;
1392 }
1393
1394 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001395 public NetworkCapabilities getNetworkCapabilities(Network network) {
1396 enforceAccessPermission();
1397 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1398 }
1399
Chalard Jeanb552c462018-02-21 18:43:54 +09001400 private NetworkCapabilities networkCapabilitiesWithoutUidsUnlessAllowed(
1401 NetworkCapabilities nc, int callerPid, int callerUid) {
1402 if (checkSettingsPermission(callerPid, callerUid)) return new NetworkCapabilities(nc);
Chalard Jeanf19db372018-01-26 19:24:40 +09001403 return new NetworkCapabilities(nc).setUids(null);
1404 }
1405
Chalard Jeanb552c462018-02-21 18:43:54 +09001406 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1407 if (!checkSettingsPermission()) {
1408 nc.setSingleUid(Binder.getCallingUid());
1409 }
1410 }
1411
Chalard Jean26aa91a2018-03-20 19:13:57 +09001412 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1413 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1414 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1415 }
1416 }
1417
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001418 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001419 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001420 // Require internal since we're handing out IMSI details
1421 enforceConnectivityInternalPermission();
1422
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001423 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001424 for (Network network : getAllNetworks()) {
1425 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1426 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001427 // TODO (b/73321673) : NetworkState contains a copy of the
1428 // NetworkCapabilities, which may contain UIDs of apps to which the
1429 // network applies. Should the UIDs be cleared so as not to leak or
1430 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001431 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001432 }
1433 }
1434 return result.toArray(new NetworkState[result.size()]);
1435 }
1436
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001437 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001438 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001439 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001440 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1441 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1442 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001443 }
1444
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001445 @Override
1446 public boolean isActiveNetworkMetered() {
1447 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001448
Eric Enslenc81ef192018-02-07 18:03:53 -08001449 final int uid = Binder.getCallingUid();
1450 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001451 if (caps != null) {
1452 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1453 } else {
1454 // Always return the most conservative value
1455 return true;
1456 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001457 }
1458
Jeff Sharkey216c1812012-08-05 14:29:23 -07001459 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1460 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001461 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001462 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001463 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001464 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001465 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001466
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001467 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 * Ensure that a network route exists to deliver traffic to the specified
1469 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001470 * @param networkType the type of the network over which traffic to the
1471 * specified host is to be routed
1472 * @param hostAddress the IP address of the host to which the route is
1473 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 * @return {@code true} on success, {@code false} on failure
1475 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001476 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001477 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001479 if (mProtectedNetworks.contains(networkType)) {
1480 enforceConnectivityInternalPermission();
1481 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001482
Chad Brubakerc0234532014-02-14 13:24:29 -08001483 InetAddress addr;
1484 try {
1485 addr = InetAddress.getByAddress(hostAddress);
1486 } catch (UnknownHostException e) {
1487 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1488 return false;
1489 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001492 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 return false;
1494 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001495
1496 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1497 if (nai == null) {
1498 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1499 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1500 } else {
1501 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1502 }
1503 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001504 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001505
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001506 DetailedState netState;
1507 synchronized (nai) {
1508 netState = nai.networkInfo.getDetailedState();
1509 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001510
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001511 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001512 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001513 log("requestRouteToHostAddress on down network "
1514 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001515 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001516 }
1517 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001519
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001520 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001521 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001522 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001523 LinkProperties lp;
1524 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001525 synchronized (nai) {
1526 lp = nai.linkProperties;
1527 netId = nai.network.netId;
1528 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001529 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001530 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1531 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001532 } finally {
1533 Binder.restoreCallingIdentity(token);
1534 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001535 }
1536
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001537 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001538 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001539 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001540 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001541 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001542 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001543 if (bestRoute.getGateway().equals(addr)) {
1544 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001545 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001546 } else {
1547 // if we will connect to this through another route, add a direct route
1548 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001549 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001550 }
1551 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001552 if (DBG) log("Adding legacy route " + bestRoute +
1553 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001554 try {
1555 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1556 } catch (Exception e) {
1557 // never crash - catch them all
1558 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001559 return false;
1560 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001561 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 }
1563
dalyk1fcb7392018-03-05 12:42:22 -05001564 @VisibleForTesting
1565 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1566 @Override
1567 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1568 String hostname, boolean validated) {
1569 try {
1570 mHandler.sendMessage(mHandler.obtainMessage(
1571 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1572 new PrivateDnsValidationUpdate(netId,
1573 InetAddress.parseNumericAddress(ipAddress),
1574 hostname, validated)));
1575 } catch (IllegalArgumentException e) {
1576 loge("Error parsing ip address in validation event");
1577 }
1578 }
1579 };
1580
1581 @VisibleForTesting
1582 protected void registerNetdEventCallback() {
1583 mIpConnectivityMetrics =
1584 (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1585 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1586 if (mIpConnectivityMetrics == null) {
1587 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
1588 }
1589
1590 try {
1591 mIpConnectivityMetrics.addNetdEventCallback(
1592 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1593 mNetdEventCallback);
1594 } catch (Exception e) {
1595 loge("Error registering netd callback: " + e);
1596 }
1597 }
1598
Jeff Sharkey75d31892018-01-18 22:01:59 +09001599 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001600 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001601 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001602 // TODO: notify UID when it has requested targeted updates
1603 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001604 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001605 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001606 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001607 if (restrictBackground) {
1608 log("onRestrictBackgroundChanged(true): disabling tethering");
1609 mTethering.untetherAll();
1610 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001611 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001612 };
1613
Robin Lee3b3dd942015-05-12 18:14:58 +01001614 /**
1615 * Require that the caller is either in the same user or has appropriate permission to interact
1616 * across users.
1617 *
1618 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1619 */
1620 private void enforceCrossUserPermission(int userId) {
1621 if (userId == UserHandle.getCallingUserId()) {
1622 // Not a cross-user call.
1623 return;
1624 }
1625 mContext.enforceCallingOrSelfPermission(
1626 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1627 "ConnectivityService");
1628 }
1629
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001630 private void enforceInternetPermission() {
1631 mContext.enforceCallingOrSelfPermission(
1632 android.Manifest.permission.INTERNET,
1633 "ConnectivityService");
1634 }
1635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001637 mContext.enforceCallingOrSelfPermission(
1638 android.Manifest.permission.ACCESS_NETWORK_STATE,
1639 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 }
1641
1642 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001643 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 }
1645
Charles He36738632017-05-15 17:07:18 +01001646 private void enforceSettingsPermission() {
1647 mContext.enforceCallingOrSelfPermission(
1648 android.Manifest.permission.NETWORK_SETTINGS,
1649 "ConnectivityService");
1650 }
1651
Chalard Jeanb552c462018-02-21 18:43:54 +09001652 private boolean checkSettingsPermission() {
1653 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1654 android.Manifest.permission.NETWORK_SETTINGS);
1655 }
1656
1657 private boolean checkSettingsPermission(int pid, int uid) {
1658 return PERMISSION_GRANTED == mContext.checkPermission(
1659 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1660 }
1661
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001662 private void enforceTetherAccessPermission() {
1663 mContext.enforceCallingOrSelfPermission(
1664 android.Manifest.permission.ACCESS_NETWORK_STATE,
1665 "ConnectivityService");
1666 }
1667
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001668 private void enforceConnectivityInternalPermission() {
1669 mContext.enforceCallingOrSelfPermission(
1670 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1671 "ConnectivityService");
1672 }
1673
Hugo Benichi514da602016-07-19 15:59:27 +09001674 private void enforceConnectivityRestrictedNetworksPermission() {
1675 try {
1676 mContext.enforceCallingOrSelfPermission(
1677 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1678 "ConnectivityService");
1679 return;
1680 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1681 enforceConnectivityInternalPermission();
1682 }
1683
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001684 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001685 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001686 }
1687
Lorenzo Colitti18660282016-07-04 12:55:44 +09001688 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001689 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001690 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001691 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001692 }
1693
1694 private void sendInetConditionBroadcast(NetworkInfo info) {
1695 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1696 }
1697
Wink Saville628b0852011-08-04 15:01:58 -07001698 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001699 synchronized (mVpns) {
1700 if (mLockdownTracker != null) {
1701 info = new NetworkInfo(info);
1702 mLockdownTracker.augmentNetworkInfo(info);
1703 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001704 }
1705
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001706 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001707 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001708 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 if (info.isFailover()) {
1710 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1711 info.setFailover(false);
1712 }
1713 if (info.getReason() != null) {
1714 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1715 }
1716 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001717 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1718 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001720 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001721 return intent;
1722 }
1723
1724 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1725 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1726 }
1727
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001728 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001729 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1730 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1731 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001732 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001733 final long ident = Binder.clearCallingIdentity();
1734 try {
1735 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1736 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1737 } finally {
1738 Binder.restoreCallingIdentity(ident);
1739 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001740 }
1741
Mike Lockwood0f79b542009-08-14 14:18:49 -04001742 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001743 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001744 if (!mSystemReady) {
1745 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001746 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001747 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001748 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001749 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001750 }
1751
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001752 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001753 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001754 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001755 final NetworkInfo ni = intent.getParcelableExtra(
1756 ConnectivityManager.EXTRA_NETWORK_INFO);
1757 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1758 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1759 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001760 } else {
1761 BroadcastOptions opts = BroadcastOptions.makeBasic();
1762 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1763 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001764 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001765 final IBatteryStats bs = BatteryStatsService.getService();
1766 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001767 bs.noteConnectivityChanged(intent.getIntExtra(
1768 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1769 ni != null ? ni.getState().toString() : "?");
1770 } catch (RemoteException e) {
1771 }
Chad Brubakerac925012018-03-08 10:37:09 -08001772 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001773 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001774 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001775 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001776 } finally {
1777 Binder.restoreCallingIdentity(ident);
1778 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001779 }
1780 }
1781
1782 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001783 loadGlobalProxy();
dalyk1fcb7392018-03-05 12:42:22 -05001784 registerNetdEventCallback();
Wink Saville948282b2013-08-29 08:55:16 -07001785
Hugo Benichi20035e02017-04-26 14:53:28 +09001786 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001787 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001788 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001789 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001790 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001791 }
1792 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001793 // load the global proxy at startup
1794 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001795
Robin Lee244ce8e2016-01-05 18:03:46 +00001796 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1797 // for user to unlock device too.
1798 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001799
Erik Klineda4bfa82015-04-30 12:58:40 +09001800 // Configure whether mobile data is always on.
1801 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1802
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001803 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001804
1805 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 }
1807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001809 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001810 *
1811 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001812 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001813 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001814 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1815 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001816
1817 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001818 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001819
Robert Greenwalt7b816022014-04-18 15:25:25 -07001820 if (networkAgent.networkCapabilities.hasTransport(
1821 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001822 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1823 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001824 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001825 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001826 } else if (networkAgent.networkCapabilities.hasTransport(
1827 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001828 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1829 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001830 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001831 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001832 } else {
1833 // do not track any other networks
1834 timeout = 0;
1835 }
1836
Robert Greenwalt7b816022014-04-18 15:25:25 -07001837 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001838 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001839 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001840 } catch (Exception e) {
1841 // You shall not crash!
1842 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001843 }
1844 }
1845 }
1846
1847 /**
1848 * Remove data activity tracking when network disconnects.
1849 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001850 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1851 final String iface = networkAgent.linkProperties.getInterfaceName();
1852 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001853
Robert Greenwalt7b816022014-04-18 15:25:25 -07001854 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1855 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001856 try {
1857 // the call fails silently if no idletimer setup for this interface
1858 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001859 } catch (Exception e) {
1860 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001861 }
1862 }
1863 }
1864
1865 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001866 * Reads the network specific MTU size from reources.
1867 * and set it on it's iface.
1868 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001869 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1870 final String iface = newLp.getInterfaceName();
1871 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001872 if (oldLp == null && mtu == 0) {
1873 // Silently ignore unset MTU value.
1874 return;
1875 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001876 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1877 if (VDBG) log("identical MTU - not setting");
1878 return;
1879 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001880 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001881 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001882 return;
1883 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001884
w1997615afd812014-08-05 15:18:11 -07001885 // Cannot set MTU without interface name
1886 if (TextUtils.isEmpty(iface)) {
1887 loge("Setting MTU size with null iface.");
1888 return;
1889 }
1890
Robert Greenwalt7b816022014-04-18 15:25:25 -07001891 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001892 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001893 mNetd.setMtu(iface, mtu);
1894 } catch (Exception e) {
1895 Slog.e(TAG, "exception in setMtu()" + e);
1896 }
1897 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001898
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001899 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001900 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1901
1902 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001903 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001904 protected MockableSystemProperties getSystemProperties() {
1905 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001906 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001907
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001908 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1909 if (isDefaultNetwork(nai) == false) {
1910 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001911 }
1912
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001913 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1914 String[] values = null;
1915 if (tcpBufferSizes != null) {
1916 values = tcpBufferSizes.split(",");
1917 }
1918
1919 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001920 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001921 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1922 values = tcpBufferSizes.split(",");
1923 }
1924
1925 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1926
1927 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001928 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001929
1930 final String prefix = "/sys/kernel/ipv4/tcp_";
1931 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1932 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1933 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1934 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1935 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1936 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1937 mCurrentTcpBufferSizes = tcpBufferSizes;
1938 } catch (IOException e) {
1939 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001940 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001941
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001942 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001943 Settings.Global.TCP_DEFAULT_INIT_RWND,
1944 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001945 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1946 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001947 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001948 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001949 }
1950
Robert Greenwalt562cc542014-05-15 18:07:26 -07001951 @Override
1952 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001953 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001954 NETWORK_RESTORE_DELAY_PROP_NAME);
1955 if(restoreDefaultNetworkDelayStr != null &&
1956 restoreDefaultNetworkDelayStr.length() != 0) {
1957 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001958 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001959 } catch (NumberFormatException e) {
1960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001962 // if the system property isn't set, use the value for the apn type
1963 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1964
1965 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1966 (mNetConfigs[networkType] != null)) {
1967 ret = mNetConfigs[networkType].restoreTime;
1968 }
1969 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 }
1971
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001972 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001973 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001974 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001975 }
1976 return false;
1977 }
1978
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001979 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1980 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1981 final long DIAG_TIME_MS = 5000;
1982 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1983 // Start gathering diagnostic information.
1984 netDiags.add(new NetworkDiagnostics(
1985 nai.network,
1986 new LinkProperties(nai.linkProperties), // Must be a copy.
1987 DIAG_TIME_MS));
1988 }
1989
1990 for (NetworkDiagnostics netDiag : netDiags) {
1991 pw.println();
1992 netDiag.waitForMeasurements();
1993 netDiag.dump(pw);
1994 }
1995 }
1996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001998 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07001999 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2000 }
2001
2002 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002003 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002004 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002005 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002006
Erik Kline7747fd42017-05-12 16:52:48 +09002007 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002008 dumpNetworkDiagnostics(pw);
2009 return;
Erik Klineee363c42017-05-29 09:11:03 +09002010 } else if (argsContain(args, TETHERING_ARG)) {
2011 mTethering.dump(fd, pw, args);
2012 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002013 }
Erik Kline379747a2015-06-05 17:47:34 +09002014
Lorenzo Colittie3805462015-06-03 11:18:24 +09002015 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002016 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002017 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002018 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002019 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002020 pw.println();
2021
Paul Jensen85cf78e2015-06-25 13:25:07 -04002022 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002023 pw.print("Active default network: ");
2024 if (defaultNai == null) {
2025 pw.println("none");
2026 } else {
2027 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002029 pw.println();
2030
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002031 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002032 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002033 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2034 pw.println(nai.toString());
2035 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002036 pw.println(String.format(
2037 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2038 nai.numForegroundNetworkRequests(),
2039 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2040 nai.numBackgroundNetworkRequests(),
2041 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002042 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002043 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2044 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002045 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002046 pw.decreaseIndent();
2047 pw.println("Lingered:");
2048 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002049 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002050 pw.decreaseIndent();
2051 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002052 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002053 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002054 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002055
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002056 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002057 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002058 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2059 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002060 }
2061 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002062 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002063
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002064 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002065
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002066 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002067 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002068
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002069 pw.println();
2070 mKeepaliveTracker.dump(pw);
2071
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002072 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002073 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002074
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002075 pw.println();
2076 mMultipathPolicyTracker.dump(pw);
2077
Erik Kline7747fd42017-05-12 16:52:48 +09002078 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002079 pw.println();
2080 synchronized (mValidationLogs) {
2081 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002082 for (ValidationLog p : mValidationLogs) {
2083 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002084 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002085 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002086 pw.decreaseIndent();
2087 }
2088 }
Erik Kline7523eb32015-07-09 18:24:03 +09002089
2090 pw.println();
2091 pw.println("mNetworkRequestInfoLogs (most recent first):");
2092 pw.increaseIndent();
2093 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2094 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002095
2096 pw.println();
2097 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2098 pw.increaseIndent();
2099 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2100 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002101
2102 pw.println();
2103 pw.println("NetTransition WakeLock activity (most recent first):");
2104 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002105 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2106 pw.println("total releases: " + mTotalWakelockReleases);
2107 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2108 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2109 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2110 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2111 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2112 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002113 mWakelockLogs.reverseDump(fd, pw, args);
2114 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 }
2117
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002118 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002119 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002120 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002121 if (officialNai != null && officialNai.equals(nai)) return true;
2122 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002123 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002124 " - " + nai);
2125 }
2126 return false;
2127 }
2128
Robert Greenwalt42acef32009-08-12 16:08:25 -07002129 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002130 private class NetworkStateTrackerHandler extends Handler {
2131 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002132 super(looper);
2133 }
2134
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002135 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002136 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002137 default:
2138 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002139 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002140 handleAsyncChannelHalfConnect(msg);
2141 break;
2142 }
2143 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2144 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2145 if (nai != null) nai.asyncChannel.disconnect();
2146 break;
2147 }
2148 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2149 handleAsyncChannelDisconnected(msg);
2150 break;
2151 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002152 }
2153 return true;
2154 }
2155
2156 private void maybeHandleNetworkAgentMessage(Message msg) {
2157 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2158 if (nai == null) {
2159 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002160 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002161 }
2162 return;
2163 }
2164
2165 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002166 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002167 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2168 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002169 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2170 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002171 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002172 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002173 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002174 break;
2175 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002176 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002177 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002178 break;
2179 }
2180 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002181 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002182 updateNetworkInfo(nai, info);
2183 break;
2184 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002185 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002186 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002187 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002188 break;
2189 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002190 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002191 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2192 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002193 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002194 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002195 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002196 break;
2197 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002198 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002199 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2200 break;
2201 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002202 }
2203 }
2204
2205 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2206 switch (msg.what) {
2207 default:
2208 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002209 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Erik Kline79c6d052018-03-21 07:18:33 -07002210 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002211 if (nai == null) break;
2212
2213 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2214 final boolean wasValidated = nai.lastValidated;
2215 final boolean wasDefault = isDefaultNetwork(nai);
2216
Erik Klinea24d4592018-01-11 21:07:29 +09002217 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2218
Erik Klinea24d4592018-01-11 21:07:29 +09002219 if (DBG) {
Erik Kline79c6d052018-03-21 07:18:33 -07002220 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2221 ? " with redirect to " + redirectUrl
2222 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002223 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2224 }
Erik Klinea24d4592018-01-11 21:07:29 +09002225 if (valid != nai.lastValidated) {
2226 if (wasDefault) {
2227 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2228 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002229 }
Erik Klinea24d4592018-01-11 21:07:29 +09002230 final int oldScore = nai.getCurrentScore();
2231 nai.lastValidated = valid;
2232 nai.everValidated |= valid;
2233 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2234 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2235 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2236 }
2237 updateInetCondition(nai);
2238 // Let the NetworkAgent know the state of its network
2239 Bundle redirectUrlBundle = new Bundle();
2240 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2241 nai.asyncChannel.sendMessage(
2242 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2243 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2244 0, redirectUrlBundle);
2245 if (wasValidated && !nai.lastValidated) {
2246 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002247 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002248 break;
2249 }
Paul Jensen869868be2014-05-15 10:33:05 -04002250 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002251 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002252 final boolean visible = toBool(msg.arg1);
Erik Kline79c6d052018-03-21 07:18:33 -07002253 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002254 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002255 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002256 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002257 nai.lastCaptivePortalDetected = visible;
2258 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002259 if (nai.lastCaptivePortalDetected &&
2260 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2261 if (DBG) log("Avoiding captive portal network: " + nai.name());
2262 nai.asyncChannel.sendMessage(
2263 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2264 teardownUnneededNetwork(nai);
2265 break;
2266 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002267 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002268 }
2269 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002270 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002271 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002272 if (nai == null) {
2273 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2274 break;
2275 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002276 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002277 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002278 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002279 }
Paul Jensen869868be2014-05-15 10:33:05 -04002280 }
Paul Jensen869868be2014-05-15 10:33:05 -04002281 break;
2282 }
Erik Klinea24d4592018-01-11 21:07:29 +09002283 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline79c6d052018-03-21 07:18:33 -07002284 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002285 if (nai == null) break;
2286
Erik Kline79c6d052018-03-21 07:18:33 -07002287 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002288 break;
2289 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002290 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002291 return true;
2292 }
2293
Calvin Onbe96da12016-10-11 15:10:46 -07002294 private int getCaptivePortalMode() {
2295 return Settings.Global.getInt(mContext.getContentResolver(),
2296 Settings.Global.CAPTIVE_PORTAL_MODE,
2297 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2298 }
2299
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002300 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2301 switch (msg.what) {
2302 default:
2303 return false;
2304 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2305 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2306 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2307 handleLingerComplete(nai);
2308 }
2309 break;
2310 }
2311 }
2312 return true;
2313 }
2314
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002315 @Override
2316 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002317 if (!maybeHandleAsyncChannelMessage(msg) &&
2318 !maybeHandleNetworkMonitorMessage(msg) &&
2319 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002320 maybeHandleNetworkAgentMessage(msg);
2321 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002322 }
2323 }
2324
Erik Kline79c6d052018-03-21 07:18:33 -07002325 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
2326 return NetworkMonitor.isValidationRequired(
2327 mDefaultRequest.networkCapabilities, nai.networkCapabilities);
2328 }
2329
Erik Klinea24d4592018-01-11 21:07:29 +09002330 private void handlePrivateDnsSettingsChanged() {
2331 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2332
2333 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline79c6d052018-03-21 07:18:33 -07002334 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk1fcb7392018-03-05 12:42:22 -05002335 if (networkRequiresValidation(nai)) {
2336 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2337 }
Erik Klinea24d4592018-01-11 21:07:29 +09002338 }
2339 }
2340
Erik Kline79c6d052018-03-21 07:18:33 -07002341 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2342 // Private DNS only ever applies to networks that might provide
2343 // Internet access and therefore also require validation.
2344 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002345
Erik Kline79c6d052018-03-21 07:18:33 -07002346 // Notify the NetworkMonitor thread in case it needs to cancel or
2347 // schedule DNS resolutions. If a DNS resolution is required the
2348 // result will be sent back to us.
2349 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2350
2351 // With Private DNS bypass support, we can proceed to update the
2352 // Private DNS config immediately, even if we're in strict mode
2353 // and have not yet resolved the provider name into a set of IPs.
2354 updatePrivateDns(nai, cfg);
2355 }
2356
2357 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2358 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002359 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002360 }
2361
dalyk1fcb7392018-03-05 12:42:22 -05002362 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2363 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2364 if (nai == null) {
2365 return;
2366 }
2367 mDnsManager.updatePrivateDnsValidation(update);
2368 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2369 }
2370
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002371 private void updateLingerState(NetworkAgentInfo nai, long now) {
2372 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2373 // 2. If the network was lingering and there are now requests, unlinger it.
2374 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2375 // one lingered request, start lingering.
2376 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002377 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002378 if (DBG) log("Unlingering " + nai.name());
2379 nai.unlinger();
2380 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002381 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002382 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002383 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002384 nai.linger();
2385 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2386 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2387 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002388 }
2389
Robert Greenwalt7b816022014-04-18 15:25:25 -07002390 private void handleAsyncChannelHalfConnect(Message msg) {
2391 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002392 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002393 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2394 if (VDBG) log("NetworkFactory connected");
2395 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002396 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002397 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002398 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002399 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002400 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002401 }
2402 } else {
2403 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002404 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002405 }
2406 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2407 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2408 if (VDBG) log("NetworkAgent connected");
2409 // A network agent has requested a connection. Establish the connection.
2410 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2411 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2412 } else {
2413 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002414 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002415 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002416 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002417 synchronized (mNetworkForNetId) {
2418 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002419 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002420 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002421 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002422 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002423 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002424 }
2425 }
2426 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002427
Robert Greenwalt7b816022014-04-18 15:25:25 -07002428 private void handleAsyncChannelDisconnected(Message msg) {
2429 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2430 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002431 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002432 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002433 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002434 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002435 // TODO - if we move the logic to the network agent (have them disconnect
2436 // because they lost all their requests or because their score isn't good)
2437 // then they would disconnect organically, report their new state and then
2438 // disconnect the channel.
2439 if (nai.networkInfo.isConnected()) {
2440 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2441 null, null);
2442 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002443 final boolean wasDefault = isDefaultNetwork(nai);
2444 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002445 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002446 // Log default network disconnection before required book-keeping.
2447 // Let rematchAllNetworksAndRequests() below record a new default network event
2448 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2449 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002450 long now = SystemClock.elapsedRealtime();
2451 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002452 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002453 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002454 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2455 // by other networks that are already connected. Perhaps that can be done by
2456 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2457 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002458 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002459 mKeepaliveTracker.handleStopAllKeepalives(nai,
2460 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002461 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2462 // Disable wakeup packet monitoring for each interface.
2463 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2464 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002465 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002466 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002467 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002468 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002469 // Remove the NetworkAgent, but don't mark the netId as
2470 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002471 mNetworkForNetId.remove(nai.network.netId);
2472 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002473 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002474 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2475 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002476 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002477 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002478 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002479 sendUpdatedScoreToFactories(request, 0);
2480 }
2481 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002482 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002483 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002484 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002485 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002486 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002487 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002488 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002489 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002490 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002491 if (nai.created) {
2492 // Tell netd to clean up the configuration for this network
2493 // (routing rules, DNS, etc).
2494 // This may be slow as it requires a lot of netd shelling out to ip and
2495 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2496 // after we've rematched networks with requests which should make a potential
2497 // fallback network the default or requested a new network from the
2498 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2499 // long time.
2500 try {
2501 mNetd.removeNetwork(nai.network.netId);
2502 } catch (Exception e) {
2503 loge("Exception removing network: " + e);
2504 }
Erik Klinea24d4592018-01-11 21:07:29 +09002505 mDnsManager.removeNetwork(nai.network);
Paul Jensen62d30802015-06-17 14:42:30 -04002506 }
2507 synchronized (mNetworkForNetId) {
2508 mNetIdInUse.delete(nai.network.netId);
2509 }
2510 } else {
2511 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2512 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002513 }
2514 }
2515
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002516 // If this method proves to be too slow then we can maintain a separate
2517 // pendingIntent => NetworkRequestInfo map.
2518 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2519 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2520 Intent intent = pendingIntent.getIntent();
2521 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2522 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2523 if (existingPendingIntent != null &&
2524 existingPendingIntent.getIntent().filterEquals(intent)) {
2525 return entry.getValue();
2526 }
2527 }
2528 return null;
2529 }
2530
2531 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2532 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2533
2534 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2535 if (existingRequest != null) { // remove the existing request.
2536 if (DBG) log("Replacing " + existingRequest.request + " with "
2537 + nri.request + " because their intents matched.");
2538 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2539 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002540 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002541 }
2542
Erik Klineda4bfa82015-04-30 12:58:40 +09002543 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002544 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002545 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002546 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002547 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002548 if (nri.request.networkCapabilities.hasSignalStrength() &&
2549 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2550 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002551 }
2552 }
2553 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002554 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002555 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002556 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002557 }
2558 }
2559
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002560 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2561 int callingUid) {
2562 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2563 if (nri != null) {
2564 handleReleaseNetworkRequest(nri.request, callingUid);
2565 }
2566 }
2567
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002568 // Determines whether the network is the best (or could become the best, if it validated), for
2569 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2570 // on the value of reason:
2571 //
2572 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2573 // then it should be torn down.
2574 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2575 // then it should be lingered.
2576 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2577 final int numRequests;
2578 switch (reason) {
2579 case TEARDOWN:
2580 numRequests = nai.numRequestNetworkRequests();
2581 break;
2582 case LINGER:
2583 numRequests = nai.numForegroundNetworkRequests();
2584 break;
2585 default:
2586 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2587 return true;
2588 }
2589
2590 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002591 return false;
2592 }
Paul Jensene0988542015-06-25 15:30:08 -04002593 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002594 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2595 // Background requests don't affect lingering.
2596 continue;
2597 }
2598
Paul Jensene0988542015-06-25 15:30:08 -04002599 // If this Network is already the highest scoring Network for a request, or if
2600 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002601 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002602 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002603 // Note that this catches two important cases:
2604 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2605 // is currently satisfying the request. This is desirable when
2606 // cellular ends up validating but WiFi does not.
2607 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002608 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002609 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002610 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002611 nai.getCurrentScoreAsValidated())) {
2612 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002613 }
2614 }
Paul Jensene0988542015-06-25 15:30:08 -04002615 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002616 }
2617
Erik Klineacdd6392016-07-07 16:50:58 +09002618 private NetworkRequestInfo getNriForAppRequest(
2619 NetworkRequest request, int callingUid, String requestedOperation) {
2620 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2621
Robert Greenwalt9258c642014-03-26 16:47:06 -07002622 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002623 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002624 log(String.format("UID %d attempted to %s for unowned request %s",
2625 callingUid, requestedOperation, nri));
2626 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002627 }
Erik Klineacdd6392016-07-07 16:50:58 +09002628 }
2629
2630 return nri;
2631 }
2632
Erik Kline57faba92015-11-25 12:49:38 +09002633 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002634 if (mNetworkRequests.get(nri.request) == null) {
2635 return;
Erik Kline57faba92015-11-25 12:49:38 +09002636 }
Hugo Benichicd952782017-09-20 11:20:14 +09002637 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002638 return;
2639 }
2640 if (VDBG || (DBG && nri.request.isRequest())) {
2641 log("releasing " + nri.request + " (timeout)");
2642 }
2643 handleRemoveNetworkRequest(nri);
2644 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002645 }
2646
Erik Klineacdd6392016-07-07 16:50:58 +09002647 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002648 final NetworkRequestInfo nri =
2649 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2650 if (nri == null) {
2651 return;
Erik Kline57faba92015-11-25 12:49:38 +09002652 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002653 if (VDBG || (DBG && nri.request.isRequest())) {
2654 log("releasing " + nri.request + " (release request)");
2655 }
2656 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002657 }
Erik Klineacdd6392016-07-07 16:50:58 +09002658
Hugo Benichidba33db2017-03-23 22:40:44 +09002659 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002660 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002661 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002662
Erik Klineacdd6392016-07-07 16:50:58 +09002663 synchronized (mUidToNetworkRequestCount) {
2664 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2665 if (requests < 1) {
2666 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2667 nri.mUid);
2668 } else if (requests == 1) {
2669 mUidToNetworkRequestCount.removeAt(
2670 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2671 } else {
2672 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2673 }
2674 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002675
Erik Klineacdd6392016-07-07 16:50:58 +09002676 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2677 if (nri.request.isRequest()) {
2678 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002679 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002680 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002681 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002682 nai.removeRequest(nri.request.requestId);
2683 if (VDBG) {
2684 log(" Removing from current network " + nai.name() +
2685 ", leaving " + nai.numNetworkRequests() + " requests.");
2686 }
2687 // If there are still lingered requests on this network, don't tear it down,
2688 // but resume lingering instead.
2689 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002690 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002691 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2692 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002693 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002694 wasKept = true;
2695 }
Hugo Benichicd952782017-09-20 11:20:14 +09002696 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002697 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2698 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002699 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002700 }
Erik Klineacdd6392016-07-07 16:50:58 +09002701 }
2702
2703 // TODO: remove this code once we know that the Slog.wtf is never hit.
2704 //
2705 // Find all networks that are satisfying this request and remove the request
2706 // from their request lists.
2707 // TODO - it's my understanding that for a request there is only a single
2708 // network satisfying it, so this loop is wasteful
2709 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2710 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2711 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2712 otherNai.name() + ", but mNetworkAgentInfos says " +
2713 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002714 }
2715 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002716
Erik Klineacdd6392016-07-07 16:50:58 +09002717 // Maintain the illusion. When this request arrived, we might have pretended
2718 // that a network connected to serve it, even though the network was already
2719 // connected. Now that this request has gone away, we might have to pretend
2720 // that the network disconnected. LegacyTypeTracker will generate that
2721 // phantom disconnect for this type.
2722 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2723 boolean doRemove = true;
2724 if (wasKept) {
2725 // check if any of the remaining requests for this network are for the
2726 // same legacy type - if so, don't remove the nai
2727 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2728 NetworkRequest otherRequest = nai.requestAt(i);
2729 if (otherRequest.legacyType == nri.request.legacyType &&
2730 otherRequest.isRequest()) {
2731 if (DBG) log(" still have other legacy request - leaving");
2732 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002733 }
2734 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002735 }
2736
Erik Klineacdd6392016-07-07 16:50:58 +09002737 if (doRemove) {
2738 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002739 }
2740 }
Erik Klineacdd6392016-07-07 16:50:58 +09002741
2742 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2743 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2744 nri.request);
2745 }
2746 } else {
2747 // listens don't have a singular affectedNetwork. Check all networks to see
2748 // if this listen request applies and remove it.
2749 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2750 nai.removeRequest(nri.request.requestId);
2751 if (nri.request.networkCapabilities.hasSignalStrength() &&
2752 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2753 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2754 }
2755 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002756 }
2757 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002758
Lorenzo Colitti18660282016-07-04 12:55:44 +09002759 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002760 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2761 enforceConnectivityInternalPermission();
2762 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002763 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002764 }
2765
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002766 @Override
2767 public void setAvoidUnvalidated(Network network) {
2768 enforceConnectivityInternalPermission();
2769 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2770 }
2771
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002772 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2773 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2774 " accept=" + accept + " always=" + always);
2775
2776 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2777 if (nai == null) {
2778 // Nothing to do.
2779 return;
2780 }
2781
2782 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002783 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002784 return;
2785 }
2786
2787 if (!nai.networkMisc.explicitlySelected) {
2788 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2789 }
2790
2791 if (accept != nai.networkMisc.acceptUnvalidated) {
2792 int oldScore = nai.getCurrentScore();
2793 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002794 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002795 sendUpdatedScoreToFactories(nai);
2796 }
2797
2798 if (always) {
2799 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002800 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002801 }
2802
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002803 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002804 // Tell the NetworkAgent to not automatically reconnect to the network.
2805 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2806 // Teardown the nework.
2807 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002808 }
2809
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002810 }
2811
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002812 private void handleSetAvoidUnvalidated(Network network) {
2813 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2814 if (nai == null || nai.lastValidated) {
2815 // Nothing to do. The network either disconnected or revalidated.
2816 return;
2817 }
2818 if (!nai.avoidUnvalidated) {
2819 int oldScore = nai.getCurrentScore();
2820 nai.avoidUnvalidated = true;
2821 rematchAllNetworksAndRequests(nai, oldScore);
2822 sendUpdatedScoreToFactories(nai);
2823 }
2824 }
2825
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002826 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002827 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002828 mHandler.sendMessageDelayed(
2829 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2830 PROMPT_UNVALIDATED_DELAY_MS);
2831 }
2832
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002833 @Override
2834 public void startCaptivePortalApp(Network network) {
2835 enforceConnectivityInternalPermission();
2836 mHandler.post(() -> {
2837 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2838 if (nai == null) return;
2839 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2840 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2841 });
2842 }
2843
Hugo Benichic8e9e122016-09-14 23:23:08 +00002844 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002845 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002846 }
2847
Erik Kline065ab6e2016-10-02 18:02:14 +09002848 private void rematchForAvoidBadWifiUpdate() {
2849 rematchAllNetworksAndRequests(null, 0);
2850 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2851 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2852 sendUpdatedScoreToFactories(nai);
2853 }
2854 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002855 }
2856
Erik Kline065ab6e2016-10-02 18:02:14 +09002857 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002858 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002859 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002860 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002861 if (!configRestrict) {
2862 pw.println("Bad Wi-Fi avoidance: unrestricted");
2863 return;
2864 }
2865
2866 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2867 pw.increaseIndent();
2868 pw.println("Config restrict: " + configRestrict);
2869
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002870 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002871 String description;
2872 // Can't use a switch statement because strings are legal case labels, but null is not.
2873 if ("0".equals(value)) {
2874 description = "get stuck";
2875 } else if (value == null) {
2876 description = "prompt";
2877 } else if ("1".equals(value)) {
2878 description = "avoid";
2879 } else {
2880 description = value + " (?)";
2881 }
2882 pw.println("User setting: " + description);
2883 pw.println("Network overrides:");
2884 pw.increaseIndent();
2885 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2886 if (nai.avoidUnvalidated) {
2887 pw.println(nai.name());
2888 }
2889 }
2890 pw.decreaseIndent();
2891 pw.decreaseIndent();
2892 }
2893
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002894 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2895 final String action;
2896 switch (type) {
2897 case NO_INTERNET:
2898 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2899 break;
2900 case LOST_INTERNET:
2901 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2902 break;
2903 default:
2904 Slog.wtf(TAG, "Unknown notification type " + type);
2905 return;
2906 }
2907
2908 Intent intent = new Intent(action);
2909 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2910 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2911 intent.setClassName("com.android.settings",
2912 "com.android.settings.wifi.WifiNoInternetDialog");
2913
2914 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2915 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2916 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2917 }
2918
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002919 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002920 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002921 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2922
2923 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2924 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002925 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002926 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002927 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2928 return;
2929 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002930 showValidationNotification(nai, NotificationType.NO_INTERNET);
2931 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002932
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002933 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2934 NetworkCapabilities nc = nai.networkCapabilities;
2935 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002936
Erik Kline065ab6e2016-10-02 18:02:14 +09002937 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002938 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002939 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2940 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002941 }
2942
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002943 @Override
2944 public int getMultipathPreference(Network network) {
2945 enforceAccessPermission();
2946
2947 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002948 if (nai != null && nai.networkCapabilities
2949 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002950 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2951 }
2952
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002953 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
2954 if (networkPreference != null) {
2955 return networkPreference;
2956 }
2957
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002958 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2959 }
2960
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002961 private class InternalHandler extends Handler {
2962 public InternalHandler(Looper looper) {
2963 super(looper);
2964 }
2965
2966 @Override
2967 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002968 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002969 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002970 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002971 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002972 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002973 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002974 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002975 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002976 break;
2977 }
Jason Monkdecd2952013-10-10 14:02:51 -04002978 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002979 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002980 break;
2981 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002982 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002983 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2984 break;
2985 }
2986 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2987 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002988 break;
2989 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002990 case EVENT_REGISTER_NETWORK_AGENT: {
2991 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2992 break;
2993 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002994 case EVENT_REGISTER_NETWORK_REQUEST:
2995 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002996 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002997 break;
2998 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002999 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3000 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003001 handleRegisterNetworkRequestWithIntent(msg);
3002 break;
3003 }
Erik Kline57faba92015-11-25 12:49:38 +09003004 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3005 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3006 handleTimedOutNetworkRequest(nri);
3007 break;
3008 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003009 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3010 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3011 break;
3012 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003013 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003014 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003015 break;
3016 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003017 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003018 Network network = (Network) msg.obj;
3019 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003020 break;
3021 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003022 case EVENT_SET_AVOID_UNVALIDATED: {
3023 handleSetAvoidUnvalidated((Network) msg.obj);
3024 break;
3025 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003026 case EVENT_PROMPT_UNVALIDATED: {
3027 handlePromptUnvalidated((Network) msg.obj);
3028 break;
3029 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003030 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
3031 handleMobileDataAlwaysOn();
3032 break;
3033 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003034 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3035 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3036 mKeepaliveTracker.handleStartKeepalive(msg);
3037 break;
3038 }
3039 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3040 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3041 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3042 int slot = msg.arg1;
3043 int reason = msg.arg2;
3044 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3045 break;
3046 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003047 case EVENT_SYSTEM_READY: {
3048 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3049 nai.networkMonitor.systemReady = true;
3050 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003051 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003052 break;
3053 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003054 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003055 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003056 break;
3057 }
Erik Klinea24d4592018-01-11 21:07:29 +09003058 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3059 handlePrivateDnsSettingsChanged();
3060 break;
dalyk1fcb7392018-03-05 12:42:22 -05003061 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3062 handlePrivateDnsValidationUpdate(
3063 (PrivateDnsValidationUpdate) msg.obj);
3064 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 }
3066 }
3067 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003068
3069 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003070 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003071 public int tether(String iface, String callerPkg) {
3072 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003073 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003074 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003075 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003076 } else {
3077 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3078 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003079 }
3080
3081 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003082 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003083 public int untether(String iface, String callerPkg) {
3084 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003085
3086 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003087 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003088 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003089 } else {
3090 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3091 }
3092 }
3093
3094 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003095 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003096 public int getLastTetherError(String iface) {
3097 enforceTetherAccessPermission();
3098
3099 if (isTetheringSupported()) {
3100 return mTethering.getLastTetherError(iface);
3101 } else {
3102 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3103 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003104 }
3105
3106 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003107 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003108 public String[] getTetherableUsbRegexs() {
3109 enforceTetherAccessPermission();
3110 if (isTetheringSupported()) {
3111 return mTethering.getTetherableUsbRegexs();
3112 } else {
3113 return new String[0];
3114 }
3115 }
3116
Lorenzo Colitti18660282016-07-04 12:55:44 +09003117 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003118 public String[] getTetherableWifiRegexs() {
3119 enforceTetherAccessPermission();
3120 if (isTetheringSupported()) {
3121 return mTethering.getTetherableWifiRegexs();
3122 } else {
3123 return new String[0];
3124 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003125 }
3126
Lorenzo Colitti18660282016-07-04 12:55:44 +09003127 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003128 public String[] getTetherableBluetoothRegexs() {
3129 enforceTetherAccessPermission();
3130 if (isTetheringSupported()) {
3131 return mTethering.getTetherableBluetoothRegexs();
3132 } else {
3133 return new String[0];
3134 }
3135 }
3136
Lorenzo Colitti18660282016-07-04 12:55:44 +09003137 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003138 public int setUsbTethering(boolean enable, String callerPkg) {
3139 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003140 if (isTetheringSupported()) {
3141 return mTethering.setUsbTethering(enable);
3142 } else {
3143 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3144 }
3145 }
3146
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003147 // TODO - move iface listing, queries, etc to new module
3148 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003149 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003150 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003151 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003152 return mTethering.getTetherableIfaces();
3153 }
3154
Lorenzo Colitti18660282016-07-04 12:55:44 +09003155 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003156 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003157 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003158 return mTethering.getTetheredIfaces();
3159 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003160
Lorenzo Colitti18660282016-07-04 12:55:44 +09003161 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003162 public String[] getTetheringErroredIfaces() {
3163 enforceTetherAccessPermission();
3164 return mTethering.getErroredIfaces();
3165 }
3166
Lorenzo Colitti18660282016-07-04 12:55:44 +09003167 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003168 public String[] getTetheredDhcpRanges() {
3169 enforceConnectivityInternalPermission();
3170 return mTethering.getTetheredDhcpRanges();
3171 }
3172
Udam Saini0e94c362017-06-07 12:06:28 -07003173 @Override
3174 public boolean isTetheringSupported(String callerPkg) {
3175 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3176 return isTetheringSupported();
3177 }
3178
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003179 // if ro.tether.denied = true we default to no tethering
3180 // gservices could set the secure setting to 1 though to enable it on a build where it
3181 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003182 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003183 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3184 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3185 Settings.Global.TETHER_SUPPORTED, defaultVal));
3186 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003187 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003188
3189 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3190 boolean adminUser = false;
3191 final long token = Binder.clearCallingIdentity();
3192 try {
3193 adminUser = mUserManager.isAdminUser();
3194 } finally {
3195 Binder.restoreCallingIdentity(token);
3196 }
3197
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003198 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003199 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003200
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003201 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003202 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3203 String callerPkg) {
3204 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003205 if (!isTetheringSupported()) {
3206 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3207 return;
3208 }
3209 mTethering.startTethering(type, receiver, showProvisioningUi);
3210 }
3211
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003212 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003213 public void stopTethering(int type, String callerPkg) {
3214 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003215 mTethering.stopTethering(type);
3216 }
3217
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003218 // Called when we lose the default network and have no replacement yet.
3219 // This will automatically be cleared after X seconds or a new default network
3220 // becomes CONNECTED, whichever happens first. The timer is started by the
3221 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003222 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003223 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003224 if (mNetTransitionWakeLock.isHeld()) {
3225 return;
3226 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003227 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003228 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3229 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003230 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003231 mWakelockLogs.log("ACQUIRE for " + forWhom);
3232 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3233 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003234 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003235
Hugo Benichi4c31b342017-03-30 23:18:10 +09003236 // Called when we gain a new default network to release the network transition wakelock in a
3237 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3238 // message is cancelled.
3239 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003240 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003241 if (!mNetTransitionWakeLock.isHeld()) {
3242 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003243 }
3244 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003245 // Cancel self timeout on wakelock hold.
3246 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3247 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3248 mHandler.sendMessageDelayed(msg, 1000);
3249 }
3250
3251 // Called when either message of ensureNetworkTransitionWakelock or
3252 // scheduleReleaseNetworkTransitionWakelock is processed.
3253 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3254 String event = eventName(eventId);
3255 synchronized (this) {
3256 if (!mNetTransitionWakeLock.isHeld()) {
3257 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3258 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3259 return;
3260 }
3261 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003262 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3263 mTotalWakelockDurationMs += lockDuration;
3264 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3265 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003266 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003267 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003268 }
3269
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003270 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003271 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003272 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003273 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003274 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003275 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003276 }
3277
Lorenzo Colitti18660282016-07-04 12:55:44 +09003278 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003279 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003280 enforceAccessPermission();
3281 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003282 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003283 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003284 mHandler.sendMessage(
3285 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3286 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003287
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003288 private void handleReportNetworkConnectivity(
3289 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003290 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003291 if (network == null) {
3292 nai = getDefaultNetwork();
3293 } else {
3294 nai = getNetworkAgentInfoForNetwork(network);
3295 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003296 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3297 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3298 return;
3299 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003300 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003301 if (hasConnectivity == nai.lastValidated) {
3302 return;
3303 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003304 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003305 int netid = nai.network.netId;
3306 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003307 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003308 // Validating a network that has not yet connected could result in a call to
3309 // rematchNetworkAndRequests() which is not meant to work on such networks.
3310 if (!nai.everConnected) {
3311 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003312 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003313 LinkProperties lp = getLinkProperties(nai);
3314 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3315 return;
3316 }
Erik Kline79c6d052018-03-21 07:18:33 -07003317 nai.networkMonitor.forceReevaluation(uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003318 }
3319
Paul Jensencee9b512015-05-06 07:32:40 -04003320 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003321 // this information is already available as a world read/writable jvm property
3322 // so this API change wouldn't have a benifit. It also breaks the passing
3323 // of proxy info to all the JVMs.
3324 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003325 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003326 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003327 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3328 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003329 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003330 }
3331
Lorenzo Colitti18660282016-07-04 12:55:44 +09003332 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003333 public ProxyInfo getProxyForNetwork(Network network) {
3334 if (network == null) return getDefaultProxy();
3335 final ProxyInfo globalProxy = getGlobalProxy();
3336 if (globalProxy != null) return globalProxy;
3337 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3338 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3339 // caller may not have.
3340 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3341 if (nai == null) return null;
3342 synchronized (nai) {
3343 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3344 if (proxyInfo == null) return null;
3345 return new ProxyInfo(proxyInfo);
3346 }
3347 }
3348
Paul Jensene0bef712014-12-10 15:12:18 -05003349 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3350 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3351 // proxy is null then there is no proxy in place).
3352 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3353 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3354 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3355 proxy = null;
3356 }
3357 return proxy;
3358 }
3359
3360 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3361 // better for determining if a new proxy broadcast is necessary:
3362 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3363 // avoid unnecessary broadcasts.
3364 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3365 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3366 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3367 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3368 // all set.
3369 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3370 a = canonicalizeProxyInfo(a);
3371 b = canonicalizeProxyInfo(b);
3372 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3373 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3374 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3375 }
3376
Jason Monk207900c2014-04-25 15:00:09 -04003377 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003378 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003379
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003380 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003381 if (proxyProperties == mGlobalProxy) return;
3382 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3383 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3384
3385 String host = "";
3386 int port = 0;
3387 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003388 String pacFileUrl = "";
3389 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003390 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003391 if (!proxyProperties.isValid()) {
3392 if (DBG)
3393 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3394 return;
3395 }
Jason Monk207900c2014-04-25 15:00:09 -04003396 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003397 host = mGlobalProxy.getHost();
3398 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003399 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003400 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003401 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003402 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003403 } else {
3404 mGlobalProxy = null;
3405 }
3406 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003407 final long token = Binder.clearCallingIdentity();
3408 try {
3409 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3410 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3411 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3412 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003413 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003414 } finally {
3415 Binder.restoreCallingIdentity(token);
3416 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003417
Jason Monkcf0f97a2014-10-02 15:39:38 -04003418 if (mGlobalProxy == null) {
3419 proxyProperties = mDefaultProxy;
3420 }
3421 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003422 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003423 }
3424
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003425 private void loadGlobalProxy() {
3426 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003427 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3428 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3429 String exclList = Settings.Global.getString(res,
3430 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003431 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3432 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003433 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003434 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003435 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003436 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003437 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003438 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003439 if (!proxyProperties.isValid()) {
3440 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3441 return;
3442 }
3443
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003444 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003445 mGlobalProxy = proxyProperties;
3446 }
3447 }
3448 }
3449
Jason Monk207900c2014-04-25 15:00:09 -04003450 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003451 // this information is already available as a world read/writable jvm property
3452 // so this API change wouldn't have a benifit. It also breaks the passing
3453 // of proxy info to all the JVMs.
3454 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003455 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003456 return mGlobalProxy;
3457 }
3458 }
3459
Jason Monk207900c2014-04-25 15:00:09 -04003460 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003461 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003462 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003463 proxy = null;
3464 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003465 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003466 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003467 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003468 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003469 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3470 return;
3471 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003472
3473 // This call could be coming from the PacManager, containing the port of the local
3474 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3475 // global (to get the correct local port), and send a broadcast.
3476 // TODO: Switch PacManager to have its own message to send back rather than
3477 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003478 if ((mGlobalProxy != null) && (proxy != null)
3479 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003480 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3481 mGlobalProxy = proxy;
3482 sendProxyBroadcast(mGlobalProxy);
3483 return;
3484 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003485 mDefaultProxy = proxy;
3486
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003487 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003488 if (!mDefaultProxyDisabled) {
3489 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003490 }
3491 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003492 }
3493
Paul Jensene0bef712014-12-10 15:12:18 -05003494 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3495 // This method gets called when any network changes proxy, but the broadcast only ever contains
3496 // the default proxy (even if it hasn't changed).
3497 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3498 // world where an app might be bound to a non-default network.
3499 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3500 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3501 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3502
3503 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3504 sendProxyBroadcast(getDefaultProxy());
3505 }
3506 }
3507
Robert Greenwalt434203a2010-10-11 16:00:27 -07003508 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003509 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3510 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003511 if (!TextUtils.isEmpty(proxy)) {
3512 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003513 if (data.length == 0) {
3514 return;
3515 }
3516
Robert Greenwalt434203a2010-10-11 16:00:27 -07003517 String proxyHost = data[0];
3518 int proxyPort = 8080;
3519 if (data.length > 1) {
3520 try {
3521 proxyPort = Integer.parseInt(data[1]);
3522 } catch (NumberFormatException e) {
3523 return;
3524 }
3525 }
Jason Monk207900c2014-04-25 15:00:09 -04003526 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003527 setGlobalProxy(p);
3528 }
3529 }
3530
Jason Monk207900c2014-04-25 15:00:09 -04003531 private void sendProxyBroadcast(ProxyInfo proxy) {
3532 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003533 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003534 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003535 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003536 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3537 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003538 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003539 final long ident = Binder.clearCallingIdentity();
3540 try {
3541 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3542 } finally {
3543 Binder.restoreCallingIdentity(ident);
3544 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003545 }
3546
3547 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003548 final private HashMap<Uri, Integer> mUriEventMap;
3549 final private Context mContext;
3550 final private Handler mHandler;
3551
3552 SettingsObserver(Context context, Handler handler) {
3553 super(null);
3554 mUriEventMap = new HashMap<Uri, Integer>();
3555 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003556 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003557 }
3558
Erik Klineda4bfa82015-04-30 12:58:40 +09003559 void observe(Uri uri, int what) {
3560 mUriEventMap.put(uri, what);
3561 final ContentResolver resolver = mContext.getContentResolver();
3562 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003563 }
3564
3565 @Override
3566 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003567 Slog.wtf(TAG, "Should never be reached.");
3568 }
3569
3570 @Override
3571 public void onChange(boolean selfChange, Uri uri) {
3572 final Integer what = mUriEventMap.get(uri);
3573 if (what != null) {
3574 mHandler.obtainMessage(what.intValue()).sendToTarget();
3575 } else {
3576 loge("No matching event to send for URI=" + uri);
3577 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003578 }
3579 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003580
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003581 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003582 Slog.d(TAG, s);
3583 }
3584
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003585 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003586 Slog.e(TAG, s);
3587 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003588
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003589 private static void loge(String s, Throwable t) {
3590 Slog.e(TAG, s, t);
3591 }
3592
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003593 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003594 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003595 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3596 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3597 *
3598 * @param oldPackage Package name of the application which currently controls VPN, which will
3599 * be replaced. If there is no such application, this should should either be
3600 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3601 * @param newPackage Package name of the application which should gain control of VPN, or
3602 * {@code null} to disable.
3603 * @param userId User for whom to prepare the new VPN.
3604 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003605 * @hide
3606 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003607 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003608 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3609 int userId) {
3610 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003611
Hugo Benichi20035e02017-04-26 14:53:28 +09003612 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003613 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003614 Vpn vpn = mVpns.get(userId);
3615 if (vpn != null) {
3616 return vpn.prepare(oldPackage, newPackage);
3617 } else {
3618 return false;
3619 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003620 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003621 }
3622
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003623 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003624 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3625 * This method is used by system-privileged apps.
3626 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3627 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3628 *
3629 * @param packageName The package for which authorization state should change.
3630 * @param userId User for whom {@code packageName} is installed.
3631 * @param authorized {@code true} if this app should be able to start a VPN connection without
3632 * explicit user approval, {@code false} if not.
3633 *
Jeff Davidson05542602014-08-11 14:07:27 -07003634 * @hide
3635 */
3636 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003637 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3638 enforceCrossUserPermission(userId);
3639
Hugo Benichi20035e02017-04-26 14:53:28 +09003640 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003641 Vpn vpn = mVpns.get(userId);
3642 if (vpn != null) {
3643 vpn.setPackageAuthorization(packageName, authorized);
3644 }
Jeff Davidson05542602014-08-11 14:07:27 -07003645 }
3646 }
3647
3648 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003649 * Configure a TUN interface and return its file descriptor. Parameters
3650 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003651 * and not available in ConnectivityManager. Permissions are checked in
3652 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003653 * @hide
3654 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003655 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003656 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003657 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003658 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003659 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003660 return mVpns.get(user).establish(config);
3661 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003662 }
3663
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003664 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003665 * Start legacy VPN, controlling native daemons as needed. Creates a
3666 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003667 */
3668 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003669 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003670 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003671 final LinkProperties egress = getActiveLinkProperties();
3672 if (egress == null) {
3673 throw new IllegalStateException("Missing active network connection");
3674 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003675 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003676 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003677 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3678 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003679 }
3680
3681 /**
3682 * Return the information of the ongoing legacy VPN. This method is used
3683 * by VpnSettings and not available in ConnectivityManager. Permissions
3684 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003685 */
3686 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003687 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3688 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003689
Hugo Benichi20035e02017-04-26 14:53:28 +09003690 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003691 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003692 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003693 }
3694
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003695 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003696 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3697 * and not available in ConnectivityManager.
3698 */
3699 @Override
3700 public VpnInfo[] getAllVpnInfo() {
3701 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003702 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003703 if (mLockdownEnabled) {
3704 return new VpnInfo[0];
3705 }
3706
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003707 List<VpnInfo> infoList = new ArrayList<>();
3708 for (int i = 0; i < mVpns.size(); i++) {
3709 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3710 if (info != null) {
3711 infoList.add(info);
3712 }
3713 }
3714 return infoList.toArray(new VpnInfo[infoList.size()]);
3715 }
3716 }
3717
3718 /**
3719 * @return VPN information for accounting, or null if we can't retrieve all required
3720 * information, e.g primary underlying iface.
3721 */
3722 @Nullable
3723 private VpnInfo createVpnInfo(Vpn vpn) {
3724 VpnInfo info = vpn.getVpnInfo();
3725 if (info == null) {
3726 return null;
3727 }
3728 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3729 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3730 // the underlyingNetworks list.
3731 if (underlyingNetworks == null) {
3732 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3733 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3734 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3735 }
3736 } else if (underlyingNetworks.length > 0) {
3737 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3738 if (linkProperties != null) {
3739 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3740 }
3741 }
3742 return info.primaryUnderlyingIface == null ? null : info;
3743 }
3744
3745 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003746 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3747 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003748 * Permissions are checked in Vpn class.
3749 * @hide
3750 */
3751 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003752 public VpnConfig getVpnConfig(int userId) {
3753 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003754 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003755 Vpn vpn = mVpns.get(userId);
3756 if (vpn != null) {
3757 return vpn.getVpnConfig();
3758 } else {
3759 return null;
3760 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003761 }
3762 }
3763
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003764 @Override
3765 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003766 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3767 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3768 return false;
3769 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003770
Hugo Benichi69744342017-11-27 10:57:16 +09003771 synchronized (mVpns) {
3772 // Tear down existing lockdown if profile was removed
3773 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3774 if (mLockdownEnabled) {
3775 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3776 if (profileTag == null) {
3777 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3778 return false;
3779 }
3780 String profileName = new String(profileTag);
3781 final VpnProfile profile = VpnProfile.decode(
3782 profileName, mKeyStore.get(Credentials.VPN + profileName));
3783 if (profile == null) {
3784 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3785 setLockdownTracker(null);
3786 return true;
3787 }
3788 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003789 Vpn vpn = mVpns.get(user);
3790 if (vpn == null) {
3791 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3792 return false;
3793 }
3794 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003795 } else {
3796 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003797 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003798 }
3799
3800 return true;
3801 }
3802
3803 /**
3804 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3805 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3806 */
Hugo Benichi69744342017-11-27 10:57:16 +09003807 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003808 private void setLockdownTracker(LockdownVpnTracker tracker) {
3809 // Shutdown any existing tracker
3810 final LockdownVpnTracker existing = mLockdownTracker;
3811 mLockdownTracker = null;
3812 if (existing != null) {
3813 existing.shutdown();
3814 }
3815
Robin Leec3736bc2017-03-10 16:19:54 +00003816 if (tracker != null) {
3817 mLockdownTracker = tracker;
3818 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003819 }
3820 }
3821
Hugo Benichi69744342017-11-27 10:57:16 +09003822 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003823 private void throwIfLockdownEnabled() {
3824 if (mLockdownEnabled) {
3825 throw new IllegalStateException("Unavailable in lockdown mode");
3826 }
3827 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003828
Robin Lee244ce8e2016-01-05 18:03:46 +00003829 /**
Robin Lee17e61832016-05-09 13:46:28 +01003830 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3831 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003832 *
Robin Lee17e61832016-05-09 13:46:28 +01003833 * @return {@code true} if the service was started, the service was already connected, or there
3834 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003835 */
Robin Lee17e61832016-05-09 13:46:28 +01003836 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003837 synchronized (mVpns) {
3838 Vpn vpn = mVpns.get(userId);
3839 if (vpn == null) {
3840 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3841 // exists already.
3842 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3843 return false;
3844 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003845
Robin Lee812800c2016-05-13 15:38:08 +01003846 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003847 }
3848 }
3849
3850 @Override
Charles He36738632017-05-15 17:07:18 +01003851 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3852 enforceSettingsPermission();
3853 enforceCrossUserPermission(userId);
3854
3855 synchronized (mVpns) {
3856 Vpn vpn = mVpns.get(userId);
3857 if (vpn == null) {
3858 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3859 return false;
3860 }
3861 return vpn.isAlwaysOnPackageSupported(packageName);
3862 }
3863 }
3864
3865 @Override
Robin Leedc679712016-05-03 13:23:03 +01003866 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003867 enforceConnectivityInternalPermission();
3868 enforceCrossUserPermission(userId);
3869
Robin Lee244ce8e2016-01-05 18:03:46 +00003870 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003871 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3872 if (LockdownVpnTracker.isEnabled()) {
3873 return false;
3874 }
3875
Robin Lee244ce8e2016-01-05 18:03:46 +00003876 Vpn vpn = mVpns.get(userId);
3877 if (vpn == null) {
3878 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3879 return false;
3880 }
Robin Lee17e61832016-05-09 13:46:28 +01003881 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003882 return false;
3883 }
Robin Lee17e61832016-05-09 13:46:28 +01003884 if (!startAlwaysOnVpn(userId)) {
3885 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003886 return false;
3887 }
3888 }
3889 return true;
3890 }
3891
3892 @Override
3893 public String getAlwaysOnVpnPackage(int userId) {
3894 enforceConnectivityInternalPermission();
3895 enforceCrossUserPermission(userId);
3896
3897 synchronized (mVpns) {
3898 Vpn vpn = mVpns.get(userId);
3899 if (vpn == null) {
3900 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3901 return null;
3902 }
3903 return vpn.getAlwaysOnPackage();
3904 }
3905 }
3906
Wink Savilleab9321d2013-06-29 21:10:57 -07003907 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003908 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003909 // TODO: Remove? Any reason to trigger a provisioning check?
3910 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003911 }
3912
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003913 /** Location to an updatable file listing carrier provisioning urls.
3914 * An example:
3915 *
3916 * <?xml version="1.0" encoding="utf-8"?>
3917 * <provisioningUrls>
3918 * <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 -07003919 * </provisioningUrls>
3920 */
3921 private static final String PROVISIONING_URL_PATH =
3922 "/data/misc/radio/provisioning_urls.xml";
3923 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003924
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003925 /** XML tag for root element. */
3926 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3927 /** XML tag for individual url */
3928 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003929 /** XML attribute for mcc */
3930 private static final String ATTR_MCC = "mcc";
3931 /** XML attribute for mnc */
3932 private static final String ATTR_MNC = "mnc";
3933
Paul Jensen434dde82015-06-11 09:43:30 -04003934 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003935 FileReader fileReader = null;
3936 XmlPullParser parser = null;
3937 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003938
3939 try {
3940 fileReader = new FileReader(mProvisioningUrlFile);
3941 parser = Xml.newPullParser();
3942 parser.setInput(fileReader);
3943 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3944
3945 while (true) {
3946 XmlUtils.nextElement(parser);
3947
3948 String element = parser.getName();
3949 if (element == null) break;
3950
Paul Jensen434dde82015-06-11 09:43:30 -04003951 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003952 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3953 try {
3954 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3955 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3956 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3957 parser.next();
3958 if (parser.getEventType() == XmlPullParser.TEXT) {
3959 return parser.getText();
3960 }
3961 }
3962 }
3963 } catch (NumberFormatException e) {
3964 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3965 }
3966 }
3967 }
3968 return null;
3969 } catch (FileNotFoundException e) {
3970 loge("Carrier Provisioning Urls file not found");
3971 } catch (XmlPullParserException e) {
3972 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3973 } catch (IOException e) {
3974 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3975 } finally {
3976 if (fileReader != null) {
3977 try {
3978 fileReader.close();
3979 } catch (IOException e) {}
3980 }
3981 }
3982 return null;
3983 }
3984
Wink Saville42d4f082013-07-20 20:31:59 -07003985 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003986 public String getMobileProvisioningUrl() {
3987 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003988 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003989 if (TextUtils.isEmpty(url)) {
3990 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003991 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003992 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003993 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003994 }
Wink Saville8cf35602013-07-10 23:00:07 -07003995 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003996 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003997 String phoneNumber = mTelephonyManager.getLine1Number();
3998 if (TextUtils.isEmpty(phoneNumber)) {
3999 phoneNumber = "0000000000";
4000 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004001 url = String.format(url,
4002 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4003 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07004004 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004005 }
4006
Wink Savilleab9321d2013-06-29 21:10:57 -07004007 return url;
4008 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004009
Wink Saville948282b2013-08-29 08:55:16 -07004010 @Override
4011 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004012 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004013 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004014 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4015 return;
4016 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004017 final long ident = Binder.clearCallingIdentity();
4018 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004019 // Concatenate the range of types onto the range of NetIDs.
4020 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4021 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004022 } finally {
4023 Binder.restoreCallingIdentity(ident);
4024 }
Wink Saville948282b2013-08-29 08:55:16 -07004025 }
Wink Saville7788c612013-08-29 14:57:08 -07004026
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004027 @Override
4028 public void setAirplaneMode(boolean enable) {
4029 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004030 final long ident = Binder.clearCallingIdentity();
4031 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004032 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004033 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004034 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4035 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004036 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004037 } finally {
4038 Binder.restoreCallingIdentity(ident);
4039 }
4040 }
4041
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004042 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004043 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004044 Vpn userVpn = mVpns.get(userId);
4045 if (userVpn != null) {
4046 loge("Starting user already has a VPN");
4047 return;
4048 }
Paul Jensene75b9e32015-04-06 11:54:53 -04004049 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004050 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004051 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4052 updateLockdownVpn();
4053 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004054 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004055 }
4056
4057 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004058 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004059 Vpn userVpn = mVpns.get(userId);
4060 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004061 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004062 return;
4063 }
Robin Lee17e61832016-05-09 13:46:28 +01004064 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004065 mVpns.delete(userId);
4066 }
4067 }
4068
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004069 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004070 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004071 final int vpnsSize = mVpns.size();
4072 for (int i = 0; i < vpnsSize; i++) {
4073 Vpn vpn = mVpns.valueAt(i);
4074 vpn.onUserAdded(userId);
4075 }
4076 }
4077 }
4078
4079 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004080 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004081 final int vpnsSize = mVpns.size();
4082 for (int i = 0; i < vpnsSize; i++) {
4083 Vpn vpn = mVpns.valueAt(i);
4084 vpn.onUserRemoved(userId);
4085 }
4086 }
4087 }
4088
Robin Lee89e7a692016-02-29 14:38:17 +00004089 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004090 synchronized (mVpns) {
4091 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4092 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4093 updateLockdownVpn();
4094 } else {
4095 startAlwaysOnVpn(userId);
4096 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004097 }
4098 }
4099
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004100 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4101 @Override
4102 public void onReceive(Context context, Intent intent) {
4103 final String action = intent.getAction();
4104 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4105 if (userId == UserHandle.USER_NULL) return;
4106
Robin Lee323f29d2016-05-04 16:38:06 +01004107 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004108 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004109 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004110 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004111 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4112 onUserAdded(userId);
4113 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4114 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004115 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4116 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004117 }
4118 }
4119 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004120
Robin Lee95204e02017-01-27 11:59:22 +00004121 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4122 @Override
4123 public void onReceive(Context context, Intent intent) {
4124 // Try creating lockdown tracker, since user present usually means
4125 // unlocked keystore.
4126 updateLockdownVpn();
4127 mContext.unregisterReceiver(this);
4128 }
4129 };
4130
Robert Greenwalta67be032014-05-16 15:49:14 -07004131 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4132 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004133 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4134 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004135
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004136 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4137 // Map from UID to number of NetworkRequests that UID has filed.
4138 @GuardedBy("mUidToNetworkRequestCount")
4139 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4140
Robert Greenwalta67be032014-05-16 15:49:14 -07004141 private static class NetworkFactoryInfo {
4142 public final String name;
4143 public final Messenger messenger;
4144 public final AsyncChannel asyncChannel;
4145
4146 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4147 this.name = name;
4148 this.messenger = messenger;
4149 this.asyncChannel = asyncChannel;
4150 }
4151 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004152
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004153 private void ensureNetworkRequestHasType(NetworkRequest request) {
4154 if (request.type == NetworkRequest.Type.NONE) {
4155 throw new IllegalArgumentException(
4156 "All NetworkRequests in ConnectivityService must have a type");
4157 }
4158 }
4159
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004160 /**
4161 * Tracks info about the requester.
4162 * Also used to notice when the calling process dies so we can self-expire
4163 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004164 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004165 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004166 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004167 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004168 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004169 final int mPid;
4170 final int mUid;
4171 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004172
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004173 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004174 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004175 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004176 mPendingIntent = pi;
4177 messenger = null;
4178 mBinder = null;
4179 mPid = getCallingPid();
4180 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004181 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004182 }
4183
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004184 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004185 super();
4186 messenger = m;
4187 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004188 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004189 mBinder = binder;
4190 mPid = getCallingPid();
4191 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004192 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004193 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004194
4195 try {
4196 mBinder.linkToDeath(this, 0);
4197 } catch (RemoteException e) {
4198 binderDied();
4199 }
4200 }
4201
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004202 private void enforceRequestCountLimit() {
4203 synchronized (mUidToNetworkRequestCount) {
4204 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4205 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004206 throw new ServiceSpecificException(
4207 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004208 }
4209 mUidToNetworkRequestCount.put(mUid, networkRequests);
4210 }
4211 }
4212
Robert Greenwalt9258c642014-03-26 16:47:06 -07004213 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004214 if (mBinder != null) {
4215 mBinder.unlinkToDeath(this, 0);
4216 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004217 }
4218
4219 public void binderDied() {
4220 log("ConnectivityService NetworkRequestInfo binderDied(" +
4221 request + ", " + mBinder + ")");
4222 releaseNetworkRequest(request);
4223 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004224
4225 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004226 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004227 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004228 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004229 }
4230
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004231 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4232 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4233 if (badCapability != null) {
4234 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004235 }
4236 }
4237
Erik Kline9d598e12015-07-13 16:37:51 +09004238 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004239 final SortedSet<Integer> thresholds = new TreeSet();
4240 synchronized (nai) {
4241 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4242 if (nri.request.networkCapabilities.hasSignalStrength() &&
4243 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4244 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4245 }
4246 }
4247 }
Erik Kline9d598e12015-07-13 16:37:51 +09004248 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004249 }
4250
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004251 private void updateSignalStrengthThresholds(
4252 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4253 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004254 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004255 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4256
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004257 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004258 String detail;
4259 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4260 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4261 } else {
4262 detail = reason;
4263 }
4264 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4265 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4266 }
4267
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004268 nai.asyncChannel.sendMessage(
4269 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004270 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004271 }
4272
Etan Cohen859748f2017-04-03 17:42:34 -07004273 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4274 if (nc == null) {
4275 return;
4276 }
4277 NetworkSpecifier ns = nc.getNetworkSpecifier();
4278 if (ns == null) {
4279 return;
4280 }
4281 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4282 ns.assertValidFromUid(Binder.getCallingUid());
4283 }
4284
Robert Greenwalt9258c642014-03-26 16:47:06 -07004285 @Override
4286 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004287 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004288 final NetworkRequest.Type type = (networkCapabilities == null)
4289 ? NetworkRequest.Type.TRACK_DEFAULT
4290 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004291 // If the requested networkCapabilities is null, take them instead from
4292 // the default network request. This allows callers to keep track of
4293 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004294 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004295 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004296 networkCapabilities.removeCapability(NET_CAPABILITY_NOT_VPN);
Erik Klinea2d29402016-03-16 15:31:39 +09004297 enforceAccessPermission();
4298 } else {
4299 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4300 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004301 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4302 // of the app when the request is filed, but we never change the request if the app
4303 // changes network state. http://b/29964605
4304 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004305 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004306 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004307 // Set the UID range for this request to the single UID of the requester, or to an empty
4308 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004309 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4310 // are no visible methods to set the UIDs, an app could use reflection to try and get
4311 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004312 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004313
Etan Cohenba07c8c2017-02-05 10:42:27 -08004314 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004315 throw new IllegalArgumentException("Bad timeout specified");
4316 }
Etan Cohen859748f2017-04-03 17:42:34 -07004317 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004318
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004319 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004320 nextNetworkRequestId(), type);
4321 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004322 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004323
4324 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004325 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004326 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004327 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004328 }
4329 return networkRequest;
4330 }
4331
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004332 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004333 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004334 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004335 } else {
4336 enforceChangePermission();
4337 }
4338 }
4339
fenglub15e72b2015-03-20 11:29:56 -07004340 @Override
fengludb571472015-04-21 17:12:05 -07004341 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004342 enforceAccessPermission();
4343 NetworkAgentInfo nai = null;
4344 if (network == null) {
4345 return false;
4346 }
4347 synchronized (mNetworkForNetId) {
4348 nai = mNetworkForNetId.get(network.netId);
4349 }
4350 if (nai != null) {
4351 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4352 return true;
4353 }
4354 return false;
4355 }
4356
Felipe Lemeee27cab2016-06-20 16:36:29 -07004357 private boolean isSystem(int uid) {
4358 return uid < Process.FIRST_APPLICATION_UID;
4359 }
fenglub15e72b2015-03-20 11:29:56 -07004360
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004361 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004362 final int uid = Binder.getCallingUid();
4363 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004364 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004365 return;
4366 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004367 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4368 // Policy already enforced.
4369 return;
4370 }
4371 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4372 // If UID is restricted, don't allow them to bring up metered APNs.
4373 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004374 }
4375 }
4376
Robert Greenwalt9258c642014-03-26 16:47:06 -07004377 @Override
4378 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4379 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004380 checkNotNull(operation, "PendingIntent cannot be null.");
4381 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4382 enforceNetworkRequestPermissions(networkCapabilities);
4383 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004384 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004385 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004386 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004387
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004388 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004389 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4390 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004391 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004392 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4393 nri));
4394 return networkRequest;
4395 }
4396
Jeremy Joslin79294842014-12-03 17:15:28 -08004397 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4398 mHandler.sendMessageDelayed(
4399 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4400 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4401 }
4402
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004403 @Override
4404 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004405 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004406 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4407 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004408 }
4409
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004410 // In order to implement the compatibility measure for pre-M apps that call
4411 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4412 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4413 // This ensures it has permission to do so.
4414 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4415 if (nc == null) {
4416 return false;
4417 }
4418 int[] transportTypes = nc.getTransportTypes();
4419 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4420 return false;
4421 }
4422 try {
4423 mContext.enforceCallingOrSelfPermission(
4424 android.Manifest.permission.ACCESS_WIFI_STATE,
4425 "ConnectivityService");
4426 } catch (SecurityException e) {
4427 return false;
4428 }
4429 return true;
4430 }
4431
Robert Greenwalt9258c642014-03-26 16:47:06 -07004432 @Override
4433 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4434 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004435 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4436 enforceAccessPermission();
4437 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004438
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004439 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004440 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09004441 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4442 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4443 // onLost and onAvailable callbacks when networks move in and out of the background.
4444 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4445 // can't request networks.
4446 restrictBackgroundRequestForCaller(nc);
4447 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004448
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004449 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004450 NetworkRequest.Type.LISTEN);
4451 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004452 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004453
4454 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4455 return networkRequest;
4456 }
4457
4458 @Override
4459 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4460 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004461 checkNotNull(operation, "PendingIntent cannot be null.");
4462 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4463 enforceAccessPermission();
4464 }
Etan Cohen859748f2017-04-03 17:42:34 -07004465 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004466
Chalard Jeandda156a2018-01-10 21:19:32 +09004467 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004468 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004469
4470 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004471 NetworkRequest.Type.LISTEN);
4472 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004473 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004474
4475 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004476 }
4477
Erik Klineacdd6392016-07-07 16:50:58 +09004478 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004479 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004480 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004481 mHandler.sendMessage(mHandler.obtainMessage(
4482 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004483 }
4484
4485 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004486 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004487 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004488 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4489 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004490 }
4491
Robert Greenwalta67be032014-05-16 15:49:14 -07004492 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004493 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004494 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4495 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4496 }
4497
4498 @Override
4499 public void unregisterNetworkFactory(Messenger messenger) {
4500 enforceConnectivityInternalPermission();
4501 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4502 }
4503
4504 private void handleUnregisterNetworkFactory(Messenger messenger) {
4505 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4506 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004507 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004508 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004509 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004510 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004511 }
4512
Robert Greenwalt7b816022014-04-18 15:25:25 -07004513 /**
4514 * NetworkAgentInfo supporting a request by requestId.
4515 * These have already been vetted (their Capabilities satisfy the request)
4516 * and the are the highest scored network available.
4517 * the are keyed off the Requests requestId.
4518 */
Hugo Benichicd952782017-09-20 11:20:14 +09004519 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4520 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004521 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4522 new SparseArray<NetworkAgentInfo>();
4523
Paul Jensen31a94f42015-02-13 14:18:39 -05004524 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4525 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004526 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4527 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004528 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4529 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4530 // there may not be a strict 1:1 correlation between the two.
4531 @GuardedBy("mNetworkForNetId")
4532 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004533
Robert Greenwalt7b816022014-04-18 15:25:25 -07004534 // NetworkAgentInfo keyed off its connecting messenger
4535 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004536 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004537 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4538 new HashMap<Messenger, NetworkAgentInfo>();
4539
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004540 @GuardedBy("mBlockedAppUids")
4541 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4542
Paul Jensen2c311d62014-11-17 12:34:51 -05004543 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004544 private final NetworkRequest mDefaultRequest;
4545
Erik Klineda4bfa82015-04-30 12:58:40 +09004546 // Request used to optionally keep mobile data active even when higher
4547 // priority networks like Wi-Fi are active.
4548 private final NetworkRequest mDefaultMobileDataRequest;
4549
Hugo Benichicd952782017-09-20 11:20:14 +09004550 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4551 synchronized (mNetworkForRequestId) {
4552 return mNetworkForRequestId.get(requestId);
4553 }
4554 }
4555
4556 private void clearNetworkForRequest(int requestId) {
4557 synchronized (mNetworkForRequestId) {
4558 mNetworkForRequestId.remove(requestId);
4559 }
4560 }
4561
4562 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4563 synchronized (mNetworkForRequestId) {
4564 mNetworkForRequestId.put(requestId, nai);
4565 }
4566 }
4567
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004568 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004569 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004570 }
4571
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004572 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004573 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004574 }
4575
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004576 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4577 return nri.request.requestId == mDefaultRequest.requestId;
4578 }
4579
Paul Jensen31a94f42015-02-13 14:18:39 -05004580 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004581 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004582 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004583 enforceConnectivityInternalPermission();
4584
Rubin Xu1bb5c082017-09-05 18:40:49 +01004585 LinkProperties lp = new LinkProperties(linkProperties);
4586 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004587 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4588 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004589 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004590 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004591 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004592 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004593 // Make sure the network capabilities reflect what the agent info says.
4594 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004595 synchronized (this) {
4596 nai.networkMonitor.systemReady = mSystemReady;
4597 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004598 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4599 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004600 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004601 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004602 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004603 }
4604
Erik Kline117e7f32018-03-04 21:01:01 +09004605 private void handleRegisterNetworkAgent(NetworkAgentInfo nai) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004606 if (VDBG) log("Got NetworkAgent Messenger");
Erik Kline117e7f32018-03-04 21:01:01 +09004607 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004608 synchronized (mNetworkForNetId) {
Erik Kline117e7f32018-03-04 21:01:01 +09004609 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004610 }
Erik Kline117e7f32018-03-04 21:01:01 +09004611 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
4612 NetworkInfo networkInfo = nai.networkInfo;
4613 nai.networkInfo = null;
4614 updateNetworkInfo(nai, networkInfo);
4615 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004616 }
4617
4618 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4619 LinkProperties newLp = networkAgent.linkProperties;
4620 int netId = networkAgent.network.netId;
4621
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004622 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4623 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004624 if (networkAgent.clatd != null) {
4625 networkAgent.clatd.fixupLinkProperties(oldLp);
4626 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004627
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004628 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004629 updateMtu(newLp, oldLp);
4630 // TODO - figure out what to do for clat
4631// for (LinkProperties lp : newLp.getStackedLinks()) {
4632// updateMtu(lp, null);
4633// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004634 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004635
Erik Kline94887872016-04-05 13:30:49 +09004636 updateRoutes(newLp, oldLp, netId);
4637 updateDnses(newLp, oldLp, netId);
dalyk1fcb7392018-03-05 12:42:22 -05004638 // Make sure LinkProperties represents the latest private DNS status.
4639 // This does not need to be done before updateDnses because the
4640 // LinkProperties are not the source of the private DNS configuration.
4641 // updateDnses will fetch the private DNS configuration from DnsManager.
4642 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004643
Hugo Benichi6f62b732017-06-27 15:13:20 +09004644 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004645 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004646 if (isDefaultNetwork(networkAgent)) {
4647 handleApplyDefaultProxy(newLp.getHttpProxy());
4648 } else {
4649 updateProxy(newLp, oldLp, networkAgent);
4650 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004651 // TODO - move this check to cover the whole function
4652 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004653 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004654 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4655 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004656
4657 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004658 }
4659
Joel Scherpelz668370b2017-06-08 15:35:21 +09004660 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004661 // Marks are only available on WiFi interaces. Checking for
4662 // marks on unsupported interfaces is harmless.
4663 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4664 return;
4665 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004666
Joel Scherpelz668370b2017-06-08 15:35:21 +09004667 int mark = mContext.getResources().getInteger(
4668 com.android.internal.R.integer.config_networkWakeupPacketMark);
4669 int mask = mContext.getResources().getInteger(
4670 com.android.internal.R.integer.config_networkWakeupPacketMask);
4671
4672 // Mask/mark of zero will not detect anything interesting.
4673 // Don't install rules unless both values are nonzero.
4674 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004675 return;
4676 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004677
4678 final String prefix = "iface:" + iface;
4679 try {
4680 if (add) {
4681 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4682 } else {
4683 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4684 }
4685 } catch (Exception e) {
4686 loge("Exception modifying wakeup packet monitoring: " + e);
4687 }
4688
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004689 }
4690
4691 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4692 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004693 CompareResult<String> interfaceDiff = new CompareResult<String>(
4694 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4695 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004696 for (String iface : interfaceDiff.added) {
4697 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004698 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004699 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004700 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004701 } catch (Exception e) {
4702 loge("Exception adding interface: " + e);
4703 }
4704 }
4705 for (String iface : interfaceDiff.removed) {
4706 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004707 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004708 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004709 mNetd.removeInterfaceFromNetwork(iface, netId);
4710 } catch (Exception e) {
4711 loge("Exception removing interface: " + e);
4712 }
4713 }
4714 }
4715
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004716 /**
4717 * Have netd update routes from oldLp to newLp.
4718 * @return true if routes changed between oldLp and newLp
4719 */
4720 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004721 // Compare the route diff to determine which routes should be added and removed.
4722 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4723 oldLp != null ? oldLp.getAllRoutes() : null,
4724 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004725
4726 // add routes before removing old in case it helps with continuous connectivity
4727
4728 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4729 for (RouteInfo route : routeDiff.added) {
4730 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004731 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004732 try {
4733 mNetd.addRoute(netId, route);
4734 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004735 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4736 loge("Exception in addRoute for non-gateway: " + e);
4737 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004738 }
4739 }
4740 for (RouteInfo route : routeDiff.added) {
4741 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004742 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004743 try {
4744 mNetd.addRoute(netId, route);
4745 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004746 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4747 loge("Exception in addRoute for gateway: " + e);
4748 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004749 }
4750 }
4751
4752 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004753 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004754 try {
4755 mNetd.removeRoute(netId, route);
4756 } catch (Exception e) {
4757 loge("Exception in removeRoute: " + e);
4758 }
4759 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004760 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004761 }
Erik Kline41368502015-06-17 13:19:54 +09004762
Erik Kline94887872016-04-05 13:30:49 +09004763 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4764 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4765 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004766 }
Erik Kline94887872016-04-05 13:30:49 +09004767
Erik Kline1742fe12017-12-13 19:40:49 +09004768 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4769 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4770
Erik Klinea24d4592018-01-11 21:07:29 +09004771 if (DBG) {
4772 final Collection<InetAddress> dnses = newLp.getDnsServers();
4773 log("Setting DNS servers for network " + netId + " to " + dnses);
4774 }
Erik Kline94887872016-04-05 13:30:49 +09004775 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004776 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004777 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004778 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004779 }
Erik Kline4edba012017-04-07 15:29:29 +09004780 }
4781
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004782 private String getNetworkPermission(NetworkCapabilities nc) {
4783 // TODO: make these permission strings AIDL constants instead.
4784 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4785 return NetworkManagementService.PERMISSION_SYSTEM;
4786 }
4787 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4788 return NetworkManagementService.PERMISSION_NETWORK;
4789 }
4790 return null;
4791 }
4792
Paul Jensen3d194ea2015-06-16 14:27:36 -04004793 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004794 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4795 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4796 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004797 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004798 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004799 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004800 if (nai.everConnected &&
4801 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4802 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004803 // does not cause any request (that is not a listen) currently matching that agent to
4804 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004805 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09004806 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004807 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09004808 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004809 }
4810
Paul Jensen3d194ea2015-06-16 14:27:36 -04004811 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004812 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004813 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004814 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004815 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004816 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004817 }
Paul Jensene0988542015-06-25 15:30:08 -04004818 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004819 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004820 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004821 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004822 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004823 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004824 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004825 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004826 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004827 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004828 if (nai.isSuspended()) {
4829 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4830 } else {
4831 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4832 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004833
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004834 return newNc;
4835 }
4836
4837 /**
4838 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4839 *
4840 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4841 * capabilities we manage and store in {@code nai}, such as validated status and captive
4842 * portal status)
4843 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4844 * potentially triggers rematches.
4845 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4846 * change.)
4847 *
4848 * @param oldScore score of the network before any of the changes that prompted us
4849 * to call this function.
4850 * @param nai the network having its capabilities updated.
4851 * @param nc the new network capabilities.
4852 */
4853 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4854 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4855
4856 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004857
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004858 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004859 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004860 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004861 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004862 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004863 } catch (RemoteException e) {
4864 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004865 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004866 }
4867
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004868 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004869 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004870 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004871 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004872 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004873
Chalard Jeanf213ca12018-01-16 18:43:05 +09004874 updateUids(nai, prevNc, newNc);
4875
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004876 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004877 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4878 // the change we're processing can't affect any requests, it can only affect the listens
4879 // on this network. We might have been called by rematchNetworkAndRequests when a
4880 // network changed foreground state.
4881 processListenRequests(nai, true);
4882 } else {
4883 // If the requestable capabilities have changed or the score changed, we can't have been
4884 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004885 rematchAllNetworksAndRequests(nai, oldScore);
4886 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004887 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004888
4889 // Report changes that are interesting for network statistics tracking.
4890 if (prevNc != null) {
4891 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004892 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004893 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004894 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004895 if (meteredChanged || roamingChanged) {
4896 notifyIfacesChangedForNetworkStats();
4897 }
4898 }
4899
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004900 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004901 // Tell VPNs about updated capabilities, since they may need to
4902 // bubble those changes through.
4903 synchronized (mVpns) {
4904 for (int i = 0; i < mVpns.size(); i++) {
4905 final Vpn vpn = mVpns.valueAt(i);
4906 vpn.updateCapabilities();
4907 }
4908 }
4909 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004910 }
4911
Chalard Jeanf213ca12018-01-16 18:43:05 +09004912 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4913 NetworkCapabilities newNc) {
4914 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4915 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4916 if (null == prevRanges) prevRanges = new ArraySet<>();
4917 if (null == newRanges) newRanges = new ArraySet<>();
4918 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4919
4920 prevRanges.removeAll(newRanges);
4921 newRanges.removeAll(prevRangesCopy);
4922
4923 try {
4924 if (!newRanges.isEmpty()) {
4925 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4926 newRanges.toArray(addedRangesArray);
4927 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4928 }
4929 if (!prevRanges.isEmpty()) {
4930 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4931 prevRanges.toArray(removedRangesArray);
4932 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4933 }
4934 } catch (Exception e) {
4935 // Never crash!
4936 loge("Exception in updateUids: " + e);
4937 }
4938 }
4939
Hugo Benichief502882017-09-01 01:23:32 +00004940 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Erik Kline79c6d052018-03-21 07:18:33 -07004941 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00004942 // Ignore updates for disconnected networks
4943 return;
4944 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004945 // newLp is already a defensive copy.
4946 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004947 if (VDBG) {
4948 log("Update of LinkProperties for " + nai.name() +
4949 "; created=" + nai.created +
4950 "; everConnected=" + nai.everConnected);
4951 }
4952 LinkProperties oldLp = nai.linkProperties;
4953 synchronized (nai) {
4954 nai.linkProperties = newLp;
4955 }
4956 if (nai.everConnected) {
4957 updateLinkProperties(nai, oldLp);
4958 }
4959 }
4960
Paul Jensenc8b9a742014-09-30 15:37:41 -04004961 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004962 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4963 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004964 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004965 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004966 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4967 }
4968 }
4969
Robert Greenwalt7b816022014-04-18 15:25:25 -07004970 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4971 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004972 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004973 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4974 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004975 }
4976 }
4977
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004978 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4979 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004980 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004981 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004982 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4983 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004984 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004985 sendIntent(nri.mPendingIntent, intent);
4986 }
4987 // else not handled
4988 }
4989
4990 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4991 mPendingIntentWakeLock.acquire();
4992 try {
4993 if (DBG) log("Sending " + pendingIntent);
4994 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4995 } catch (PendingIntent.CanceledException e) {
4996 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4997 mPendingIntentWakeLock.release();
4998 releasePendingNetworkRequest(pendingIntent);
4999 }
5000 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5001 }
5002
5003 @Override
5004 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5005 String resultData, Bundle resultExtras) {
5006 if (DBG) log("Finished sending " + pendingIntent);
5007 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005008 // Release with a delay so the receiving client has an opportunity to put in its
5009 // own request.
5010 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005011 }
5012
Chalard Jeanf19db372018-01-26 19:24:40 +09005013 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005014 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005015 if (nri.messenger == null) {
5016 return; // Default request has no msgr
5017 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005018 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005019 // TODO: check if defensive copies of data is needed.
5020 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005021 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005022 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5023 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005024 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005025 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005026 case ConnectivityManager.CALLBACK_AVAILABLE: {
5027 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
5028 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
5029 break;
5030 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005031 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005032 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005033 break;
5034 }
5035 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005036 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb552c462018-02-21 18:43:54 +09005037 final NetworkCapabilities nc = networkCapabilitiesWithoutUidsUnlessAllowed(
5038 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005039 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005040 break;
5041 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005042 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005043 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005044 break;
5045 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005046 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005047 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005048 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005049 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005050 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005051 String notification = ConnectivityManager.getCallbackName(notificationType);
5052 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005053 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005054 nri.messenger.send(msg);
5055 } catch (RemoteException e) {
5056 // may occur naturally in the race of binder death.
5057 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5058 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005059 }
5060
Hugo Benichidba33db2017-03-23 22:40:44 +09005061 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5062 bundle.putParcelable(t.getClass().getSimpleName(), t);
5063 }
5064
Paul Jensenc8b9a742014-09-30 15:37:41 -04005065 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005066 if (nai.numRequestNetworkRequests() != 0) {
5067 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5068 NetworkRequest nr = nai.requestAt(i);
5069 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005070 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005071 loge("Dead network still had at least " + nr);
5072 break;
5073 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005074 }
5075 nai.asyncChannel.disconnect();
5076 }
5077
Robert Greenwalt7b816022014-04-18 15:25:25 -07005078 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5079 if (oldNetwork == null) {
5080 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5081 return;
5082 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005083 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005084
5085 // If we get here it means that the last linger timeout for this network expired. So there
5086 // must be no other active linger timers, and we must stop lingering.
5087 oldNetwork.clearLingerState();
5088
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005089 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005090 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005091 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005092 } else {
5093 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005094 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5095 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005096 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005097 }
5098
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005099 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005100 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005101 setupDataActivityTracking(newNetwork);
5102 try {
5103 mNetd.setDefaultNetId(newNetwork.network.netId);
5104 } catch (Exception e) {
5105 loge("Exception setting default network :" + e);
5106 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005107
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005108 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005109 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005110 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005111 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005112 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005113 }
5114
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005115 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005116 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5117 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5118 NetworkRequest nr = nri.request;
5119 if (!nr.isListen()) continue;
5120 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5121 nai.removeRequest(nri.request.requestId);
5122 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5123 }
5124 }
5125
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005126 if (capabilitiesChanged) {
5127 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5128 }
5129
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005130 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5131 NetworkRequest nr = nri.request;
5132 if (!nr.isListen()) continue;
5133 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5134 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005135 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005136 }
5137 }
5138 }
5139
Paul Jensen2161a8e2014-09-11 11:00:39 -04005140 // Handles a network appearing or improving its score.
5141 //
5142 // - Evaluates all current NetworkRequests that can be
5143 // satisfied by newNetwork, and reassigns to newNetwork
5144 // any such requests for which newNetwork is the best.
5145 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005146 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005147 // needed. A network is needed if it is the best network for
5148 // one or more NetworkRequests, or if it is a VPN.
5149 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005150 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005151 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005152 //
5153 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5154 // networks that have no chance (i.e. even if validated)
5155 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005156 //
5157 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5158 // it does not remove NetworkRequests that other Networks could better satisfy.
5159 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5160 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5161 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005162 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005163 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005164 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5165 // performed to tear down unvalidated networks that have no chance (i.e. even if
5166 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005167 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005168 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005169 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005170 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005171 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005172 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005173
5174 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5175 final int score = newNetwork.getCurrentScore();
5176
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005177 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005178
Paul Jensen2161a8e2014-09-11 11:00:39 -04005179 // Find and migrate to this Network any NetworkRequests for
5180 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07005181 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04005182 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005183 NetworkCapabilities nc = newNetwork.networkCapabilities;
5184 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005185 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005186 // Process requests in the first pass and listens in the second pass. This allows us to
5187 // change a network's capabilities depending on which requests it has. This is only
5188 // correct if the change in capabilities doesn't affect whether the network satisfies
5189 // requests or not, and doesn't affect the network's score.
5190 if (nri.request.isListen()) continue;
5191
Hugo Benichicd952782017-09-20 11:20:14 +09005192 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005193 final boolean satisfies = newNetwork.satisfies(nri.request);
5194 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005195 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005196 log("Network " + newNetwork.name() + " was already satisfying" +
5197 " request " + nri.request.requestId + ". No change.");
5198 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005199 keep = true;
5200 continue;
5201 }
5202
5203 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005204 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005205 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005206 // next check if it's better than any current network we're using for
5207 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005208 if (VDBG) {
5209 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005210 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005211 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005212 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005213 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005214 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005215 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005216 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005217 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005218 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005219 affectedNetworks.add(currentNetwork);
5220 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005221 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005222 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005223 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005224 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005225 if (!newNetwork.addRequest(nri.request)) {
5226 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5227 }
5228 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005229 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005230 // Tell NetworkFactories about the new score, so they can stop
5231 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005232 // TODO - this could get expensive if we have alot of requests for this
5233 // network. Think about if there is a way to reduce this. Push
5234 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005235 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005236 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005237 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005238 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005239 if (currentNetwork != null) {
5240 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5241 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005242 }
5243 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005244 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005245 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5246 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005247 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005248 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5249 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5250 // This means this code doesn't have to handle the case where "currentNetwork" no
5251 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5252 if (DBG) {
5253 log("Network " + newNetwork.name() + " stopped satisfying" +
5254 " request " + nri.request.requestId);
5255 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005256 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005257 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005258 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005259 sendUpdatedScoreToFactories(nri.request, 0);
5260 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005261 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5262 newNetwork.name() +
5263 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005264 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005265 // TODO: Technically, sending CALLBACK_LOST here is
5266 // incorrect if there is a replacement network currently
5267 // connected that can satisfy nri, which is a request
5268 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005269 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5270 // so this code is only incorrect for a network that loses
5271 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005272 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005273 }
5274 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005275 if (isNewDefault) {
5276 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005277 makeDefault(newNetwork);
5278 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005279 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005280 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005281 // Have a new default network, release the transition wakelock in
5282 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005283 }
5284
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005285 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5286 Slog.wtf(TAG, String.format(
5287 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005288 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005289 }
5290 if (newNetwork.getCurrentScore() != score) {
5291 Slog.wtf(TAG, String.format(
5292 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005293 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005294 }
5295
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005296 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005297 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5298 // If the network went from background to foreground or vice versa, we need to update
5299 // its foreground state. It is safe to do this after rematching the requests because
5300 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5301 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005302 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005303 } else {
5304 processListenRequests(newNetwork, false);
5305 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005306
Paul Jensencf4c2c62015-07-01 14:16:32 -04005307 // do this after the default net is switched, but
5308 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005309 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005310
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005311 // Linger any networks that are no longer needed. This should be done after sending the
5312 // available callback for newNetwork.
5313 for (NetworkAgentInfo nai : affectedNetworks) {
5314 updateLingerState(nai, now);
5315 }
5316 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5317 // does not need to be done in any particular order.
5318 updateLingerState(newNetwork, now);
5319
Paul Jensencf4c2c62015-07-01 14:16:32 -04005320 if (isNewDefault) {
5321 // Maintain the illusion: since the legacy API only
5322 // understands one network at a time, we must pretend
5323 // that the current default network disconnected before
5324 // the new one connected.
5325 if (oldDefaultNetwork != null) {
5326 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5327 oldDefaultNetwork, true);
5328 }
5329 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5330 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5331 notifyLockdownVpn(newNetwork);
5332 }
5333
Robert Greenwalt7b816022014-04-18 15:25:25 -07005334 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005335 // Notify battery stats service about this network, both the normal
5336 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005337 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005338 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005339 final IBatteryStats bs = BatteryStatsService.getService();
5340 final int type = newNetwork.networkInfo.getType();
5341
5342 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5343 bs.noteNetworkInterfaceType(baseIface, type);
5344 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5345 final String stackedIface = stacked.getInterfaceName();
5346 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005347 }
5348 } catch (RemoteException ignored) {
5349 }
5350
Robert Greenwalt152ed372014-12-17 17:19:53 -08005351 // This has to happen after the notifyNetworkCallbacks as that tickles each
5352 // ConnectivityManager instance so that legacy requests correctly bind dns
5353 // requests to this network. The legacy users are listening for this bcast
5354 // and will generally do a dns request so they can ensureRouteToHost and if
5355 // they do that before the callbacks happen they'll use the default network.
5356 //
5357 // TODO: Is there still a race here? We send the broadcast
5358 // after sending the callback, but if the app can receive the
5359 // broadcast before the callback, it might still break.
5360 //
5361 // This *does* introduce a race where if the user uses the new api
5362 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5363 // they may get old info. Reverse this after the old startUsing api is removed.
5364 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005365 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5366 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005367 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005368 // legacy type tracker filters out repeat adds
5369 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5370 }
5371 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005372
5373 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5374 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5375 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5376 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5377 if (newNetwork.isVPN()) {
5378 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5379 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005380 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005381 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5382 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005383 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005384 if (nai.getLingerExpiry() > 0) {
5385 // This network has active linger timers and no requests, but is not
5386 // lingering. Linger it.
5387 //
5388 // One way (the only way?) this can happen if this network is unvalidated
5389 // and became unneeded due to another network improving its score to the
5390 // point where this network will no longer be able to satisfy any requests
5391 // even if it validates.
5392 updateLingerState(nai, now);
5393 } else {
5394 if (DBG) log("Reaping " + nai.name());
5395 teardownUnneededNetwork(nai);
5396 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005397 }
5398 }
5399 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005400 }
5401
Paul Jensen1c7ba022015-06-16 14:27:36 -04005402 /**
5403 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5404 * being disconnected.
5405 * @param changed If only one Network's score or capabilities have been modified since the last
5406 * time this function was called, pass this Network in this argument, otherwise pass
5407 * null.
5408 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5409 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5410 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5411 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5412 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005413 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005414 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005415 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5416 // to avoid the slowness. It is not simply enough to process just "changed", for
5417 // example in the case where "changed"'s score decreases and another network should begin
5418 // satifying a NetworkRequest that "changed" currently satisfies.
5419
5420 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5421 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5422 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005423 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005424 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005425 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005426 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005427 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5428 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5429 // Rematch higher scoring networks first to prevent requests first matching a lower
5430 // scoring network and then a higher scoring network, which could produce multiple
5431 // callbacks and inadvertently unlinger networks.
5432 Arrays.sort(nais);
5433 for (NetworkAgentInfo nai : nais) {
5434 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005435 // Only reap the last time through the loop. Reaping before all rematching
5436 // is complete could incorrectly teardown a network that hasn't yet been
5437 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005438 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005439 : ReapUnvalidatedNetworks.REAP,
5440 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005441 }
5442 }
5443 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005444
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005445 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005446 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005447 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005448 // For now only update icons for default connection.
5449 // TODO: Update WiFi and cellular icons separately. b/17237507
5450 if (!isDefaultNetwork(nai)) return;
5451
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005452 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005453 // Don't repeat publish.
5454 if (newInetCondition == mDefaultInetConditionPublished) return;
5455
5456 mDefaultInetConditionPublished = newInetCondition;
5457 sendInetConditionBroadcast(nai.networkInfo);
5458 }
5459
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005460 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005461 synchronized (mVpns) {
5462 if (mLockdownTracker != null) {
5463 if (nai != null && nai.isVPN()) {
5464 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5465 } else {
5466 mLockdownTracker.onNetworkInfoChanged();
5467 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005468 }
5469 }
5470 }
5471
Robert Greenwalt7b816022014-04-18 15:25:25 -07005472 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005473 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005474 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005475 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005476 synchronized (networkAgent) {
5477 oldInfo = networkAgent.networkInfo;
5478 networkAgent.networkInfo = newInfo;
5479 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005480 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005481
Robert Greenwalt7b816022014-04-18 15:25:25 -07005482 if (DBG) {
5483 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5484 (oldInfo == null ? "null" : oldInfo.getState()) +
5485 " to " + state);
5486 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005487
Robin Lee585e2482016-05-01 23:00:00 +01005488 if (!networkAgent.created
5489 && (state == NetworkInfo.State.CONNECTED
5490 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005491
5492 // A network that has just connected has zero requests and is thus a foreground network.
5493 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5494
Robert Greenwalt7b816022014-04-18 15:25:25 -07005495 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005496 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005497 if (networkAgent.isVPN()) {
5498 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005499 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5500 (networkAgent.networkMisc == null ||
5501 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005502 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005503 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005504 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005505 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005506 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005507 loge("Error creating network " + networkAgent.network.netId + ": "
5508 + e.getMessage());
5509 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005510 }
Paul Jenseneec75412014-08-04 12:21:19 -04005511 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005512 }
5513
5514 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5515 networkAgent.everConnected = true;
5516
Erik Kline79c6d052018-03-21 07:18:33 -07005517 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005518 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005519 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005520
Paul Jensenca8f16a2014-05-09 12:47:55 -04005521 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005522 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005523
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005524 if (networkAgent.isVPN()) {
5525 // Temporarily disable the default proxy (not global).
5526 synchronized (mProxyLock) {
5527 if (!mDefaultProxyDisabled) {
5528 mDefaultProxyDisabled = true;
5529 if (mGlobalProxy == null && mDefaultProxy != null) {
5530 sendProxyBroadcast(null);
5531 }
5532 }
5533 }
5534 // TODO: support proxy per network.
5535 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005536
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005537 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5538 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5539 // capabilities, so it only needs to be done once on initial connect, not every time the
5540 // network's capabilities change. Note that we do this before rematching the network,
5541 // so we could decide to tear it down immediately afterwards. That's fine though - on
5542 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5543 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005544 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005545
Paul Jensen2161a8e2014-09-11 11:00:39 -04005546 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005547 final long now = SystemClock.elapsedRealtime();
5548 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005549
5550 // This has to happen after matching the requests, because callbacks are just requests.
5551 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005552 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005553 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005554 if (networkAgent.isVPN()) {
5555 synchronized (mProxyLock) {
5556 if (mDefaultProxyDisabled) {
5557 mDefaultProxyDisabled = false;
5558 if (mGlobalProxy == null && mDefaultProxy != null) {
5559 sendProxyBroadcast(mDefaultProxy);
5560 }
5561 }
5562 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005563 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005564 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005565 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5566 state == NetworkInfo.State.SUSPENDED) {
5567 // going into or coming out of SUSPEND: rescore and notify
5568 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005569 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005570 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005571 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5572 networkAgent.networkCapabilities);
5573 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5574 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005575 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5576 ConnectivityManager.CALLBACK_SUSPENDED :
5577 ConnectivityManager.CALLBACK_RESUMED));
5578 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005579 }
5580 }
5581
Robert Greenwaltac96c522014-06-03 16:43:57 -07005582 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005583 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005584 if (score < 0) {
5585 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5586 "). Bumping score to min of 0");
5587 score = 0;
5588 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005589
Paul Jensen2161a8e2014-09-11 11:00:39 -04005590 final int oldScore = nai.getCurrentScore();
5591 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005592
Paul Jensen85cf78e2015-06-25 13:25:07 -04005593 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005594
Paul Jensenc8b9a742014-09-30 15:37:41 -04005595 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005596 }
5597
Erik Klinec75d4fa2017-02-15 19:59:17 +09005598 // Notify only this one new request of the current state. Transfer all the
5599 // current state by calling NetworkCapabilities and LinkProperties callbacks
5600 // so that callers can be guaranteed to have as close to atomicity in state
5601 // transfer as can be supported by this current API.
5602 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005603 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005604 if (nri.mPendingIntent != null) {
5605 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5606 // Attempt no subsequent state pushes where intents are involved.
5607 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005608 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005609
5610 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005611 }
5612
Robert Greenwalt8d482522015-06-24 13:23:42 -07005613 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005614 // The NetworkInfo we actually send out has no bearing on the real
5615 // state of affairs. For example, if the default connection is mobile,
5616 // and a request for HIPRI has just gone away, we need to pretend that
5617 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5618 // the state to DISCONNECTED, even though the network is of type MOBILE
5619 // and is still connected.
5620 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5621 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005622 if (state != DetailedState.DISCONNECTED) {
5623 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005624 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005625 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005626 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005627 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5628 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5629 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5630 if (info.isFailover()) {
5631 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5632 nai.networkInfo.setFailover(false);
5633 }
5634 if (info.getReason() != null) {
5635 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5636 }
5637 if (info.getExtraInfo() != null) {
5638 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5639 }
5640 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005641 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005642 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005643 if (newDefaultAgent != null) {
5644 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5645 newDefaultAgent.networkInfo);
5646 } else {
5647 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5648 }
5649 }
5650 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5651 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005652 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005653 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005654 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005655 }
5656 }
5657 }
5658
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005659 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005660 if (VDBG) {
5661 String notification = ConnectivityManager.getCallbackName(notifyType);
5662 log("notifyType " + notification + " for " + networkAgent.name());
5663 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005664 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5665 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005666 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5667 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005668 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5669 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005670 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005671 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005672 } else {
5673 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5674 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005675 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005676 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005677
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005678 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5679 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5680 }
5681
Jeff Sharkey69736342014-12-08 14:50:12 -08005682 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005683 * Returns the list of all interfaces that could be used by network traffic that does not
5684 * explicitly specify a network. This includes the default network, but also all VPNs that are
5685 * currently connected.
5686 *
5687 * Must be called on the handler thread.
5688 */
5689 private Network[] getDefaultNetworks() {
5690 ArrayList<Network> defaultNetworks = new ArrayList<>();
5691 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5692 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5693 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5694 defaultNetworks.add(nai.network);
5695 }
5696 }
5697 return defaultNetworks.toArray(new Network[0]);
5698 }
5699
5700 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005701 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5702 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005703 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005704 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005705 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005706 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005707 } catch (Exception ignored) {
5708 }
5709 }
5710
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005711 @Override
5712 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005713 int user = UserHandle.getUserId(Binder.getCallingUid());
5714 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005715 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005716 return mVpns.get(user).addAddress(address, prefixLength);
5717 }
5718 }
5719
5720 @Override
5721 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005722 int user = UserHandle.getUserId(Binder.getCallingUid());
5723 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005724 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005725 return mVpns.get(user).removeAddress(address, prefixLength);
5726 }
5727 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005728
5729 @Override
5730 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005731 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005732 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005733 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005734 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005735 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005736 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005737 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005738 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005739 }
5740 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005741 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005742
5743 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005744 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07005745 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005746 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005747 }
5748
5749 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005750 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5751 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5752 enforceKeepalivePermission();
5753 mKeepaliveTracker.startNattKeepalive(
5754 getNetworkAgentInfoForNetwork(network),
5755 intervalSeconds, messenger, binder,
5756 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5757 }
5758
5759 @Override
5760 public void stopKeepalive(Network network, int slot) {
5761 mHandler.sendMessage(mHandler.obtainMessage(
5762 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5763 }
5764
5765 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005766 public void factoryReset() {
5767 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005768
5769 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5770 return;
5771 }
5772
Robin Lee3b3dd942015-05-12 18:14:58 +01005773 final int userId = UserHandle.getCallingUserId();
5774
Stuart Scottf1fb3972015-04-02 18:00:02 -07005775 // Turn airplane mode off
5776 setAirplaneMode(false);
5777
Stuart Scotte3e314d2015-04-20 14:07:45 -07005778 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5779 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005780 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005781 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005782 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005783 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005784 }
5785
Stuart Scotte3e314d2015-04-20 14:07:45 -07005786 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005787 // Remove always-on package
5788 synchronized (mVpns) {
5789 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5790 if (alwaysOnPackage != null) {
5791 setAlwaysOnVpnPackage(userId, null, false);
5792 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5793 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005794
Hugo Benichi69744342017-11-27 10:57:16 +09005795 // Turn Always-on VPN off
5796 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5797 final long ident = Binder.clearCallingIdentity();
5798 try {
5799 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5800 mLockdownEnabled = false;
5801 setLockdownTracker(null);
5802 } finally {
5803 Binder.restoreCallingIdentity(ident);
5804 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005805 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005806
Hugo Benichi69744342017-11-27 10:57:16 +09005807 // Turn VPN off
5808 VpnConfig vpnConfig = getVpnConfig(userId);
5809 if (vpnConfig != null) {
5810 if (vpnConfig.legacy) {
5811 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5812 } else {
5813 // Prevent this app (packagename = vpnConfig.user) from initiating
5814 // VPN connections in the future without user intervention.
5815 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005816
Hugo Benichi69744342017-11-27 10:57:16 +09005817 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5818 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005819 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005820 }
5821 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005822
5823 Settings.Global.putString(mContext.getContentResolver(),
5824 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005825 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005826
Ricky Wai44dcbde2018-01-23 04:09:45 +00005827 @Override
5828 public byte[] getNetworkWatchlistConfigHash() {
5829 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
5830 if (nwm == null) {
5831 loge("Unable to get NetworkWatchlistManager");
5832 return null;
5833 }
5834 // Redirect it to network watchlist service to access watchlist file and calculate hash.
5835 return nwm.getWatchlistConfigHash();
5836 }
5837
Paul Jensencf4c2c62015-07-01 14:16:32 -04005838 @VisibleForTesting
5839 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5840 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5841 return new NetworkMonitor(context, handler, nai, defaultRequest);
5842 }
Erik Kline48f12f22016-04-14 17:30:59 +09005843
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005844 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005845 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5846 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005847 }
5848
5849 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005850 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5851 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5852 }
5853
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005854 @VisibleForTesting
5855 public boolean hasService(String name) {
5856 return ServiceManager.checkService(name) != null;
5857 }
5858
Hugo Benichi64901e52017-10-19 14:42:40 +09005859 @VisibleForTesting
5860 protected IpConnectivityMetrics.Logger metricsLogger() {
5861 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5862 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005863 }
5864
5865 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005866 int[] transports = nai.networkCapabilities.getTransportTypes();
5867 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005868 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005869
5870 private static boolean toBool(int encodedBoolean) {
5871 return encodedBoolean != 0; // Only 0 means false.
5872 }
5873
5874 private static int encodeBool(boolean b) {
5875 return b ? 1 : 0;
5876 }
mswest46386886f2018-03-12 10:34:34 -07005877
5878 @Override
5879 public void onShellCommand(FileDescriptor in, FileDescriptor out,
5880 FileDescriptor err, String[] args, ShellCallback callback,
5881 ResultReceiver resultReceiver) {
5882 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
5883 }
5884
5885 private class ShellCmd extends ShellCommand {
5886
5887 @Override
5888 public int onCommand(String cmd) {
5889 if (cmd == null) {
5890 return handleDefaultCommands(cmd);
5891 }
5892 final PrintWriter pw = getOutPrintWriter();
5893 try {
5894 switch (cmd) {
5895 case "airplane-mode":
5896 final String action = getNextArg();
5897 if ("enable".equals(action)) {
5898 setAirplaneMode(true);
5899 return 0;
5900 } else if ("disable".equals(action)) {
5901 setAirplaneMode(false);
5902 return 0;
5903 } else if (action == null) {
5904 final ContentResolver cr = mContext.getContentResolver();
5905 final int enabled = Settings.Global.getInt(cr,
5906 Settings.Global.AIRPLANE_MODE_ON);
5907 pw.println(enabled == 0 ? "disabled" : "enabled");
5908 return 0;
5909 } else {
5910 onHelp();
5911 return -1;
5912 }
5913 default:
5914 return handleDefaultCommands(cmd);
5915 }
5916 } catch (Exception e) {
5917 pw.println(e);
5918 }
5919 return -1;
5920 }
5921
5922 @Override
5923 public void onHelp() {
5924 PrintWriter pw = getOutPrintWriter();
5925 pw.println("Connectivity service commands:");
5926 pw.println(" help");
5927 pw.println(" Print this help text.");
5928 pw.println(" airplane-mode [enable|disable]");
5929 pw.println(" Turn airplane mode on or off.");
5930 pw.println(" airplane-mode");
5931 pw.println(" Get airplane mode.");
5932 }
5933 }
Erik Kline79c6d052018-03-21 07:18:33 -07005934}