blob: f729cb84f6a69f01ec2923fa812d10714cc82ed8 [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;
Erik Kline3f8306b2018-05-01 16:51:44 +0900135import com.android.internal.util.ArrayUtils;
Robert Greenwalte049c232014-04-11 15:53:27 -0700136import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600137import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700138import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900139import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900140import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700141import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700142import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400143import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900144import com.android.server.connectivity.DnsManager;
Erik Klinea24d4592018-01-11 21:07:29 +0900145import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
dalyk1fcb7392018-03-05 12:42:22 -0500146import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900147import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900148import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100149import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700150import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900151import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700152import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600153import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400154import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900155import com.android.server.connectivity.NetworkNotificationManager;
156import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400157import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700158import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800159import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700160import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100161import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk1fcb7392018-03-05 12:42:22 -0500162import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700163import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700164import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900165import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700166import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600167
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700168import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700169
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700170import org.xmlpull.v1.XmlPullParser;
171import org.xmlpull.v1.XmlPullParserException;
172
173import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700175import java.io.FileNotFoundException;
176import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700177import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700179import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700180import java.net.InetAddress;
181import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700182import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700183import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700184import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700185import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700186import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700187import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700188import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700189import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700190import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900191import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600192import java.util.SortedSet;
193import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194
195/**
196 * @hide
197 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800198public class ConnectivityService extends IConnectivityManager.Stub
199 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900200 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Erik Kline7747fd42017-05-12 16:52:48 +0900202 public static final String DIAG_ARG = "--diag";
203 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900204 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900205
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900206 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700207 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
Jake Hamby786e71a2014-02-06 14:43:50 -0800209 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900210 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700211
Jeff Sharkey899223b2012-08-04 15:24:58 -0700212 // TODO: create better separation between radio types and network types
213
Robert Greenwalt42acef32009-08-12 16:08:25 -0700214 // how long to wait before switching back to a radio's default network
215 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
216 // system property that can override the above value
217 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
218 "android.telephony.apn-restore";
219
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900220 // How long to wait before putting up a "This network doesn't have an Internet connection,
221 // connect anyway?" dialog after the user selects a network that doesn't validate.
222 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
223
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900224 // Default to 30s linger time-out. Modifiable only for testing.
225 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
226 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
227 @VisibleForTesting
228 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
229
Jeremy Joslin79294842014-12-03 17:15:28 -0800230 // How long to delay to removal of a pending intent based request.
231 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
232 private final int mReleasePendingIntentDelayMs;
233
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900234 private MockableSystemProperties mSystemProperties;
235
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800236 private Tethering mTethering;
237
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700238 private final PermissionMonitor mPermissionMonitor;
239
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700240 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700241
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900242 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700243 @GuardedBy("mVpns")
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900244 protected final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700245
Hugo Benichi69744342017-11-27 10:57:16 +0900246 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
247 // a direct call to LockdownVpnTracker.isEnabled().
248 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700249 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900250 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700251 private LockdownVpnTracker mLockdownTracker;
252
Erik Klineda4bfa82015-04-30 12:58:40 +0900253 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700255 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700256 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700259 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700261 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800262 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700263 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900264 private NetworkPolicyManagerInternal mPolicyManagerInternal;
dalyk1fcb7392018-03-05 12:42:22 -0500265 private IIpConnectivityMetrics mIpConnectivityMetrics;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700266
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700267 private String mCurrentTcpBufferSizes;
268
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700269 private static final int ENABLED = 1;
270 private static final int DISABLED = 0;
271
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900272 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900273 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
274 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900275
Paul Jensenb10e37f2014-11-25 12:33:08 -0500276 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400277 // Tear down networks that have no chance (e.g. even if validated) of becoming
278 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500279 // all networks have been rematched against all NetworkRequests.
280 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400281 // Don't reap networks. This should be passed when some networks have not yet been
282 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500283 DONT_REAP
284 };
285
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900286 private enum UnneededFor {
287 LINGER, // Determine whether this network is unneeded and should be lingered.
288 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
289 }
290
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700291 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700292 * used internally to change our mobile data enabled flag
293 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700294 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700295
296 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700297 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700298 * from one net to another. Clear happens when we get a new
299 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
300 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700301 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700302 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700303
Robert Greenwalt434203a2010-10-11 16:00:27 -0700304 /**
305 * used internally to reload global proxy settings
306 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700307 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700308
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700309 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400310 * PAC manager has received new port.
311 */
312 private static final int EVENT_PROXY_HAS_CHANGED = 16;
313
Robert Greenwalte049c232014-04-11 15:53:27 -0700314 /**
315 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700316 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700317 */
318 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
319
Robert Greenwalt7b816022014-04-18 15:25:25 -0700320 /**
321 * used internally when registering NetworkAgents
322 * obj = Messenger
323 */
324 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
325
Robert Greenwalt9258c642014-03-26 16:47:06 -0700326 /**
327 * used to add a network request
328 * includes a NetworkRequestInfo
329 */
330 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
331
332 /**
333 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900334 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700335 * cancel it.
336 * includes a NetworkRequestInfo
337 */
338 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
339
340 /**
341 * used to add a network listener - no request
342 * includes a NetworkRequestInfo
343 */
344 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
345
346 /**
347 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400348 * arg1 = UID of caller
349 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700350 */
351 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
352
Robert Greenwalta67be032014-05-16 15:49:14 -0700353 /**
354 * used internally when registering NetworkFactories
355 * obj = Messenger
356 */
357 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
358
Robert Greenwalt27711812014-06-25 16:45:57 -0700359 /**
360 * used internally to expire a wakelock when transitioning
361 * from one net to another. Expire happens when we fail to find
362 * a new network (typically after 1 minute) -
363 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
364 * a replacement network.
365 */
366 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
367
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700368 /**
369 * Used internally to indicate the system is ready.
370 */
371 private static final int EVENT_SYSTEM_READY = 25;
372
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800373 /**
374 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400375 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800376 */
377 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
378
379 /**
380 * used to remove a pending intent and its associated network request.
381 * arg1 = UID of caller
382 * obj = PendingIntent
383 */
384 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
385
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900386 /**
387 * used to specify whether a network should be used even if unvalidated.
388 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
389 * arg2 = whether to remember this choice in the future (1 or 0)
390 * obj = network
391 */
392 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
393
394 /**
395 * used to ask the user to confirm a connection to an unvalidated network.
396 * obj = network
397 */
398 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700399
Erik Klineda4bfa82015-04-30 12:58:40 +0900400 /**
401 * used internally to (re)configure mobile data always-on settings.
402 */
403 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
404
Paul Jensen694f2b82015-06-17 14:15:39 -0400405 /**
406 * used to add a network listener with a pending intent
407 * obj = NetworkRequestInfo
408 */
409 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
410
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900411 /**
412 * used to specify whether a network should not be penalized when it becomes unvalidated.
413 */
414 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
415
416 /**
417 * used to trigger revalidation of a network.
418 */
419 private static final int EVENT_REVALIDATE_NETWORK = 36;
420
Erik Klinea24d4592018-01-11 21:07:29 +0900421 // Handle changes in Private DNS settings.
422 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
423
dalyk1fcb7392018-03-05 12:42:22 -0500424 // Handle private DNS validation status updates.
425 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
426
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900427 private static String eventName(int what) {
428 return sMagicDecoderRing.get(what, Integer.toString(what));
429 }
430
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900431 /** Handler thread used for both of the handlers below. */
432 @VisibleForTesting
433 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700434 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700435 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700436 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700437 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900438 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700439
Mike Lockwood0f79b542009-08-14 14:18:49 -0400440 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800441 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400442
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700443 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700444 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800445 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700446
Robert Greenwalt434203a2010-10-11 16:00:27 -0700447 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400448 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700449 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700450 private boolean mDefaultProxyDisabled = false;
451
Robert Greenwalt434203a2010-10-11 16:00:27 -0700452 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400453 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700454
Jason Monk602b2322013-07-03 17:04:33 -0400455 private PacManager mPacManager = null;
456
Erik Klineda4bfa82015-04-30 12:58:40 +0900457 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700458
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400459 private UserManager mUserManager;
460
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700461 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700462 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700463
Robert Greenwalt50393202011-06-21 17:26:14 -0700464 // the set of network types that can only be enabled by system/sig apps
465 List mProtectedNetworks;
466
John Spurlockbf991a82013-06-24 14:20:23 -0400467 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700468
Wink Savilleab9321d2013-06-29 21:10:57 -0700469 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400470
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900471 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900472 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900473 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900474
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700475 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800476 private static final int MIN_NET_ID = 100; // some reserved marks
477 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700478 private int mNextNetId = MIN_NET_ID;
479
Robert Greenwalt34524f02014-05-18 16:22:10 -0700480 // sequence number of NetworkRequests
481 private int mNextNetworkRequestId = 1;
482
Erik Kline7523eb32015-07-09 18:24:03 +0900483 // NetworkRequest activity String log entries.
484 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
485 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
486
Hugo Benichic2ae2872016-07-11 11:05:12 +0900487 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900488 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900489 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
490
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900491 private static final int MAX_WAKELOCK_LOGS = 20;
492 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900493 private int mTotalWakelockAcquisitions = 0;
494 private int mTotalWakelockReleases = 0;
495 private long mTotalWakelockDurationMs = 0;
496 private long mMaxWakelockDurationMs = 0;
497 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900498
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700499 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
500 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400501 private static class ValidationLog {
502 final Network mNetwork;
Chalard Jeand771aa02018-04-26 16:16:10 +0900503 final String mName;
Paul Jensen0808eb82016-06-03 13:51:21 -0400504 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700505
Chalard Jeand771aa02018-04-26 16:16:10 +0900506 ValidationLog(Network network, String name, ReadOnlyLocalLog log) {
Paul Jensen0808eb82016-06-03 13:51:21 -0400507 mNetwork = network;
Chalard Jeand771aa02018-04-26 16:16:10 +0900508 mName = name;
Paul Jensen0808eb82016-06-03 13:51:21 -0400509 mLog = log;
510 }
511 }
512 private final ArrayDeque<ValidationLog> mValidationLogs =
513 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
514
Chalard Jeand771aa02018-04-26 16:16:10 +0900515 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String name) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900516 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700517 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
518 mValidationLogs.removeLast();
519 }
Chalard Jeand771aa02018-04-26 16:16:10 +0900520 mValidationLogs.addFirst(new ValidationLog(network, name, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700521 }
522 }
523
Hugo Benichif9fdf872016-07-28 17:53:06 +0900524 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900525
Erik Kline065ab6e2016-10-02 18:02:14 +0900526 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900527 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900528
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900529 @VisibleForTesting
530 final MultipathPolicyTracker mMultipathPolicyTracker;
531
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700532 /**
533 * Implements support for the legacy "one network per network type" model.
534 *
535 * We used to have a static array of NetworkStateTrackers, one for each
536 * network type, but that doesn't work any more now that we can have,
537 * for example, more that one wifi network. This class stores all the
538 * NetworkAgentInfo objects that support a given type, but the legacy
539 * API will only see the first one.
540 *
541 * It serves two main purposes:
542 *
543 * 1. Provide information about "the network for a given type" (since this
544 * API only supports one).
545 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
546 * the first network for a given type changes, or if the default network
547 * changes.
548 */
549 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900550
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900551 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900552 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900553
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700554 /**
555 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
556 * Each list holds references to all NetworkAgentInfos that are used to
557 * satisfy requests for that network type.
558 *
559 * This array is built out at startup such that an unsupported network
560 * doesn't get an ArrayList instance, making this a tristate:
561 * unsupported, supported but not active and active.
562 *
563 * The actual lists are populated when we scan the network types that
564 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900565 *
566 * Threading model:
567 * - addSupportedType() is only called in the constructor
568 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
569 * They are therefore not thread-safe with respect to each other.
570 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
571 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
572 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700573 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900574 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700575
576 public LegacyTypeTracker() {
577 mTypeLists = (ArrayList<NetworkAgentInfo>[])
578 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
579 }
580
581 public void addSupportedType(int type) {
582 if (mTypeLists[type] != null) {
583 throw new IllegalStateException(
584 "legacy list for type " + type + "already initialized");
585 }
586 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
587 }
588
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700589 public boolean isTypeSupported(int type) {
590 return isNetworkTypeValid(type) && mTypeLists[type] != null;
591 }
592
593 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900594 synchronized (mTypeLists) {
595 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
596 return mTypeLists[type].get(0);
597 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700598 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900599 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700600 }
601
Robert Greenwalt8d482522015-06-24 13:23:42 -0700602 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900603 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900604 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700605 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900606 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900607 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900608 }
609 }
610
611 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700612 public void add(int type, NetworkAgentInfo nai) {
613 if (!isTypeSupported(type)) {
614 return; // Invalid network type.
615 }
616 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
617
618 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
619 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700620 return;
621 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900622 synchronized (mTypeLists) {
623 list.add(nai);
624 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900625
626 // 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 +0900627 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900628 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700629 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
630 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700631 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700632 }
633
Lorenzo Colittia793a672014-07-31 23:20:17 +0900634 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900635 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900636 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
637 if (list == null || list.isEmpty()) {
638 return;
639 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900640 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900641
Hugo Benichi78caa2582016-06-21 09:48:07 +0900642 synchronized (mTypeLists) {
643 if (!list.remove(nai)) {
644 return;
645 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900646 }
647
Robert Greenwalt8d482522015-06-24 13:23:42 -0700648 final DetailedState state = DetailedState.DISCONNECTED;
649
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900650 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700651 maybeLogBroadcast(nai, state, type, wasDefault);
652 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900653 }
654
655 if (!list.isEmpty() && wasFirstNetwork) {
656 if (DBG) log("Other network available for type " + type +
657 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900658 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700659 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
660 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900661 }
662 }
663
664 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900665 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
666 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700667 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900668 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700669 }
670 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700671
Robert Greenwalt8d482522015-06-24 13:23:42 -0700672 // send out another legacy broadcast - currently only used for suspend/unsuspend
673 // toggle
674 public void update(NetworkAgentInfo nai) {
675 final boolean isDefault = isDefaultNetwork(nai);
676 final DetailedState state = nai.networkInfo.getDetailedState();
677 for (int type = 0; type < mTypeLists.length; type++) {
678 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700679 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900680 final boolean isFirst = contains && (nai == list.get(0));
681 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700682 maybeLogBroadcast(nai, state, type, isDefault);
683 sendLegacyNetworkBroadcast(nai, state, type);
684 }
685 }
686 }
687
Lorenzo Colittia793a672014-07-31 23:20:17 +0900688 private String naiToString(NetworkAgentInfo nai) {
689 String name = (nai != null) ? nai.name() : "null";
690 String state = (nai.networkInfo != null) ?
691 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
692 "???/???";
693 return name + " " + state;
694 }
695
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700696 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900697 pw.println("mLegacyTypeTracker:");
698 pw.increaseIndent();
699 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700700 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900701 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700702 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900703 pw.println();
704 pw.println("Current state:");
705 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900706 synchronized (mTypeLists) {
707 for (int type = 0; type < mTypeLists.length; type++) {
708 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
709 for (NetworkAgentInfo nai : mTypeLists[type]) {
710 pw.println(type + " " + naiToString(nai));
711 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900712 }
713 }
714 pw.decreaseIndent();
715 pw.decreaseIndent();
716 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700717 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700718 }
719 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
720
Vishnu Nair5c010902017-10-26 10:08:50 -0700721 /**
722 * Helper class which parses out priority arguments and dumps sections according to their
723 * priority. If priority arguments are omitted, function calls the legacy dump command.
724 */
725 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
726 @Override
727 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
728 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
729 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
730 }
731
732 @Override
733 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
734 doDump(fd, pw, args, asProto);
735 }
736
737 @Override
738 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
739 doDump(fd, pw, args, asProto);
740 }
741 };
742
Jeff Sharkey899223b2012-08-04 15:24:58 -0700743 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700744 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900745 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
746 }
747
748 @VisibleForTesting
749 protected ConnectivityService(Context context, INetworkManagementService netManager,
750 INetworkStatsService statsService, INetworkPolicyManager policyManager,
751 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800752 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800753
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900754 mSystemProperties = getSystemProperties();
755
Hugo Benichif9fdf872016-07-28 17:53:06 +0900756 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900757 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900758 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900759 mNetworkRequests.put(mDefaultRequest, defaultNRI);
760 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900761
Chalard Jeandda156a2018-01-10 21:19:32 +0900762 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900763 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700764
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900765 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900766 mHandlerThread.start();
767 mHandler = new InternalHandler(mHandlerThread.getLooper());
768 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700769
Jeremy Joslin79294842014-12-03 17:15:28 -0800770 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
771 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
772
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900773 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900774
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700775 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700776 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800777 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700778 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900779 mPolicyManagerInternal = checkNotNull(
780 LocalServices.getService(NetworkPolicyManagerInternal.class),
781 "missing NetworkPolicyManagerInternal");
782
Jeff Sharkey82f85212012-08-24 11:17:25 -0700783 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700784 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700785
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700786 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900787 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700788 } catch (RemoteException e) {
789 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700790 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700791 }
792
793 final PowerManager powerManager = (PowerManager) context.getSystemService(
794 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700795 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
796 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
797 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800798 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700799
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700800 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700801
Wink Saville51f456f2013-04-23 14:26:51 -0700802 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900803 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700804 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700805 String[] naStrings = context.getResources().getStringArray(
806 com.android.internal.R.array.networkAttributes);
807 for (String naString : naStrings) {
808 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700809 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700810 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700811 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800812 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700813 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700814 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700815 }
Wink Saville51f456f2013-04-23 14:26:51 -0700816 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
817 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
818 n.type);
819 continue;
820 }
Wink Saville975c8482011-04-07 14:23:45 -0700821 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800822 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700823 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700824 continue;
825 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700826 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700827
Wink Saville975c8482011-04-07 14:23:45 -0700828 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700829 mNetworksDefined++;
830 } catch(Exception e) {
831 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700832 }
833 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700834
835 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
836 if (mNetConfigs[TYPE_VPN] == null) {
837 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
838 // don't need to add TYPE_VPN to mNetConfigs.
839 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
840 mNetworksDefined++; // used only in the log() statement below.
841 }
842
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900843 // Do the same for Ethernet, since it's often not specified in the configs, although many
844 // devices can use it via USB host adapters.
845 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
846 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
847 mNetworksDefined++;
848 }
849
Wink Saville5e56bc52013-07-29 15:00:57 -0700850 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700851
Robert Greenwalt50393202011-06-21 17:26:14 -0700852 mProtectedNetworks = new ArrayList<Integer>();
853 int[] protectedNetworks = context.getResources().getIntArray(
854 com.android.internal.R.array.config_protectedNetworks);
855 for (int p : protectedNetworks) {
856 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
857 mProtectedNetworks.add(p);
858 } else {
859 if (DBG) loge("Ignoring protectedNetwork " + p);
860 }
861 }
862
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900863 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
864 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700865
Erik Kline47222fc2017-04-30 19:36:15 +0900866 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800867
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700868 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
869
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700870 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700871 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100872 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700873 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700874 intentFilter.addAction(Intent.ACTION_USER_ADDED);
875 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000876 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700877 mContext.registerReceiverAsUser(
878 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000879 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
880 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900881
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700882 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700883 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700884 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700885 } catch (RemoteException e) {
886 loge("Error registering observer :" + e);
887 }
888
Erik Klineda4bfa82015-04-30 12:58:40 +0900889 mSettingsObserver = new SettingsObserver(mContext, mHandler);
890 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800891
John Spurlockbf991a82013-06-24 14:20:23 -0400892 mDataConnectionStats = new DataConnectionStats(mContext);
893 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400894
Jason Monkdecd2952013-10-10 14:02:51 -0400895 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700896
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400897 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900898
899 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900900 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
901 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900902
903 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
904 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
905 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
906 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
907 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
908 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
909 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900910
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900911 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900912 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900913 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900914
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900915 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
916
Erik Kline1742fe12017-12-13 19:40:49 +0900917 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900918 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700920
Erik Kline47222fc2017-04-30 19:36:15 +0900921 private Tethering makeTethering() {
922 // TODO: Move other elements into @Overridden getters.
Erik Kline7a26ba32018-03-09 14:18:02 +0900923 final TetheringDependencies deps = new TetheringDependencies() {
924 @Override
925 public boolean isTetheringSupported() {
926 return ConnectivityService.this.isTetheringSupported();
927 }
928 };
Erik Kline47222fc2017-04-30 19:36:15 +0900929 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
930 IoThread.get().getLooper(), new MockableSystemProperties(),
931 deps);
932 }
933
Chalard Jean26400492018-04-18 20:18:38 +0900934 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
935 final NetworkCapabilities netCap = new NetworkCapabilities();
936 netCap.addCapability(NET_CAPABILITY_INTERNET);
937 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
938 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
939 netCap.setSingleUid(uid);
940 return netCap;
941 }
942
Chalard Jeandda156a2018-01-10 21:19:32 +0900943 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900944 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900945 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900946 netCap.addCapability(NET_CAPABILITY_INTERNET);
947 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900948 if (transportType > -1) {
949 netCap.addTransportType(transportType);
950 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900951 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900952 }
953
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900954 // Used only for testing.
955 // TODO: Delete this and either:
Erik Kline79c6d052018-03-21 07:18:33 -0700956 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900957 // changing ContentResolver to make registerContentObserver non-final).
958 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
959 // by subclassing SettingsObserver.
960 @VisibleForTesting
961 void updateMobileDataAlwaysOn() {
962 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
963 }
964
Erik Kline79c6d052018-03-21 07:18:33 -0700965 // See FakeSettingsProvider comment above.
966 @VisibleForTesting
967 void updatePrivateDnsSettings() {
968 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
969 }
970
Erik Klineda4bfa82015-04-30 12:58:40 +0900971 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900972 final boolean enable = toBool(Settings.Global.getInt(
973 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900974 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
975 if (enable == isEnabled) {
976 return; // Nothing to do.
977 }
978
979 if (enable) {
980 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900981 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900982 } else {
983 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
984 }
985 }
986
987 private void registerSettingsCallbacks() {
988 // Watch for global HTTP proxy changes.
989 mSettingsObserver.observe(
990 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
991 EVENT_APPLY_GLOBAL_HTTP_PROXY);
992
993 // Watch for whether or not to keep mobile data always on.
994 mSettingsObserver.observe(
995 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
996 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
997 }
998
Erik Klinea24d4592018-01-11 21:07:29 +0900999 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline79c6d052018-03-21 07:18:33 -07001000 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1001 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +09001002 }
1003 }
1004
Robert Greenwalt34524f02014-05-18 16:22:10 -07001005 private synchronized int nextNetworkRequestId() {
1006 return mNextNetworkRequestId++;
1007 }
1008
Paul Jensen67b0b072015-06-10 11:22:17 -04001009 @VisibleForTesting
1010 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001011 synchronized (mNetworkForNetId) {
1012 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1013 int netId = mNextNetId;
1014 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1015 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001016 if (!mNetIdInUse.get(netId)) {
1017 mNetIdInUse.put(netId, true);
1018 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001019 }
1020 }
1021 }
1022 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001023 }
1024
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001025 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001026 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001027 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1028 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001029 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001030 state = nai.getNetworkState();
1031 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001032 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001033 final NetworkInfo info = new NetworkInfo(networkType, 0,
1034 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001035 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1036 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001037 final NetworkCapabilities capabilities = new NetworkCapabilities();
1038 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1039 !info.isRoaming());
1040 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001041 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001042 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001043 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001044 return state;
1045 } else {
1046 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001047 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001048 }
1049
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001050 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
1051 if (network == null) {
1052 return null;
1053 }
Erik Kline79c6d052018-03-21 07:18:33 -07001054 return getNetworkAgentInfoForNetId(network.netId);
1055 }
1056
1057 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001058 synchronized (mNetworkForNetId) {
Erik Kline79c6d052018-03-21 07:18:33 -07001059 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001060 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001061 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001062
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001063 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001064 synchronized (mVpns) {
1065 if (!mLockdownEnabled) {
1066 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001067 Vpn vpn = mVpns.get(user);
1068 if (vpn != null && vpn.appliesToUid(uid)) {
1069 return vpn.getUnderlyingNetworks();
1070 }
1071 }
1072 }
1073 return null;
1074 }
1075
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001076 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001077 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001078
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001079 final Network[] networks = getVpnUnderlyingNetworks(uid);
1080 if (networks != null) {
1081 // getUnderlyingNetworks() returns:
1082 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1083 // empty array => the VPN explicitly said "no default network".
1084 // non-empty array => the VPN specified one or more default networks; we use the
1085 // first one.
1086 if (networks.length > 0) {
1087 nai = getNetworkAgentInfoForNetwork(networks[0]);
1088 } else {
1089 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001090 }
1091 }
1092
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001093 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001094 return nai.getNetworkState();
1095 } else {
1096 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001097 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001098 }
1099
1100 /**
1101 * Check if UID should be blocked from using the network with the given LinkProperties.
1102 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001103 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1104 boolean ignoreBlocked) {
1105 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001106 if (ignoreBlocked) {
1107 return false;
1108 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001109 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001110 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1111 if (isSystem(uid)) {
1112 return false;
1113 }
Robin Lee17e61832016-05-09 13:46:28 +01001114 synchronized (mVpns) {
1115 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1116 if (vpn != null && vpn.isBlockingUid(uid)) {
1117 return true;
1118 }
1119 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001120 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001121 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001122 }
1123
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001124 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001125 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1126 return;
1127 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001128 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001129 synchronized (mBlockedAppUids) {
1130 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001131 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001132 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001133 blocked = false;
1134 } else {
1135 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001136 }
1137 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001138 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1139 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1140 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001141 }
1142
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001143 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001144 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1145 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001146 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001147 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001148 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001149 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1150
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001151 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001152 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001153 }
Hugo Benichi69744342017-11-27 10:57:16 +09001154 synchronized (mVpns) {
1155 if (mLockdownTracker != null) {
1156 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1157 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001158 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001159 }
1160
1161 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 * Return NetworkInfo for the active (i.e., connected) network interface.
1163 * It is assumed that at most one network is active at a time. If more
1164 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001165 * @return the info for the active network, or {@code null} if none is
1166 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001168 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001170 enforceAccessPermission();
1171 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001172 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001173 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001174 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1175 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 }
1177
Paul Jensen31a94f42015-02-13 14:18:39 -05001178 @Override
1179 public Network getActiveNetwork() {
1180 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001181 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001182 }
1183
1184 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001185 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001186 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001187 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001188 }
1189
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001190 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001191 final int user = UserHandle.getUserId(uid);
1192 int vpnNetId = NETID_UNSET;
1193 synchronized (mVpns) {
1194 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001195 // TODO : now that capabilities contain the UID, the appliesToUid test should
1196 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001197 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1198 }
1199 NetworkAgentInfo nai;
1200 if (vpnNetId != NETID_UNSET) {
Erik Kline79c6d052018-03-21 07:18:33 -07001201 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001202 if (nai != null) {
1203 final NetworkCapabilities requiredCaps =
1204 createDefaultNetworkCapabilitiesForUid(uid);
1205 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1206 return nai.network;
1207 }
1208 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001209 }
1210 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001211 if (nai != null
1212 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1213 nai = null;
1214 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001215 return nai != null ? nai.network : null;
1216 }
1217
Lorenzo Colitti18660282016-07-04 12:55:44 +09001218 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001219 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1220 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001221 final int uid = Binder.getCallingUid();
1222 NetworkState state = getUnfilteredActiveNetworkState(uid);
1223 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001224 }
1225
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001226 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001227 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001228 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001229 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001230 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001231 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001232 }
1233
1234 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 public NetworkInfo getNetworkInfo(int networkType) {
1236 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001237 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001238 if (getVpnUnderlyingNetworks(uid) != null) {
1239 // A VPN is active, so we may need to return one of its underlying networks. This
1240 // information is not available in LegacyTypeTracker, so we have to get it from
1241 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001242 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001243 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001244 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001245 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001246 }
1247 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001248 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001249 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 }
1251
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001252 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001253 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001254 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001255 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001256 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001257 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001258 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001259 return state.networkInfo;
1260 } else {
1261 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001262 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001263 }
1264
1265 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 public NetworkInfo[] getAllNetworkInfo() {
1267 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001268 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001269 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1270 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001271 NetworkInfo info = getNetworkInfo(networkType);
1272 if (info != null) {
1273 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001274 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001276 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 }
1278
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001279 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001280 public Network getNetworkForType(int networkType) {
1281 enforceAccessPermission();
1282 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001283 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1284 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001285 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001286 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001287 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001288 }
1289
1290 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001291 public Network[] getAllNetworks() {
1292 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001293 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001294 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001295 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001296 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001297 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001298 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001299 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001300 }
1301
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001302 @Override
1303 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1304 // The basic principle is: if an app's traffic could possibly go over a
1305 // network, without the app doing anything multinetwork-specific,
1306 // (hence, by "default"), then include that network's capabilities in
1307 // the array.
1308 //
1309 // In the normal case, app traffic only goes over the system's default
1310 // network connection, so that's the only network returned.
1311 //
1312 // With a VPN in force, some app traffic may go into the VPN, and thus
1313 // over whatever underlying networks the VPN specifies, while other app
1314 // traffic may go over the system default network (e.g.: a split-tunnel
1315 // VPN, or an app disallowed by the VPN), so the set of networks
1316 // returned includes the VPN's underlying networks and the system
1317 // default.
1318 enforceAccessPermission();
1319
1320 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1321
1322 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001323 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001324 if (nc != null) {
1325 result.put(nai.network, nc);
1326 }
1327
Hugo Benichi69744342017-11-27 10:57:16 +09001328 synchronized (mVpns) {
1329 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001330 Vpn vpn = mVpns.get(userId);
1331 if (vpn != null) {
1332 Network[] networks = vpn.getUnderlyingNetworks();
1333 if (networks != null) {
1334 for (Network network : networks) {
1335 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001336 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001337 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001338 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001339 }
1340 }
1341 }
1342 }
1343 }
1344 }
1345
1346 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1347 out = result.values().toArray(out);
1348 return out;
1349 }
1350
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001351 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001352 public boolean isNetworkSupported(int networkType) {
1353 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001354 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001355 }
1356
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001357 /**
1358 * Return LinkProperties for the active (i.e., connected) default
1359 * network interface. It is assumed that at most one default network
1360 * is active at a time. If more than one is active, it is indeterminate
1361 * which will be returned.
1362 * @return the ip properties for the active network, or {@code null} if
1363 * none is active
1364 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001365 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001366 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001367 enforceAccessPermission();
1368 final int uid = Binder.getCallingUid();
1369 NetworkState state = getUnfilteredActiveNetworkState(uid);
1370 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001371 }
1372
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001373 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001374 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001375 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001376 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1377 if (nai != null) {
1378 synchronized (nai) {
1379 return new LinkProperties(nai.linkProperties);
1380 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001381 }
1382 return null;
1383 }
1384
Robert Greenwalt12e67352014-05-13 21:41:06 -07001385 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001386 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001387 public LinkProperties getLinkProperties(Network network) {
1388 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001389 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1390 }
1391
1392 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1393 if (nai == null) {
1394 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001395 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001396 synchronized (nai) {
1397 return new LinkProperties(nai.linkProperties);
1398 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001399 }
1400
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001401 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001402 if (nai != null) {
1403 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001404 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001405 return networkCapabilitiesRestrictedForCallerPermissions(
1406 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001407 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001408 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001409 }
1410 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001411 return null;
1412 }
1413
1414 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001415 public NetworkCapabilities getNetworkCapabilities(Network network) {
1416 enforceAccessPermission();
1417 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1418 }
1419
Chalard Jeanb03a6222018-04-11 21:09:10 +09001420 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001421 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001422 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001423 if (!checkSettingsPermission(callerPid, callerUid)) {
1424 newNc.setUids(null);
1425 newNc.setSSID(null);
1426 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001427 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001428 }
1429
Chalard Jeanb552c462018-02-21 18:43:54 +09001430 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1431 if (!checkSettingsPermission()) {
1432 nc.setSingleUid(Binder.getCallingUid());
1433 }
1434 }
1435
Chalard Jean26aa91a2018-03-20 19:13:57 +09001436 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1437 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1438 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1439 }
1440 }
1441
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001442 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001443 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001444 // Require internal since we're handing out IMSI details
1445 enforceConnectivityInternalPermission();
1446
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001447 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001448 for (Network network : getAllNetworks()) {
1449 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1450 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001451 // TODO (b/73321673) : NetworkState contains a copy of the
1452 // NetworkCapabilities, which may contain UIDs of apps to which the
1453 // network applies. Should the UIDs be cleared so as not to leak or
1454 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001455 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001456 }
1457 }
1458 return result.toArray(new NetworkState[result.size()]);
1459 }
1460
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001461 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001462 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001463 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001464 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1465 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1466 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001467 }
1468
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001469 @Override
1470 public boolean isActiveNetworkMetered() {
1471 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001472
Eric Enslenc81ef192018-02-07 18:03:53 -08001473 final int uid = Binder.getCallingUid();
1474 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001475 if (caps != null) {
1476 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1477 } else {
1478 // Always return the most conservative value
1479 return true;
1480 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001481 }
1482
Jeff Sharkey216c1812012-08-05 14:29:23 -07001483 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1484 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001485 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001486 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001487 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001488 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001489 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001490
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001491 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 * Ensure that a network route exists to deliver traffic to the specified
1493 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001494 * @param networkType the type of the network over which traffic to the
1495 * specified host is to be routed
1496 * @param hostAddress the IP address of the host to which the route is
1497 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 * @return {@code true} on success, {@code false} on failure
1499 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001500 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001501 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001503 if (mProtectedNetworks.contains(networkType)) {
1504 enforceConnectivityInternalPermission();
1505 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001506
Chad Brubakerc0234532014-02-14 13:24:29 -08001507 InetAddress addr;
1508 try {
1509 addr = InetAddress.getByAddress(hostAddress);
1510 } catch (UnknownHostException e) {
1511 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1512 return false;
1513 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001516 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 return false;
1518 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001519
1520 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1521 if (nai == null) {
1522 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1523 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1524 } else {
1525 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1526 }
1527 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001528 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001529
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001530 DetailedState netState;
1531 synchronized (nai) {
1532 netState = nai.networkInfo.getDetailedState();
1533 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001534
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001535 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001536 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001537 log("requestRouteToHostAddress on down network "
1538 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001539 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001540 }
1541 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001543
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001544 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001545 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001546 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001547 LinkProperties lp;
1548 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001549 synchronized (nai) {
1550 lp = nai.linkProperties;
1551 netId = nai.network.netId;
1552 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001553 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001554 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1555 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001556 } finally {
1557 Binder.restoreCallingIdentity(token);
1558 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001559 }
1560
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001561 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001562 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001563 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001564 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001565 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001566 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001567 if (bestRoute.getGateway().equals(addr)) {
1568 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001569 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001570 } else {
1571 // if we will connect to this through another route, add a direct route
1572 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001573 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001574 }
1575 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001576 if (DBG) log("Adding legacy route " + bestRoute +
1577 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001578 try {
1579 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1580 } catch (Exception e) {
1581 // never crash - catch them all
1582 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001583 return false;
1584 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001585 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 }
1587
dalyk1fcb7392018-03-05 12:42:22 -05001588 @VisibleForTesting
1589 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1590 @Override
1591 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1592 String hostname, boolean validated) {
1593 try {
1594 mHandler.sendMessage(mHandler.obtainMessage(
1595 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1596 new PrivateDnsValidationUpdate(netId,
1597 InetAddress.parseNumericAddress(ipAddress),
1598 hostname, validated)));
1599 } catch (IllegalArgumentException e) {
1600 loge("Error parsing ip address in validation event");
1601 }
1602 }
1603 };
1604
1605 @VisibleForTesting
1606 protected void registerNetdEventCallback() {
1607 mIpConnectivityMetrics =
1608 (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1609 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1610 if (mIpConnectivityMetrics == null) {
1611 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
1612 }
1613
1614 try {
1615 mIpConnectivityMetrics.addNetdEventCallback(
1616 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1617 mNetdEventCallback);
1618 } catch (Exception e) {
1619 loge("Error registering netd callback: " + e);
1620 }
1621 }
1622
Jeff Sharkey75d31892018-01-18 22:01:59 +09001623 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001624 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001625 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001626 // TODO: notify UID when it has requested targeted updates
1627 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001628 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001629 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001630 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001631 if (restrictBackground) {
1632 log("onRestrictBackgroundChanged(true): disabling tethering");
1633 mTethering.untetherAll();
1634 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001635 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001636 };
1637
Robin Lee3b3dd942015-05-12 18:14:58 +01001638 /**
1639 * Require that the caller is either in the same user or has appropriate permission to interact
1640 * across users.
1641 *
1642 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1643 */
1644 private void enforceCrossUserPermission(int userId) {
1645 if (userId == UserHandle.getCallingUserId()) {
1646 // Not a cross-user call.
1647 return;
1648 }
1649 mContext.enforceCallingOrSelfPermission(
1650 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1651 "ConnectivityService");
1652 }
1653
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001654 private void enforceInternetPermission() {
1655 mContext.enforceCallingOrSelfPermission(
1656 android.Manifest.permission.INTERNET,
1657 "ConnectivityService");
1658 }
1659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001661 mContext.enforceCallingOrSelfPermission(
1662 android.Manifest.permission.ACCESS_NETWORK_STATE,
1663 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 }
1665
1666 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001667 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 }
1669
Charles He36738632017-05-15 17:07:18 +01001670 private void enforceSettingsPermission() {
1671 mContext.enforceCallingOrSelfPermission(
1672 android.Manifest.permission.NETWORK_SETTINGS,
1673 "ConnectivityService");
1674 }
1675
Chalard Jeanb552c462018-02-21 18:43:54 +09001676 private boolean checkSettingsPermission() {
1677 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1678 android.Manifest.permission.NETWORK_SETTINGS);
1679 }
1680
1681 private boolean checkSettingsPermission(int pid, int uid) {
1682 return PERMISSION_GRANTED == mContext.checkPermission(
1683 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1684 }
1685
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001686 private void enforceTetherAccessPermission() {
1687 mContext.enforceCallingOrSelfPermission(
1688 android.Manifest.permission.ACCESS_NETWORK_STATE,
1689 "ConnectivityService");
1690 }
1691
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001692 private void enforceConnectivityInternalPermission() {
1693 mContext.enforceCallingOrSelfPermission(
1694 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1695 "ConnectivityService");
1696 }
1697
Hugo Benichi514da602016-07-19 15:59:27 +09001698 private void enforceConnectivityRestrictedNetworksPermission() {
1699 try {
1700 mContext.enforceCallingOrSelfPermission(
1701 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1702 "ConnectivityService");
1703 return;
1704 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1705 enforceConnectivityInternalPermission();
1706 }
1707
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001708 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001709 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001710 }
1711
Lorenzo Colitti18660282016-07-04 12:55:44 +09001712 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001713 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001714 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001715 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001716 }
1717
1718 private void sendInetConditionBroadcast(NetworkInfo info) {
1719 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1720 }
1721
Wink Saville628b0852011-08-04 15:01:58 -07001722 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001723 synchronized (mVpns) {
1724 if (mLockdownTracker != null) {
1725 info = new NetworkInfo(info);
1726 mLockdownTracker.augmentNetworkInfo(info);
1727 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001728 }
1729
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001730 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001731 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001732 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 if (info.isFailover()) {
1734 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1735 info.setFailover(false);
1736 }
1737 if (info.getReason() != null) {
1738 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1739 }
1740 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001741 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1742 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001744 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001745 return intent;
1746 }
1747
1748 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1749 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1750 }
1751
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001752 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001753 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1754 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1755 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001756 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001757 final long ident = Binder.clearCallingIdentity();
1758 try {
1759 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1760 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1761 } finally {
1762 Binder.restoreCallingIdentity(ident);
1763 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001764 }
1765
Mike Lockwood0f79b542009-08-14 14:18:49 -04001766 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001767 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001768 if (!mSystemReady) {
1769 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001770 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001771 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001772 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001773 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001774 }
1775
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001776 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001777 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001778 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001779 final NetworkInfo ni = intent.getParcelableExtra(
1780 ConnectivityManager.EXTRA_NETWORK_INFO);
1781 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1782 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1783 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001784 } else {
1785 BroadcastOptions opts = BroadcastOptions.makeBasic();
1786 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1787 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001788 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001789 final IBatteryStats bs = BatteryStatsService.getService();
1790 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001791 bs.noteConnectivityChanged(intent.getIntExtra(
1792 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1793 ni != null ? ni.getState().toString() : "?");
1794 } catch (RemoteException e) {
1795 }
Chad Brubakerac925012018-03-08 10:37:09 -08001796 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001797 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001798 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001799 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001800 } finally {
1801 Binder.restoreCallingIdentity(ident);
1802 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001803 }
1804 }
1805
1806 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001807 loadGlobalProxy();
dalyk1fcb7392018-03-05 12:42:22 -05001808 registerNetdEventCallback();
Wink Saville948282b2013-08-29 08:55:16 -07001809
Hugo Benichi20035e02017-04-26 14:53:28 +09001810 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001811 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001812 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001813 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001814 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001815 }
1816 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001817 // load the global proxy at startup
1818 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001819
Robin Lee244ce8e2016-01-05 18:03:46 +00001820 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1821 // for user to unlock device too.
1822 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001823
Erik Klineda4bfa82015-04-30 12:58:40 +09001824 // Configure whether mobile data is always on.
1825 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1826
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001827 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001828
1829 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 }
1831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001833 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001834 *
1835 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001836 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001837 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001838 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1839 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001840
1841 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001842 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001843
Robert Greenwalt7b816022014-04-18 15:25:25 -07001844 if (networkAgent.networkCapabilities.hasTransport(
1845 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001846 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1847 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001848 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001849 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001850 } else if (networkAgent.networkCapabilities.hasTransport(
1851 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001852 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1853 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001854 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001855 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001856 } else {
1857 // do not track any other networks
1858 timeout = 0;
1859 }
1860
Robert Greenwalt7b816022014-04-18 15:25:25 -07001861 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001862 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001863 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001864 } catch (Exception e) {
1865 // You shall not crash!
1866 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001867 }
1868 }
1869 }
1870
1871 /**
1872 * Remove data activity tracking when network disconnects.
1873 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001874 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1875 final String iface = networkAgent.linkProperties.getInterfaceName();
1876 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001877
Robert Greenwalt7b816022014-04-18 15:25:25 -07001878 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1879 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001880 try {
1881 // the call fails silently if no idletimer setup for this interface
1882 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001883 } catch (Exception e) {
1884 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001885 }
1886 }
1887 }
1888
1889 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001890 * Reads the network specific MTU size from reources.
1891 * and set it on it's iface.
1892 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001893 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1894 final String iface = newLp.getInterfaceName();
1895 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001896 if (oldLp == null && mtu == 0) {
1897 // Silently ignore unset MTU value.
1898 return;
1899 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001900 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1901 if (VDBG) log("identical MTU - not setting");
1902 return;
1903 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001904 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001905 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001906 return;
1907 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001908
w1997615afd812014-08-05 15:18:11 -07001909 // Cannot set MTU without interface name
1910 if (TextUtils.isEmpty(iface)) {
1911 loge("Setting MTU size with null iface.");
1912 return;
1913 }
1914
Robert Greenwalt7b816022014-04-18 15:25:25 -07001915 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001916 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001917 mNetd.setMtu(iface, mtu);
1918 } catch (Exception e) {
1919 Slog.e(TAG, "exception in setMtu()" + e);
1920 }
1921 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001922
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001923 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001924 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1925
1926 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001927 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001928 protected MockableSystemProperties getSystemProperties() {
1929 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001930 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001931
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001932 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1933 if (isDefaultNetwork(nai) == false) {
1934 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001935 }
1936
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001937 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1938 String[] values = null;
1939 if (tcpBufferSizes != null) {
1940 values = tcpBufferSizes.split(",");
1941 }
1942
1943 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001944 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001945 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1946 values = tcpBufferSizes.split(",");
1947 }
1948
1949 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1950
1951 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001952 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001953
1954 final String prefix = "/sys/kernel/ipv4/tcp_";
1955 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1956 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1957 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1958 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1959 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1960 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1961 mCurrentTcpBufferSizes = tcpBufferSizes;
1962 } catch (IOException e) {
1963 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001964 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001965
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001966 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001967 Settings.Global.TCP_DEFAULT_INIT_RWND,
1968 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001969 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1970 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001971 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001972 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001973 }
1974
Robert Greenwalt562cc542014-05-15 18:07:26 -07001975 @Override
1976 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001977 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001978 NETWORK_RESTORE_DELAY_PROP_NAME);
1979 if(restoreDefaultNetworkDelayStr != null &&
1980 restoreDefaultNetworkDelayStr.length() != 0) {
1981 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001982 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001983 } catch (NumberFormatException e) {
1984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001986 // if the system property isn't set, use the value for the apn type
1987 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1988
1989 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1990 (mNetConfigs[networkType] != null)) {
1991 ret = mNetConfigs[networkType].restoreTime;
1992 }
1993 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 }
1995
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001996 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1997 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1998 final long DIAG_TIME_MS = 5000;
1999 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2000 // Start gathering diagnostic information.
2001 netDiags.add(new NetworkDiagnostics(
2002 nai.network,
2003 new LinkProperties(nai.linkProperties), // Must be a copy.
2004 DIAG_TIME_MS));
2005 }
2006
2007 for (NetworkDiagnostics netDiag : netDiags) {
2008 pw.println();
2009 netDiag.waitForMeasurements();
2010 netDiag.dump(pw);
2011 }
2012 }
2013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002015 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002016 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2017 }
2018
2019 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002020 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002021 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002022 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002023
Erik Kline3f8306b2018-05-01 16:51:44 +09002024 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002025 dumpNetworkDiagnostics(pw);
2026 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002027 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002028 mTethering.dump(fd, pw, args);
2029 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002030 }
Erik Kline379747a2015-06-05 17:47:34 +09002031
Lorenzo Colittie3805462015-06-03 11:18:24 +09002032 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002033 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002034 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002035 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002036 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002037 pw.println();
2038
Paul Jensen85cf78e2015-06-25 13:25:07 -04002039 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002040 pw.print("Active default network: ");
2041 if (defaultNai == null) {
2042 pw.println("none");
2043 } else {
2044 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002046 pw.println();
2047
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002048 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002049 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002050 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2051 pw.println(nai.toString());
2052 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002053 pw.println(String.format(
2054 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2055 nai.numForegroundNetworkRequests(),
2056 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2057 nai.numBackgroundNetworkRequests(),
2058 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002059 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002060 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2061 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002062 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002063 pw.decreaseIndent();
2064 pw.println("Lingered:");
2065 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002066 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002067 pw.decreaseIndent();
2068 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002069 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002070 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002071 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002072
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002073 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002074 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002075 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2076 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002077 }
2078 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002079 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002080
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002081 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002082
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002083 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002084 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002085
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002086 pw.println();
2087 mKeepaliveTracker.dump(pw);
2088
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002089 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002090 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002091
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002092 pw.println();
2093 mMultipathPolicyTracker.dump(pw);
2094
Erik Kline3f8306b2018-05-01 16:51:44 +09002095 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002096 pw.println();
2097 synchronized (mValidationLogs) {
2098 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002099 for (ValidationLog p : mValidationLogs) {
Chalard Jeand771aa02018-04-26 16:16:10 +09002100 pw.println(p.mNetwork + " - " + p.mName);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002101 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002102 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002103 pw.decreaseIndent();
2104 }
2105 }
Erik Kline7523eb32015-07-09 18:24:03 +09002106
2107 pw.println();
2108 pw.println("mNetworkRequestInfoLogs (most recent first):");
2109 pw.increaseIndent();
2110 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2111 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002112
2113 pw.println();
2114 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2115 pw.increaseIndent();
2116 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2117 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002118
2119 pw.println();
2120 pw.println("NetTransition WakeLock activity (most recent first):");
2121 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002122 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2123 pw.println("total releases: " + mTotalWakelockReleases);
2124 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2125 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2126 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2127 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2128 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2129 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002130 mWakelockLogs.reverseDump(fd, pw, args);
2131 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133 }
2134
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002135 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002136 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002137 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002138 if (officialNai != null && officialNai.equals(nai)) return true;
2139 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002140 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002141 " - " + nai);
2142 }
2143 return false;
2144 }
2145
Robert Greenwalt42acef32009-08-12 16:08:25 -07002146 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002147 private class NetworkStateTrackerHandler extends Handler {
2148 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002149 super(looper);
2150 }
2151
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002152 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002153 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002154 default:
2155 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002156 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002157 handleAsyncChannelHalfConnect(msg);
2158 break;
2159 }
2160 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2161 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2162 if (nai != null) nai.asyncChannel.disconnect();
2163 break;
2164 }
2165 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2166 handleAsyncChannelDisconnected(msg);
2167 break;
2168 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002169 }
2170 return true;
2171 }
2172
2173 private void maybeHandleNetworkAgentMessage(Message msg) {
2174 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2175 if (nai == null) {
2176 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002177 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002178 }
2179 return;
2180 }
2181
2182 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002183 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002184 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2185 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002186 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2187 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002188 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002189 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002190 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002191 break;
2192 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002193 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002194 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002195 break;
2196 }
2197 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002198 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002199 updateNetworkInfo(nai, info);
2200 break;
2201 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002202 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002203 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002204 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002205 break;
2206 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002207 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002208 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2209 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002210 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002211 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002212 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002213 break;
2214 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002215 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002216 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2217 break;
2218 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002219 }
2220 }
2221
2222 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2223 switch (msg.what) {
2224 default:
2225 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002226 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Erik Kline79c6d052018-03-21 07:18:33 -07002227 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002228 if (nai == null) break;
2229
2230 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2231 final boolean wasValidated = nai.lastValidated;
2232 final boolean wasDefault = isDefaultNetwork(nai);
2233
Erik Klinea24d4592018-01-11 21:07:29 +09002234 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2235
Erik Klinea24d4592018-01-11 21:07:29 +09002236 if (DBG) {
Erik Kline79c6d052018-03-21 07:18:33 -07002237 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2238 ? " with redirect to " + redirectUrl
2239 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002240 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2241 }
Erik Klinea24d4592018-01-11 21:07:29 +09002242 if (valid != nai.lastValidated) {
2243 if (wasDefault) {
2244 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2245 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002246 }
Erik Klinea24d4592018-01-11 21:07:29 +09002247 final int oldScore = nai.getCurrentScore();
2248 nai.lastValidated = valid;
2249 nai.everValidated |= valid;
2250 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2251 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2252 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2253 }
2254 updateInetCondition(nai);
2255 // Let the NetworkAgent know the state of its network
2256 Bundle redirectUrlBundle = new Bundle();
2257 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2258 nai.asyncChannel.sendMessage(
2259 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2260 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2261 0, redirectUrlBundle);
2262 if (wasValidated && !nai.lastValidated) {
2263 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002264 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002265 break;
2266 }
Paul Jensen869868be2014-05-15 10:33:05 -04002267 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002268 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002269 final boolean visible = toBool(msg.arg1);
Erik Kline79c6d052018-03-21 07:18:33 -07002270 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002271 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002272 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002273 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002274 nai.lastCaptivePortalDetected = visible;
2275 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002276 if (nai.lastCaptivePortalDetected &&
2277 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2278 if (DBG) log("Avoiding captive portal network: " + nai.name());
2279 nai.asyncChannel.sendMessage(
2280 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2281 teardownUnneededNetwork(nai);
2282 break;
2283 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002284 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002285 }
2286 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002287 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002288 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002289 if (nai == null) {
2290 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2291 break;
2292 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002293 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002294 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002295 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002296 }
Paul Jensen869868be2014-05-15 10:33:05 -04002297 }
Paul Jensen869868be2014-05-15 10:33:05 -04002298 break;
2299 }
Erik Klinea24d4592018-01-11 21:07:29 +09002300 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline79c6d052018-03-21 07:18:33 -07002301 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002302 if (nai == null) break;
2303
Erik Kline79c6d052018-03-21 07:18:33 -07002304 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002305 break;
2306 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002307 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002308 return true;
2309 }
2310
Calvin Onbe96da12016-10-11 15:10:46 -07002311 private int getCaptivePortalMode() {
2312 return Settings.Global.getInt(mContext.getContentResolver(),
2313 Settings.Global.CAPTIVE_PORTAL_MODE,
2314 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2315 }
2316
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002317 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2318 switch (msg.what) {
2319 default:
2320 return false;
2321 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2322 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2323 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2324 handleLingerComplete(nai);
2325 }
2326 break;
2327 }
2328 }
2329 return true;
2330 }
2331
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002332 @Override
2333 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002334 if (!maybeHandleAsyncChannelMessage(msg) &&
2335 !maybeHandleNetworkMonitorMessage(msg) &&
2336 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002337 maybeHandleNetworkAgentMessage(msg);
2338 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002339 }
2340 }
2341
Erik Kline79c6d052018-03-21 07:18:33 -07002342 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
2343 return NetworkMonitor.isValidationRequired(
2344 mDefaultRequest.networkCapabilities, nai.networkCapabilities);
2345 }
2346
Erik Klinea24d4592018-01-11 21:07:29 +09002347 private void handlePrivateDnsSettingsChanged() {
2348 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2349
2350 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline79c6d052018-03-21 07:18:33 -07002351 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk1fcb7392018-03-05 12:42:22 -05002352 if (networkRequiresValidation(nai)) {
2353 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2354 }
Erik Klinea24d4592018-01-11 21:07:29 +09002355 }
2356 }
2357
Erik Kline79c6d052018-03-21 07:18:33 -07002358 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2359 // Private DNS only ever applies to networks that might provide
2360 // Internet access and therefore also require validation.
2361 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002362
Erik Kline79c6d052018-03-21 07:18:33 -07002363 // Notify the NetworkMonitor thread in case it needs to cancel or
2364 // schedule DNS resolutions. If a DNS resolution is required the
2365 // result will be sent back to us.
2366 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2367
2368 // With Private DNS bypass support, we can proceed to update the
2369 // Private DNS config immediately, even if we're in strict mode
2370 // and have not yet resolved the provider name into a set of IPs.
2371 updatePrivateDns(nai, cfg);
2372 }
2373
2374 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2375 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002376 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002377 }
2378
dalyk1fcb7392018-03-05 12:42:22 -05002379 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2380 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2381 if (nai == null) {
2382 return;
2383 }
2384 mDnsManager.updatePrivateDnsValidation(update);
2385 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2386 }
2387
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002388 private void updateLingerState(NetworkAgentInfo nai, long now) {
2389 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2390 // 2. If the network was lingering and there are now requests, unlinger it.
2391 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2392 // one lingered request, start lingering.
2393 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002394 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002395 if (DBG) log("Unlingering " + nai.name());
2396 nai.unlinger();
2397 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002398 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002399 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002400 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002401 nai.linger();
2402 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2403 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2404 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002405 }
2406
Robert Greenwalt7b816022014-04-18 15:25:25 -07002407 private void handleAsyncChannelHalfConnect(Message msg) {
2408 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002409 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002410 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2411 if (VDBG) log("NetworkFactory connected");
2412 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002413 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002414 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002415 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002416 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002417 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002418 }
2419 } else {
2420 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002421 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002422 }
2423 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2424 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2425 if (VDBG) log("NetworkAgent connected");
2426 // A network agent has requested a connection. Establish the connection.
2427 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2428 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2429 } else {
2430 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002431 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002432 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002433 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002434 synchronized (mNetworkForNetId) {
2435 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002436 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002437 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002438 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002439 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002440 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002441 }
2442 }
2443 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002444
Robert Greenwalt7b816022014-04-18 15:25:25 -07002445 private void handleAsyncChannelDisconnected(Message msg) {
2446 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2447 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002448 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002449 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002450 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002451 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002452 // TODO - if we move the logic to the network agent (have them disconnect
2453 // because they lost all their requests or because their score isn't good)
2454 // then they would disconnect organically, report their new state and then
2455 // disconnect the channel.
2456 if (nai.networkInfo.isConnected()) {
2457 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2458 null, null);
2459 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002460 final boolean wasDefault = isDefaultNetwork(nai);
2461 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002462 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002463 // Log default network disconnection before required book-keeping.
2464 // Let rematchAllNetworksAndRequests() below record a new default network event
2465 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2466 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002467 long now = SystemClock.elapsedRealtime();
2468 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002469 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002470 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002471 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2472 // by other networks that are already connected. Perhaps that can be done by
2473 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2474 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002475 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002476 mKeepaliveTracker.handleStopAllKeepalives(nai,
2477 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002478 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2479 // Disable wakeup packet monitoring for each interface.
2480 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2481 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002482 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002483 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002484 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002485 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002486 // Remove the NetworkAgent, but don't mark the netId as
2487 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002488 mNetworkForNetId.remove(nai.network.netId);
2489 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002490 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002491 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2492 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002493 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002494 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002495 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002496 sendUpdatedScoreToFactories(request, 0);
2497 }
2498 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002499 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002500 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002501 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002502 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002503 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002504 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002505 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jean6b65ec72018-05-18 22:02:56 +09002506 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
2507 updateAllVpnsCapabilities();
2508 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002509 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002510 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002511 if (nai.created) {
2512 // Tell netd to clean up the configuration for this network
2513 // (routing rules, DNS, etc).
2514 // This may be slow as it requires a lot of netd shelling out to ip and
2515 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2516 // after we've rematched networks with requests which should make a potential
2517 // fallback network the default or requested a new network from the
2518 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2519 // long time.
2520 try {
2521 mNetd.removeNetwork(nai.network.netId);
2522 } catch (Exception e) {
2523 loge("Exception removing network: " + e);
2524 }
Erik Klinea24d4592018-01-11 21:07:29 +09002525 mDnsManager.removeNetwork(nai.network);
Paul Jensen62d30802015-06-17 14:42:30 -04002526 }
2527 synchronized (mNetworkForNetId) {
2528 mNetIdInUse.delete(nai.network.netId);
2529 }
2530 } else {
2531 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2532 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002533 }
2534 }
2535
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002536 // If this method proves to be too slow then we can maintain a separate
2537 // pendingIntent => NetworkRequestInfo map.
2538 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2539 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2540 Intent intent = pendingIntent.getIntent();
2541 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2542 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2543 if (existingPendingIntent != null &&
2544 existingPendingIntent.getIntent().filterEquals(intent)) {
2545 return entry.getValue();
2546 }
2547 }
2548 return null;
2549 }
2550
2551 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2552 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2553
2554 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2555 if (existingRequest != null) { // remove the existing request.
2556 if (DBG) log("Replacing " + existingRequest.request + " with "
2557 + nri.request + " because their intents matched.");
2558 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2559 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002560 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002561 }
2562
Erik Klineda4bfa82015-04-30 12:58:40 +09002563 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002564 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002565 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002566 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002567 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002568 if (nri.request.networkCapabilities.hasSignalStrength() &&
2569 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2570 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002571 }
2572 }
2573 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002574 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002575 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002576 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002577 }
2578 }
2579
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002580 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2581 int callingUid) {
2582 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2583 if (nri != null) {
2584 handleReleaseNetworkRequest(nri.request, callingUid);
2585 }
2586 }
2587
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002588 // Determines whether the network is the best (or could become the best, if it validated), for
2589 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2590 // on the value of reason:
2591 //
2592 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2593 // then it should be torn down.
2594 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2595 // then it should be lingered.
2596 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2597 final int numRequests;
2598 switch (reason) {
2599 case TEARDOWN:
2600 numRequests = nai.numRequestNetworkRequests();
2601 break;
2602 case LINGER:
2603 numRequests = nai.numForegroundNetworkRequests();
2604 break;
2605 default:
2606 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2607 return true;
2608 }
2609
2610 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002611 return false;
2612 }
Paul Jensene0988542015-06-25 15:30:08 -04002613 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002614 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2615 // Background requests don't affect lingering.
2616 continue;
2617 }
2618
Paul Jensene0988542015-06-25 15:30:08 -04002619 // If this Network is already the highest scoring Network for a request, or if
2620 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002621 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002622 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002623 // Note that this catches two important cases:
2624 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2625 // is currently satisfying the request. This is desirable when
2626 // cellular ends up validating but WiFi does not.
2627 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002628 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002629 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002630 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002631 nai.getCurrentScoreAsValidated())) {
2632 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002633 }
2634 }
Paul Jensene0988542015-06-25 15:30:08 -04002635 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002636 }
2637
Erik Klineacdd6392016-07-07 16:50:58 +09002638 private NetworkRequestInfo getNriForAppRequest(
2639 NetworkRequest request, int callingUid, String requestedOperation) {
2640 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2641
Robert Greenwalt9258c642014-03-26 16:47:06 -07002642 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002643 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002644 log(String.format("UID %d attempted to %s for unowned request %s",
2645 callingUid, requestedOperation, nri));
2646 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002647 }
Erik Klineacdd6392016-07-07 16:50:58 +09002648 }
2649
2650 return nri;
2651 }
2652
Erik Kline57faba92015-11-25 12:49:38 +09002653 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002654 if (mNetworkRequests.get(nri.request) == null) {
2655 return;
Erik Kline57faba92015-11-25 12:49:38 +09002656 }
Hugo Benichicd952782017-09-20 11:20:14 +09002657 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002658 return;
2659 }
2660 if (VDBG || (DBG && nri.request.isRequest())) {
2661 log("releasing " + nri.request + " (timeout)");
2662 }
2663 handleRemoveNetworkRequest(nri);
2664 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002665 }
2666
Erik Klineacdd6392016-07-07 16:50:58 +09002667 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002668 final NetworkRequestInfo nri =
2669 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2670 if (nri == null) {
2671 return;
Erik Kline57faba92015-11-25 12:49:38 +09002672 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002673 if (VDBG || (DBG && nri.request.isRequest())) {
2674 log("releasing " + nri.request + " (release request)");
2675 }
2676 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002677 }
Erik Klineacdd6392016-07-07 16:50:58 +09002678
Hugo Benichidba33db2017-03-23 22:40:44 +09002679 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002680 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002681 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002682
Erik Klineacdd6392016-07-07 16:50:58 +09002683 synchronized (mUidToNetworkRequestCount) {
2684 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2685 if (requests < 1) {
2686 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2687 nri.mUid);
2688 } else if (requests == 1) {
2689 mUidToNetworkRequestCount.removeAt(
2690 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2691 } else {
2692 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2693 }
2694 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002695
Erik Klineacdd6392016-07-07 16:50:58 +09002696 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2697 if (nri.request.isRequest()) {
2698 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002699 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002700 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002701 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002702 nai.removeRequest(nri.request.requestId);
2703 if (VDBG) {
2704 log(" Removing from current network " + nai.name() +
2705 ", leaving " + nai.numNetworkRequests() + " requests.");
2706 }
2707 // If there are still lingered requests on this network, don't tear it down,
2708 // but resume lingering instead.
2709 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002710 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002711 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2712 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002713 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002714 wasKept = true;
2715 }
Hugo Benichicd952782017-09-20 11:20:14 +09002716 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002717 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2718 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002719 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002720 }
Erik Klineacdd6392016-07-07 16:50:58 +09002721 }
2722
2723 // TODO: remove this code once we know that the Slog.wtf is never hit.
2724 //
2725 // Find all networks that are satisfying this request and remove the request
2726 // from their request lists.
2727 // TODO - it's my understanding that for a request there is only a single
2728 // network satisfying it, so this loop is wasteful
2729 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2730 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2731 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2732 otherNai.name() + ", but mNetworkAgentInfos says " +
2733 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002734 }
2735 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002736
Erik Klineacdd6392016-07-07 16:50:58 +09002737 // Maintain the illusion. When this request arrived, we might have pretended
2738 // that a network connected to serve it, even though the network was already
2739 // connected. Now that this request has gone away, we might have to pretend
2740 // that the network disconnected. LegacyTypeTracker will generate that
2741 // phantom disconnect for this type.
2742 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2743 boolean doRemove = true;
2744 if (wasKept) {
2745 // check if any of the remaining requests for this network are for the
2746 // same legacy type - if so, don't remove the nai
2747 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2748 NetworkRequest otherRequest = nai.requestAt(i);
2749 if (otherRequest.legacyType == nri.request.legacyType &&
2750 otherRequest.isRequest()) {
2751 if (DBG) log(" still have other legacy request - leaving");
2752 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002753 }
2754 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002755 }
2756
Erik Klineacdd6392016-07-07 16:50:58 +09002757 if (doRemove) {
2758 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002759 }
2760 }
Erik Klineacdd6392016-07-07 16:50:58 +09002761
2762 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2763 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2764 nri.request);
2765 }
2766 } else {
2767 // listens don't have a singular affectedNetwork. Check all networks to see
2768 // if this listen request applies and remove it.
2769 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2770 nai.removeRequest(nri.request.requestId);
2771 if (nri.request.networkCapabilities.hasSignalStrength() &&
2772 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2773 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2774 }
2775 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002776 }
2777 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002778
Lorenzo Colitti18660282016-07-04 12:55:44 +09002779 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002780 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2781 enforceConnectivityInternalPermission();
2782 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002783 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002784 }
2785
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002786 @Override
2787 public void setAvoidUnvalidated(Network network) {
2788 enforceConnectivityInternalPermission();
2789 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2790 }
2791
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002792 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2793 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2794 " accept=" + accept + " always=" + always);
2795
2796 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2797 if (nai == null) {
2798 // Nothing to do.
2799 return;
2800 }
2801
2802 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002803 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002804 return;
2805 }
2806
2807 if (!nai.networkMisc.explicitlySelected) {
2808 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2809 }
2810
2811 if (accept != nai.networkMisc.acceptUnvalidated) {
2812 int oldScore = nai.getCurrentScore();
2813 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002814 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002815 sendUpdatedScoreToFactories(nai);
2816 }
2817
2818 if (always) {
2819 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002820 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002821 }
2822
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002823 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002824 // Tell the NetworkAgent to not automatically reconnect to the network.
2825 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2826 // Teardown the nework.
2827 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002828 }
2829
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002830 }
2831
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002832 private void handleSetAvoidUnvalidated(Network network) {
2833 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2834 if (nai == null || nai.lastValidated) {
2835 // Nothing to do. The network either disconnected or revalidated.
2836 return;
2837 }
2838 if (!nai.avoidUnvalidated) {
2839 int oldScore = nai.getCurrentScore();
2840 nai.avoidUnvalidated = true;
2841 rematchAllNetworksAndRequests(nai, oldScore);
2842 sendUpdatedScoreToFactories(nai);
2843 }
2844 }
2845
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002846 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002847 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002848 mHandler.sendMessageDelayed(
2849 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2850 PROMPT_UNVALIDATED_DELAY_MS);
2851 }
2852
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002853 @Override
2854 public void startCaptivePortalApp(Network network) {
2855 enforceConnectivityInternalPermission();
2856 mHandler.post(() -> {
2857 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2858 if (nai == null) return;
2859 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2860 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2861 });
2862 }
2863
Hugo Benichic8e9e122016-09-14 23:23:08 +00002864 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002865 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002866 }
2867
Erik Kline065ab6e2016-10-02 18:02:14 +09002868 private void rematchForAvoidBadWifiUpdate() {
2869 rematchAllNetworksAndRequests(null, 0);
2870 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2871 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2872 sendUpdatedScoreToFactories(nai);
2873 }
2874 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002875 }
2876
Erik Kline065ab6e2016-10-02 18:02:14 +09002877 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002878 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002879 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002880 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002881 if (!configRestrict) {
2882 pw.println("Bad Wi-Fi avoidance: unrestricted");
2883 return;
2884 }
2885
2886 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2887 pw.increaseIndent();
2888 pw.println("Config restrict: " + configRestrict);
2889
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002890 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002891 String description;
2892 // Can't use a switch statement because strings are legal case labels, but null is not.
2893 if ("0".equals(value)) {
2894 description = "get stuck";
2895 } else if (value == null) {
2896 description = "prompt";
2897 } else if ("1".equals(value)) {
2898 description = "avoid";
2899 } else {
2900 description = value + " (?)";
2901 }
2902 pw.println("User setting: " + description);
2903 pw.println("Network overrides:");
2904 pw.increaseIndent();
2905 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2906 if (nai.avoidUnvalidated) {
2907 pw.println(nai.name());
2908 }
2909 }
2910 pw.decreaseIndent();
2911 pw.decreaseIndent();
2912 }
2913
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002914 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2915 final String action;
2916 switch (type) {
2917 case NO_INTERNET:
2918 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2919 break;
2920 case LOST_INTERNET:
2921 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2922 break;
2923 default:
2924 Slog.wtf(TAG, "Unknown notification type " + type);
2925 return;
2926 }
2927
2928 Intent intent = new Intent(action);
2929 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2930 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2931 intent.setClassName("com.android.settings",
2932 "com.android.settings.wifi.WifiNoInternetDialog");
2933
2934 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2935 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2936 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2937 }
2938
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002939 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002940 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002941 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2942
2943 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2944 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002945 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002946 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002947 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2948 return;
2949 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002950 showValidationNotification(nai, NotificationType.NO_INTERNET);
2951 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002952
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002953 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2954 NetworkCapabilities nc = nai.networkCapabilities;
2955 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002956
Erik Kline065ab6e2016-10-02 18:02:14 +09002957 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002958 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002959 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2960 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002961 }
2962
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002963 @Override
2964 public int getMultipathPreference(Network network) {
2965 enforceAccessPermission();
2966
2967 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002968 if (nai != null && nai.networkCapabilities
2969 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002970 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2971 }
2972
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002973 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
2974 if (networkPreference != null) {
2975 return networkPreference;
2976 }
2977
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002978 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2979 }
2980
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002981 private class InternalHandler extends Handler {
2982 public InternalHandler(Looper looper) {
2983 super(looper);
2984 }
2985
2986 @Override
2987 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002988 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002989 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002990 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002991 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002992 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002993 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002994 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002995 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002996 break;
2997 }
Jason Monkdecd2952013-10-10 14:02:51 -04002998 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002999 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003000 break;
3001 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003002 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003003 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3004 break;
3005 }
3006 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3007 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003008 break;
3009 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003010 case EVENT_REGISTER_NETWORK_AGENT: {
3011 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
3012 break;
3013 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003014 case EVENT_REGISTER_NETWORK_REQUEST:
3015 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003016 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003017 break;
3018 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003019 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3020 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003021 handleRegisterNetworkRequestWithIntent(msg);
3022 break;
3023 }
Erik Kline57faba92015-11-25 12:49:38 +09003024 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3025 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3026 handleTimedOutNetworkRequest(nri);
3027 break;
3028 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003029 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3030 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3031 break;
3032 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003033 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003034 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003035 break;
3036 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003037 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003038 Network network = (Network) msg.obj;
3039 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003040 break;
3041 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003042 case EVENT_SET_AVOID_UNVALIDATED: {
3043 handleSetAvoidUnvalidated((Network) msg.obj);
3044 break;
3045 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003046 case EVENT_PROMPT_UNVALIDATED: {
3047 handlePromptUnvalidated((Network) msg.obj);
3048 break;
3049 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003050 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
3051 handleMobileDataAlwaysOn();
3052 break;
3053 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003054 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3055 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3056 mKeepaliveTracker.handleStartKeepalive(msg);
3057 break;
3058 }
3059 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3060 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3061 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3062 int slot = msg.arg1;
3063 int reason = msg.arg2;
3064 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3065 break;
3066 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003067 case EVENT_SYSTEM_READY: {
3068 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3069 nai.networkMonitor.systemReady = true;
3070 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003071 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003072 break;
3073 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003074 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003075 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003076 break;
3077 }
Erik Klinea24d4592018-01-11 21:07:29 +09003078 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3079 handlePrivateDnsSettingsChanged();
3080 break;
dalyk1fcb7392018-03-05 12:42:22 -05003081 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3082 handlePrivateDnsValidationUpdate(
3083 (PrivateDnsValidationUpdate) msg.obj);
3084 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003085 }
3086 }
3087 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003088
3089 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003090 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003091 public int tether(String iface, String callerPkg) {
3092 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003093 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003094 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003095 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003096 } else {
3097 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3098 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003099 }
3100
3101 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003102 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003103 public int untether(String iface, String callerPkg) {
3104 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003105
3106 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003107 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003108 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003109 } else {
3110 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3111 }
3112 }
3113
3114 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003115 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003116 public int getLastTetherError(String iface) {
3117 enforceTetherAccessPermission();
3118
3119 if (isTetheringSupported()) {
3120 return mTethering.getLastTetherError(iface);
3121 } else {
3122 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3123 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003124 }
3125
3126 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003127 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003128 public String[] getTetherableUsbRegexs() {
3129 enforceTetherAccessPermission();
3130 if (isTetheringSupported()) {
3131 return mTethering.getTetherableUsbRegexs();
3132 } else {
3133 return new String[0];
3134 }
3135 }
3136
Lorenzo Colitti18660282016-07-04 12:55:44 +09003137 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003138 public String[] getTetherableWifiRegexs() {
3139 enforceTetherAccessPermission();
3140 if (isTetheringSupported()) {
3141 return mTethering.getTetherableWifiRegexs();
3142 } else {
3143 return new String[0];
3144 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003145 }
3146
Lorenzo Colitti18660282016-07-04 12:55:44 +09003147 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003148 public String[] getTetherableBluetoothRegexs() {
3149 enforceTetherAccessPermission();
3150 if (isTetheringSupported()) {
3151 return mTethering.getTetherableBluetoothRegexs();
3152 } else {
3153 return new String[0];
3154 }
3155 }
3156
Lorenzo Colitti18660282016-07-04 12:55:44 +09003157 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003158 public int setUsbTethering(boolean enable, String callerPkg) {
3159 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003160 if (isTetheringSupported()) {
3161 return mTethering.setUsbTethering(enable);
3162 } else {
3163 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3164 }
3165 }
3166
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003167 // TODO - move iface listing, queries, etc to new module
3168 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003169 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003170 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003171 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003172 return mTethering.getTetherableIfaces();
3173 }
3174
Lorenzo Colitti18660282016-07-04 12:55:44 +09003175 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003176 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003177 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003178 return mTethering.getTetheredIfaces();
3179 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003180
Lorenzo Colitti18660282016-07-04 12:55:44 +09003181 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003182 public String[] getTetheringErroredIfaces() {
3183 enforceTetherAccessPermission();
3184 return mTethering.getErroredIfaces();
3185 }
3186
Lorenzo Colitti18660282016-07-04 12:55:44 +09003187 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003188 public String[] getTetheredDhcpRanges() {
3189 enforceConnectivityInternalPermission();
3190 return mTethering.getTetheredDhcpRanges();
3191 }
3192
Udam Saini0e94c362017-06-07 12:06:28 -07003193 @Override
3194 public boolean isTetheringSupported(String callerPkg) {
3195 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3196 return isTetheringSupported();
3197 }
3198
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003199 // if ro.tether.denied = true we default to no tethering
3200 // gservices could set the secure setting to 1 though to enable it on a build where it
3201 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003202 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003203 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3204 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3205 Settings.Global.TETHER_SUPPORTED, defaultVal));
3206 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003207 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003208
3209 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3210 boolean adminUser = false;
3211 final long token = Binder.clearCallingIdentity();
3212 try {
3213 adminUser = mUserManager.isAdminUser();
3214 } finally {
3215 Binder.restoreCallingIdentity(token);
3216 }
3217
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003218 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003219 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003220
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003221 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003222 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3223 String callerPkg) {
3224 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003225 if (!isTetheringSupported()) {
3226 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3227 return;
3228 }
3229 mTethering.startTethering(type, receiver, showProvisioningUi);
3230 }
3231
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003232 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003233 public void stopTethering(int type, String callerPkg) {
3234 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003235 mTethering.stopTethering(type);
3236 }
3237
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003238 // Called when we lose the default network and have no replacement yet.
3239 // This will automatically be cleared after X seconds or a new default network
3240 // becomes CONNECTED, whichever happens first. The timer is started by the
3241 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003242 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003243 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003244 if (mNetTransitionWakeLock.isHeld()) {
3245 return;
3246 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003247 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003248 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3249 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003250 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003251 mWakelockLogs.log("ACQUIRE for " + forWhom);
3252 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3253 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003254 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003255
Hugo Benichi4c31b342017-03-30 23:18:10 +09003256 // Called when we gain a new default network to release the network transition wakelock in a
3257 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3258 // message is cancelled.
3259 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003260 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003261 if (!mNetTransitionWakeLock.isHeld()) {
3262 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003263 }
3264 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003265 // Cancel self timeout on wakelock hold.
3266 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3267 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3268 mHandler.sendMessageDelayed(msg, 1000);
3269 }
3270
3271 // Called when either message of ensureNetworkTransitionWakelock or
3272 // scheduleReleaseNetworkTransitionWakelock is processed.
3273 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3274 String event = eventName(eventId);
3275 synchronized (this) {
3276 if (!mNetTransitionWakeLock.isHeld()) {
3277 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3278 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3279 return;
3280 }
3281 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003282 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3283 mTotalWakelockDurationMs += lockDuration;
3284 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3285 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003286 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003287 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003288 }
3289
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003290 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003291 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003292 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003293 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003294 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003295 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003296 }
3297
Lorenzo Colitti18660282016-07-04 12:55:44 +09003298 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003299 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003300 enforceAccessPermission();
3301 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003302 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003303 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003304 mHandler.sendMessage(
3305 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3306 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003307
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003308 private void handleReportNetworkConnectivity(
3309 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003310 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003311 if (network == null) {
3312 nai = getDefaultNetwork();
3313 } else {
3314 nai = getNetworkAgentInfoForNetwork(network);
3315 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003316 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3317 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3318 return;
3319 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003320 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003321 if (hasConnectivity == nai.lastValidated) {
3322 return;
3323 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003324 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003325 int netid = nai.network.netId;
3326 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003327 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003328 // Validating a network that has not yet connected could result in a call to
3329 // rematchNetworkAndRequests() which is not meant to work on such networks.
3330 if (!nai.everConnected) {
3331 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003332 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003333 LinkProperties lp = getLinkProperties(nai);
3334 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3335 return;
3336 }
Erik Kline79c6d052018-03-21 07:18:33 -07003337 nai.networkMonitor.forceReevaluation(uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003338 }
3339
Paul Jensencee9b512015-05-06 07:32:40 -04003340 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003341 // this information is already available as a world read/writable jvm property
3342 // so this API change wouldn't have a benifit. It also breaks the passing
3343 // of proxy info to all the JVMs.
3344 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003345 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003346 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003347 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3348 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003349 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003350 }
3351
Lorenzo Colitti18660282016-07-04 12:55:44 +09003352 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003353 public ProxyInfo getProxyForNetwork(Network network) {
3354 if (network == null) return getDefaultProxy();
3355 final ProxyInfo globalProxy = getGlobalProxy();
3356 if (globalProxy != null) return globalProxy;
3357 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3358 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3359 // caller may not have.
3360 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3361 if (nai == null) return null;
3362 synchronized (nai) {
3363 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3364 if (proxyInfo == null) return null;
3365 return new ProxyInfo(proxyInfo);
3366 }
3367 }
3368
Paul Jensene0bef712014-12-10 15:12:18 -05003369 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3370 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3371 // proxy is null then there is no proxy in place).
3372 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3373 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3374 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3375 proxy = null;
3376 }
3377 return proxy;
3378 }
3379
3380 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3381 // better for determining if a new proxy broadcast is necessary:
3382 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3383 // avoid unnecessary broadcasts.
3384 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3385 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3386 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3387 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3388 // all set.
3389 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3390 a = canonicalizeProxyInfo(a);
3391 b = canonicalizeProxyInfo(b);
3392 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3393 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3394 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3395 }
3396
Jason Monk207900c2014-04-25 15:00:09 -04003397 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003398 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003399
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003400 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003401 if (proxyProperties == mGlobalProxy) return;
3402 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3403 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3404
3405 String host = "";
3406 int port = 0;
3407 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003408 String pacFileUrl = "";
3409 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003410 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003411 if (!proxyProperties.isValid()) {
3412 if (DBG)
3413 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3414 return;
3415 }
Jason Monk207900c2014-04-25 15:00:09 -04003416 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003417 host = mGlobalProxy.getHost();
3418 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003419 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003420 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003421 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003422 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003423 } else {
3424 mGlobalProxy = null;
3425 }
3426 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003427 final long token = Binder.clearCallingIdentity();
3428 try {
3429 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3430 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3431 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3432 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003433 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003434 } finally {
3435 Binder.restoreCallingIdentity(token);
3436 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003437
Jason Monkcf0f97a2014-10-02 15:39:38 -04003438 if (mGlobalProxy == null) {
3439 proxyProperties = mDefaultProxy;
3440 }
3441 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003442 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003443 }
3444
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003445 private void loadGlobalProxy() {
3446 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003447 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3448 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3449 String exclList = Settings.Global.getString(res,
3450 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003451 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3452 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003453 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003454 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003455 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003456 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003457 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003458 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003459 if (!proxyProperties.isValid()) {
3460 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3461 return;
3462 }
3463
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003464 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003465 mGlobalProxy = proxyProperties;
3466 }
3467 }
3468 }
3469
Jason Monk207900c2014-04-25 15:00:09 -04003470 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003471 // this information is already available as a world read/writable jvm property
3472 // so this API change wouldn't have a benifit. It also breaks the passing
3473 // of proxy info to all the JVMs.
3474 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003475 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003476 return mGlobalProxy;
3477 }
3478 }
3479
Jason Monk207900c2014-04-25 15:00:09 -04003480 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003481 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003482 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003483 proxy = null;
3484 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003485 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003486 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003487 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003488 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003489 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3490 return;
3491 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003492
3493 // This call could be coming from the PacManager, containing the port of the local
3494 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3495 // global (to get the correct local port), and send a broadcast.
3496 // TODO: Switch PacManager to have its own message to send back rather than
3497 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003498 if ((mGlobalProxy != null) && (proxy != null)
3499 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003500 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3501 mGlobalProxy = proxy;
3502 sendProxyBroadcast(mGlobalProxy);
3503 return;
3504 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003505 mDefaultProxy = proxy;
3506
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003507 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003508 if (!mDefaultProxyDisabled) {
3509 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003510 }
3511 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003512 }
3513
Paul Jensene0bef712014-12-10 15:12:18 -05003514 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3515 // This method gets called when any network changes proxy, but the broadcast only ever contains
3516 // the default proxy (even if it hasn't changed).
3517 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3518 // world where an app might be bound to a non-default network.
3519 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3520 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3521 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3522
3523 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3524 sendProxyBroadcast(getDefaultProxy());
3525 }
3526 }
3527
Robert Greenwalt434203a2010-10-11 16:00:27 -07003528 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003529 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3530 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003531 if (!TextUtils.isEmpty(proxy)) {
3532 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003533 if (data.length == 0) {
3534 return;
3535 }
3536
Robert Greenwalt434203a2010-10-11 16:00:27 -07003537 String proxyHost = data[0];
3538 int proxyPort = 8080;
3539 if (data.length > 1) {
3540 try {
3541 proxyPort = Integer.parseInt(data[1]);
3542 } catch (NumberFormatException e) {
3543 return;
3544 }
3545 }
Jason Monk207900c2014-04-25 15:00:09 -04003546 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003547 setGlobalProxy(p);
3548 }
3549 }
3550
Jason Monk207900c2014-04-25 15:00:09 -04003551 private void sendProxyBroadcast(ProxyInfo proxy) {
3552 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003553 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003554 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003555 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003556 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3557 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003558 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003559 final long ident = Binder.clearCallingIdentity();
3560 try {
3561 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3562 } finally {
3563 Binder.restoreCallingIdentity(ident);
3564 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003565 }
3566
3567 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003568 final private HashMap<Uri, Integer> mUriEventMap;
3569 final private Context mContext;
3570 final private Handler mHandler;
3571
3572 SettingsObserver(Context context, Handler handler) {
3573 super(null);
3574 mUriEventMap = new HashMap<Uri, Integer>();
3575 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003576 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003577 }
3578
Erik Klineda4bfa82015-04-30 12:58:40 +09003579 void observe(Uri uri, int what) {
3580 mUriEventMap.put(uri, what);
3581 final ContentResolver resolver = mContext.getContentResolver();
3582 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003583 }
3584
3585 @Override
3586 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003587 Slog.wtf(TAG, "Should never be reached.");
3588 }
3589
3590 @Override
3591 public void onChange(boolean selfChange, Uri uri) {
3592 final Integer what = mUriEventMap.get(uri);
3593 if (what != null) {
3594 mHandler.obtainMessage(what.intValue()).sendToTarget();
3595 } else {
3596 loge("No matching event to send for URI=" + uri);
3597 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003598 }
3599 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003600
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003601 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003602 Slog.d(TAG, s);
3603 }
3604
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003605 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003606 Slog.e(TAG, s);
3607 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003608
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003609 private static void loge(String s, Throwable t) {
3610 Slog.e(TAG, s, t);
3611 }
3612
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003613 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003614 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003615 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3616 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3617 *
3618 * @param oldPackage Package name of the application which currently controls VPN, which will
3619 * be replaced. If there is no such application, this should should either be
3620 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3621 * @param newPackage Package name of the application which should gain control of VPN, or
3622 * {@code null} to disable.
3623 * @param userId User for whom to prepare the new VPN.
3624 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003625 * @hide
3626 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003627 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003628 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3629 int userId) {
3630 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003631
Hugo Benichi20035e02017-04-26 14:53:28 +09003632 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003633 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003634 Vpn vpn = mVpns.get(userId);
3635 if (vpn != null) {
3636 return vpn.prepare(oldPackage, newPackage);
3637 } else {
3638 return false;
3639 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003640 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003641 }
3642
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003643 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003644 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3645 * This method is used by system-privileged apps.
3646 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3647 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3648 *
3649 * @param packageName The package for which authorization state should change.
3650 * @param userId User for whom {@code packageName} is installed.
3651 * @param authorized {@code true} if this app should be able to start a VPN connection without
3652 * explicit user approval, {@code false} if not.
3653 *
Jeff Davidson05542602014-08-11 14:07:27 -07003654 * @hide
3655 */
3656 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003657 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3658 enforceCrossUserPermission(userId);
3659
Hugo Benichi20035e02017-04-26 14:53:28 +09003660 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003661 Vpn vpn = mVpns.get(userId);
3662 if (vpn != null) {
3663 vpn.setPackageAuthorization(packageName, authorized);
3664 }
Jeff Davidson05542602014-08-11 14:07:27 -07003665 }
3666 }
3667
3668 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003669 * Configure a TUN interface and return its file descriptor. Parameters
3670 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003671 * and not available in ConnectivityManager. Permissions are checked in
3672 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003673 * @hide
3674 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003675 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003676 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003677 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003678 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003679 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003680 return mVpns.get(user).establish(config);
3681 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003682 }
3683
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003684 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003685 * Start legacy VPN, controlling native daemons as needed. Creates a
3686 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003687 */
3688 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003689 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003690 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003691 final LinkProperties egress = getActiveLinkProperties();
3692 if (egress == null) {
3693 throw new IllegalStateException("Missing active network connection");
3694 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003695 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003696 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003697 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3698 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003699 }
3700
3701 /**
3702 * Return the information of the ongoing legacy VPN. This method is used
3703 * by VpnSettings and not available in ConnectivityManager. Permissions
3704 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003705 */
3706 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003707 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3708 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003709
Hugo Benichi20035e02017-04-26 14:53:28 +09003710 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003711 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003712 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003713 }
3714
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003715 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003716 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3717 * and not available in ConnectivityManager.
3718 */
3719 @Override
3720 public VpnInfo[] getAllVpnInfo() {
3721 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003722 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003723 if (mLockdownEnabled) {
3724 return new VpnInfo[0];
3725 }
3726
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003727 List<VpnInfo> infoList = new ArrayList<>();
3728 for (int i = 0; i < mVpns.size(); i++) {
3729 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3730 if (info != null) {
3731 infoList.add(info);
3732 }
3733 }
3734 return infoList.toArray(new VpnInfo[infoList.size()]);
3735 }
3736 }
3737
3738 /**
3739 * @return VPN information for accounting, or null if we can't retrieve all required
3740 * information, e.g primary underlying iface.
3741 */
3742 @Nullable
3743 private VpnInfo createVpnInfo(Vpn vpn) {
3744 VpnInfo info = vpn.getVpnInfo();
3745 if (info == null) {
3746 return null;
3747 }
3748 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3749 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3750 // the underlyingNetworks list.
3751 if (underlyingNetworks == null) {
3752 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3753 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3754 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3755 }
3756 } else if (underlyingNetworks.length > 0) {
3757 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3758 if (linkProperties != null) {
3759 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3760 }
3761 }
3762 return info.primaryUnderlyingIface == null ? null : info;
3763 }
3764
3765 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003766 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3767 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003768 * Permissions are checked in Vpn class.
3769 * @hide
3770 */
3771 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003772 public VpnConfig getVpnConfig(int userId) {
3773 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003774 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003775 Vpn vpn = mVpns.get(userId);
3776 if (vpn != null) {
3777 return vpn.getVpnConfig();
3778 } else {
3779 return null;
3780 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003781 }
3782 }
3783
Chalard Jean6b65ec72018-05-18 22:02:56 +09003784 /**
3785 * Ask all VPN objects to recompute and update their capabilities.
3786 *
3787 * When underlying networks change, VPNs may have to update capabilities to reflect things
3788 * like the metered bit, their transports, and so on. This asks the VPN objects to update
3789 * their capabilities, and as this will cause them to send messages to the ConnectivityService
3790 * handler thread through their agent, this is asynchronous. When the capabilities objects
3791 * are computed they will be up-to-date as they are computed synchronously from here and
3792 * this is running on the ConnectivityService thread.
3793 * TODO : Fix this and call updateCapabilities inline to remove out-of-order events.
3794 */
3795 private void updateAllVpnsCapabilities() {
3796 synchronized (mVpns) {
3797 for (int i = 0; i < mVpns.size(); i++) {
3798 final Vpn vpn = mVpns.valueAt(i);
3799 vpn.updateCapabilities();
3800 }
3801 }
3802 }
3803
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003804 @Override
3805 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003806 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3807 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3808 return false;
3809 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003810
Hugo Benichi69744342017-11-27 10:57:16 +09003811 synchronized (mVpns) {
3812 // Tear down existing lockdown if profile was removed
3813 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3814 if (mLockdownEnabled) {
3815 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3816 if (profileTag == null) {
3817 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3818 return false;
3819 }
3820 String profileName = new String(profileTag);
3821 final VpnProfile profile = VpnProfile.decode(
3822 profileName, mKeyStore.get(Credentials.VPN + profileName));
3823 if (profile == null) {
3824 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3825 setLockdownTracker(null);
3826 return true;
3827 }
3828 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003829 Vpn vpn = mVpns.get(user);
3830 if (vpn == null) {
3831 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3832 return false;
3833 }
3834 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003835 } else {
3836 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003837 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003838 }
3839
3840 return true;
3841 }
3842
3843 /**
3844 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3845 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3846 */
Hugo Benichi69744342017-11-27 10:57:16 +09003847 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003848 private void setLockdownTracker(LockdownVpnTracker tracker) {
3849 // Shutdown any existing tracker
3850 final LockdownVpnTracker existing = mLockdownTracker;
3851 mLockdownTracker = null;
3852 if (existing != null) {
3853 existing.shutdown();
3854 }
3855
Robin Leec3736bc2017-03-10 16:19:54 +00003856 if (tracker != null) {
3857 mLockdownTracker = tracker;
3858 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003859 }
3860 }
3861
Hugo Benichi69744342017-11-27 10:57:16 +09003862 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003863 private void throwIfLockdownEnabled() {
3864 if (mLockdownEnabled) {
3865 throw new IllegalStateException("Unavailable in lockdown mode");
3866 }
3867 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003868
Robin Lee244ce8e2016-01-05 18:03:46 +00003869 /**
Robin Lee17e61832016-05-09 13:46:28 +01003870 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3871 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003872 *
Robin Lee17e61832016-05-09 13:46:28 +01003873 * @return {@code true} if the service was started, the service was already connected, or there
3874 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003875 */
Robin Lee17e61832016-05-09 13:46:28 +01003876 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003877 synchronized (mVpns) {
3878 Vpn vpn = mVpns.get(userId);
3879 if (vpn == null) {
3880 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3881 // exists already.
3882 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3883 return false;
3884 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003885
Robin Lee812800c2016-05-13 15:38:08 +01003886 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003887 }
3888 }
3889
3890 @Override
Charles He36738632017-05-15 17:07:18 +01003891 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3892 enforceSettingsPermission();
3893 enforceCrossUserPermission(userId);
3894
3895 synchronized (mVpns) {
3896 Vpn vpn = mVpns.get(userId);
3897 if (vpn == null) {
3898 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3899 return false;
3900 }
3901 return vpn.isAlwaysOnPackageSupported(packageName);
3902 }
3903 }
3904
3905 @Override
Robin Leedc679712016-05-03 13:23:03 +01003906 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003907 enforceConnectivityInternalPermission();
3908 enforceCrossUserPermission(userId);
3909
Robin Lee244ce8e2016-01-05 18:03:46 +00003910 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003911 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3912 if (LockdownVpnTracker.isEnabled()) {
3913 return false;
3914 }
3915
Robin Lee244ce8e2016-01-05 18:03:46 +00003916 Vpn vpn = mVpns.get(userId);
3917 if (vpn == null) {
3918 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3919 return false;
3920 }
Robin Lee17e61832016-05-09 13:46:28 +01003921 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003922 return false;
3923 }
Robin Lee17e61832016-05-09 13:46:28 +01003924 if (!startAlwaysOnVpn(userId)) {
3925 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003926 return false;
3927 }
3928 }
3929 return true;
3930 }
3931
3932 @Override
3933 public String getAlwaysOnVpnPackage(int userId) {
3934 enforceConnectivityInternalPermission();
3935 enforceCrossUserPermission(userId);
3936
3937 synchronized (mVpns) {
3938 Vpn vpn = mVpns.get(userId);
3939 if (vpn == null) {
3940 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3941 return null;
3942 }
3943 return vpn.getAlwaysOnPackage();
3944 }
3945 }
3946
Wink Savilleab9321d2013-06-29 21:10:57 -07003947 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003948 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003949 // TODO: Remove? Any reason to trigger a provisioning check?
3950 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003951 }
3952
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003953 /** Location to an updatable file listing carrier provisioning urls.
3954 * An example:
3955 *
3956 * <?xml version="1.0" encoding="utf-8"?>
3957 * <provisioningUrls>
3958 * <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 -07003959 * </provisioningUrls>
3960 */
3961 private static final String PROVISIONING_URL_PATH =
3962 "/data/misc/radio/provisioning_urls.xml";
3963 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003964
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003965 /** XML tag for root element. */
3966 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3967 /** XML tag for individual url */
3968 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003969 /** XML attribute for mcc */
3970 private static final String ATTR_MCC = "mcc";
3971 /** XML attribute for mnc */
3972 private static final String ATTR_MNC = "mnc";
3973
Paul Jensen434dde82015-06-11 09:43:30 -04003974 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003975 FileReader fileReader = null;
3976 XmlPullParser parser = null;
3977 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003978
3979 try {
3980 fileReader = new FileReader(mProvisioningUrlFile);
3981 parser = Xml.newPullParser();
3982 parser.setInput(fileReader);
3983 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3984
3985 while (true) {
3986 XmlUtils.nextElement(parser);
3987
3988 String element = parser.getName();
3989 if (element == null) break;
3990
Paul Jensen434dde82015-06-11 09:43:30 -04003991 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003992 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3993 try {
3994 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3995 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3996 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3997 parser.next();
3998 if (parser.getEventType() == XmlPullParser.TEXT) {
3999 return parser.getText();
4000 }
4001 }
4002 }
4003 } catch (NumberFormatException e) {
4004 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4005 }
4006 }
4007 }
4008 return null;
4009 } catch (FileNotFoundException e) {
4010 loge("Carrier Provisioning Urls file not found");
4011 } catch (XmlPullParserException e) {
4012 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4013 } catch (IOException e) {
4014 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4015 } finally {
4016 if (fileReader != null) {
4017 try {
4018 fileReader.close();
4019 } catch (IOException e) {}
4020 }
4021 }
4022 return null;
4023 }
4024
Wink Saville42d4f082013-07-20 20:31:59 -07004025 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004026 public String getMobileProvisioningUrl() {
4027 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04004028 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004029 if (TextUtils.isEmpty(url)) {
4030 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004031 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004032 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004033 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004034 }
Wink Saville8cf35602013-07-10 23:00:07 -07004035 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004036 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004037 String phoneNumber = mTelephonyManager.getLine1Number();
4038 if (TextUtils.isEmpty(phoneNumber)) {
4039 phoneNumber = "0000000000";
4040 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004041 url = String.format(url,
4042 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4043 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07004044 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004045 }
4046
Wink Savilleab9321d2013-06-29 21:10:57 -07004047 return url;
4048 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004049
Wink Saville948282b2013-08-29 08:55:16 -07004050 @Override
4051 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004052 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004053 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004054 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4055 return;
4056 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004057 final long ident = Binder.clearCallingIdentity();
4058 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004059 // Concatenate the range of types onto the range of NetIDs.
4060 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4061 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004062 } finally {
4063 Binder.restoreCallingIdentity(ident);
4064 }
Wink Saville948282b2013-08-29 08:55:16 -07004065 }
Wink Saville7788c612013-08-29 14:57:08 -07004066
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004067 @Override
4068 public void setAirplaneMode(boolean enable) {
4069 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004070 final long ident = Binder.clearCallingIdentity();
4071 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004072 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004073 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004074 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4075 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004076 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004077 } finally {
4078 Binder.restoreCallingIdentity(ident);
4079 }
4080 }
4081
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004082 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004083 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004084 Vpn userVpn = mVpns.get(userId);
4085 if (userVpn != null) {
4086 loge("Starting user already has a VPN");
4087 return;
4088 }
Paul Jensene75b9e32015-04-06 11:54:53 -04004089 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004090 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004091 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4092 updateLockdownVpn();
4093 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004094 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004095 }
4096
4097 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004098 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004099 Vpn userVpn = mVpns.get(userId);
4100 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004101 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004102 return;
4103 }
Robin Lee17e61832016-05-09 13:46:28 +01004104 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004105 mVpns.delete(userId);
4106 }
4107 }
4108
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004109 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004110 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004111 final int vpnsSize = mVpns.size();
4112 for (int i = 0; i < vpnsSize; i++) {
4113 Vpn vpn = mVpns.valueAt(i);
4114 vpn.onUserAdded(userId);
4115 }
4116 }
4117 }
4118
4119 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004120 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004121 final int vpnsSize = mVpns.size();
4122 for (int i = 0; i < vpnsSize; i++) {
4123 Vpn vpn = mVpns.valueAt(i);
4124 vpn.onUserRemoved(userId);
4125 }
4126 }
4127 }
4128
Robin Lee89e7a692016-02-29 14:38:17 +00004129 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004130 synchronized (mVpns) {
4131 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4132 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4133 updateLockdownVpn();
4134 } else {
4135 startAlwaysOnVpn(userId);
4136 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004137 }
4138 }
4139
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004140 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4141 @Override
4142 public void onReceive(Context context, Intent intent) {
4143 final String action = intent.getAction();
4144 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4145 if (userId == UserHandle.USER_NULL) return;
4146
Robin Lee323f29d2016-05-04 16:38:06 +01004147 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004148 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004149 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004150 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004151 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4152 onUserAdded(userId);
4153 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4154 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004155 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4156 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004157 }
4158 }
4159 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004160
Robin Lee95204e02017-01-27 11:59:22 +00004161 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4162 @Override
4163 public void onReceive(Context context, Intent intent) {
4164 // Try creating lockdown tracker, since user present usually means
4165 // unlocked keystore.
4166 updateLockdownVpn();
4167 mContext.unregisterReceiver(this);
4168 }
4169 };
4170
Robert Greenwalta67be032014-05-16 15:49:14 -07004171 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4172 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004173 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4174 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004175
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004176 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4177 // Map from UID to number of NetworkRequests that UID has filed.
4178 @GuardedBy("mUidToNetworkRequestCount")
4179 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4180
Robert Greenwalta67be032014-05-16 15:49:14 -07004181 private static class NetworkFactoryInfo {
4182 public final String name;
4183 public final Messenger messenger;
4184 public final AsyncChannel asyncChannel;
4185
4186 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4187 this.name = name;
4188 this.messenger = messenger;
4189 this.asyncChannel = asyncChannel;
4190 }
4191 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004192
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004193 private void ensureNetworkRequestHasType(NetworkRequest request) {
4194 if (request.type == NetworkRequest.Type.NONE) {
4195 throw new IllegalArgumentException(
4196 "All NetworkRequests in ConnectivityService must have a type");
4197 }
4198 }
4199
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004200 /**
4201 * Tracks info about the requester.
4202 * Also used to notice when the calling process dies so we can self-expire
4203 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004204 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004205 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004206 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004207 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004208 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004209 final int mPid;
4210 final int mUid;
4211 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004212
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004213 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004214 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004215 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004216 mPendingIntent = pi;
4217 messenger = null;
4218 mBinder = null;
4219 mPid = getCallingPid();
4220 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004221 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004222 }
4223
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004224 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004225 super();
4226 messenger = m;
4227 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004228 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004229 mBinder = binder;
4230 mPid = getCallingPid();
4231 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004232 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004233 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004234
4235 try {
4236 mBinder.linkToDeath(this, 0);
4237 } catch (RemoteException e) {
4238 binderDied();
4239 }
4240 }
4241
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004242 private void enforceRequestCountLimit() {
4243 synchronized (mUidToNetworkRequestCount) {
4244 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4245 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004246 throw new ServiceSpecificException(
4247 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004248 }
4249 mUidToNetworkRequestCount.put(mUid, networkRequests);
4250 }
4251 }
4252
Robert Greenwalt9258c642014-03-26 16:47:06 -07004253 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004254 if (mBinder != null) {
4255 mBinder.unlinkToDeath(this, 0);
4256 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004257 }
4258
4259 public void binderDied() {
4260 log("ConnectivityService NetworkRequestInfo binderDied(" +
4261 request + ", " + mBinder + ")");
4262 releaseNetworkRequest(request);
4263 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004264
4265 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004266 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004267 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004268 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004269 }
4270
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004271 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4272 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4273 if (badCapability != null) {
4274 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004275 }
4276 }
4277
Chalard Jeanb03a6222018-04-11 21:09:10 +09004278 // This checks that the passed capabilities either do not request a specific SSID, or the
4279 // calling app has permission to do so.
4280 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4281 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004282 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004283 throw new SecurityException("Insufficient permissions to request a specific SSID");
4284 }
4285 }
4286
Erik Kline9d598e12015-07-13 16:37:51 +09004287 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004288 final SortedSet<Integer> thresholds = new TreeSet();
4289 synchronized (nai) {
4290 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4291 if (nri.request.networkCapabilities.hasSignalStrength() &&
4292 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4293 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4294 }
4295 }
4296 }
Erik Kline9d598e12015-07-13 16:37:51 +09004297 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004298 }
4299
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004300 private void updateSignalStrengthThresholds(
4301 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4302 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004303 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004304 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4305
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004306 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004307 String detail;
4308 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4309 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4310 } else {
4311 detail = reason;
4312 }
4313 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4314 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4315 }
4316
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004317 nai.asyncChannel.sendMessage(
4318 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004319 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004320 }
4321
Etan Cohen859748f2017-04-03 17:42:34 -07004322 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4323 if (nc == null) {
4324 return;
4325 }
4326 NetworkSpecifier ns = nc.getNetworkSpecifier();
4327 if (ns == null) {
4328 return;
4329 }
4330 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4331 ns.assertValidFromUid(Binder.getCallingUid());
4332 }
4333
Robert Greenwalt9258c642014-03-26 16:47:06 -07004334 @Override
4335 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004336 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004337 final NetworkRequest.Type type = (networkCapabilities == null)
4338 ? NetworkRequest.Type.TRACK_DEFAULT
4339 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004340 // If the requested networkCapabilities is null, take them instead from
4341 // the default network request. This allows callers to keep track of
4342 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004343 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09004344 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09004345 enforceAccessPermission();
4346 } else {
4347 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4348 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004349 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4350 // of the app when the request is filed, but we never change the request if the app
4351 // changes network state. http://b/29964605
4352 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004353 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004354 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004355 ensureSufficientPermissionsForRequest(networkCapabilities,
4356 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004357 // Set the UID range for this request to the single UID of the requester, or to an empty
4358 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004359 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4360 // are no visible methods to set the UIDs, an app could use reflection to try and get
4361 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004362 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004363
Etan Cohenba07c8c2017-02-05 10:42:27 -08004364 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004365 throw new IllegalArgumentException("Bad timeout specified");
4366 }
Etan Cohen859748f2017-04-03 17:42:34 -07004367 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004368
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004369 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004370 nextNetworkRequestId(), type);
4371 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004372 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004373
4374 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004375 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004376 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004377 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004378 }
4379 return networkRequest;
4380 }
4381
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004382 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004383 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004384 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004385 } else {
4386 enforceChangePermission();
4387 }
4388 }
4389
fenglub15e72b2015-03-20 11:29:56 -07004390 @Override
fengludb571472015-04-21 17:12:05 -07004391 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004392 enforceAccessPermission();
4393 NetworkAgentInfo nai = null;
4394 if (network == null) {
4395 return false;
4396 }
4397 synchronized (mNetworkForNetId) {
4398 nai = mNetworkForNetId.get(network.netId);
4399 }
4400 if (nai != null) {
4401 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4402 return true;
4403 }
4404 return false;
4405 }
4406
Felipe Lemeee27cab2016-06-20 16:36:29 -07004407 private boolean isSystem(int uid) {
4408 return uid < Process.FIRST_APPLICATION_UID;
4409 }
fenglub15e72b2015-03-20 11:29:56 -07004410
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004411 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004412 final int uid = Binder.getCallingUid();
4413 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004414 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004415 return;
4416 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004417 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4418 // Policy already enforced.
4419 return;
4420 }
4421 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4422 // If UID is restricted, don't allow them to bring up metered APNs.
4423 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004424 }
4425 }
4426
Robert Greenwalt9258c642014-03-26 16:47:06 -07004427 @Override
4428 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4429 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004430 checkNotNull(operation, "PendingIntent cannot be null.");
4431 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4432 enforceNetworkRequestPermissions(networkCapabilities);
4433 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004434 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004435 ensureSufficientPermissionsForRequest(networkCapabilities,
4436 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07004437 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004438 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004439
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004440 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004441 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4442 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004443 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004444 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4445 nri));
4446 return networkRequest;
4447 }
4448
Jeremy Joslin79294842014-12-03 17:15:28 -08004449 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4450 mHandler.sendMessageDelayed(
4451 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4452 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4453 }
4454
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004455 @Override
4456 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004457 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004458 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4459 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004460 }
4461
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004462 // In order to implement the compatibility measure for pre-M apps that call
4463 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4464 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4465 // This ensures it has permission to do so.
4466 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4467 if (nc == null) {
4468 return false;
4469 }
4470 int[] transportTypes = nc.getTransportTypes();
4471 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4472 return false;
4473 }
4474 try {
4475 mContext.enforceCallingOrSelfPermission(
4476 android.Manifest.permission.ACCESS_WIFI_STATE,
4477 "ConnectivityService");
4478 } catch (SecurityException e) {
4479 return false;
4480 }
4481 return true;
4482 }
4483
Robert Greenwalt9258c642014-03-26 16:47:06 -07004484 @Override
4485 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4486 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004487 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4488 enforceAccessPermission();
4489 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004490
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004491 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004492 ensureSufficientPermissionsForRequest(networkCapabilities,
4493 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004494 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09004495 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4496 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4497 // onLost and onAvailable callbacks when networks move in and out of the background.
4498 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4499 // can't request networks.
4500 restrictBackgroundRequestForCaller(nc);
4501 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004502
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004503 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004504 NetworkRequest.Type.LISTEN);
4505 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004506 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004507
4508 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4509 return networkRequest;
4510 }
4511
4512 @Override
4513 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4514 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004515 checkNotNull(operation, "PendingIntent cannot be null.");
4516 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4517 enforceAccessPermission();
4518 }
Etan Cohen859748f2017-04-03 17:42:34 -07004519 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004520 ensureSufficientPermissionsForRequest(networkCapabilities,
4521 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004522
Chalard Jeandda156a2018-01-10 21:19:32 +09004523 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004524 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004525
4526 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004527 NetworkRequest.Type.LISTEN);
4528 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004529 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004530
4531 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004532 }
4533
Erik Klineacdd6392016-07-07 16:50:58 +09004534 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004535 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004536 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004537 mHandler.sendMessage(mHandler.obtainMessage(
4538 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004539 }
4540
4541 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004542 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004543 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004544 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4545 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004546 }
4547
Robert Greenwalta67be032014-05-16 15:49:14 -07004548 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004549 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004550 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4551 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4552 }
4553
4554 @Override
4555 public void unregisterNetworkFactory(Messenger messenger) {
4556 enforceConnectivityInternalPermission();
4557 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4558 }
4559
4560 private void handleUnregisterNetworkFactory(Messenger messenger) {
4561 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4562 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004563 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004564 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004565 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004566 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004567 }
4568
Robert Greenwalt7b816022014-04-18 15:25:25 -07004569 /**
4570 * NetworkAgentInfo supporting a request by requestId.
4571 * These have already been vetted (their Capabilities satisfy the request)
4572 * and the are the highest scored network available.
4573 * the are keyed off the Requests requestId.
4574 */
Hugo Benichicd952782017-09-20 11:20:14 +09004575 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4576 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004577 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4578 new SparseArray<NetworkAgentInfo>();
4579
Paul Jensen31a94f42015-02-13 14:18:39 -05004580 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4581 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004582 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4583 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004584 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4585 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4586 // there may not be a strict 1:1 correlation between the two.
4587 @GuardedBy("mNetworkForNetId")
4588 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004589
Robert Greenwalt7b816022014-04-18 15:25:25 -07004590 // NetworkAgentInfo keyed off its connecting messenger
4591 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004592 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004593 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4594 new HashMap<Messenger, NetworkAgentInfo>();
4595
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004596 @GuardedBy("mBlockedAppUids")
4597 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4598
Paul Jensen2c311d62014-11-17 12:34:51 -05004599 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004600 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09004601
Erik Klineda4bfa82015-04-30 12:58:40 +09004602 // Request used to optionally keep mobile data active even when higher
4603 // priority networks like Wi-Fi are active.
4604 private final NetworkRequest mDefaultMobileDataRequest;
4605
Hugo Benichicd952782017-09-20 11:20:14 +09004606 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4607 synchronized (mNetworkForRequestId) {
4608 return mNetworkForRequestId.get(requestId);
4609 }
4610 }
4611
4612 private void clearNetworkForRequest(int requestId) {
4613 synchronized (mNetworkForRequestId) {
4614 mNetworkForRequestId.remove(requestId);
4615 }
4616 }
4617
4618 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4619 synchronized (mNetworkForRequestId) {
4620 mNetworkForRequestId.put(requestId, nai);
4621 }
4622 }
4623
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004624 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004625 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004626 }
4627
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004628 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004629 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004630 }
4631
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004632 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4633 return nri.request.requestId == mDefaultRequest.requestId;
4634 }
4635
Paul Jensen31a94f42015-02-13 14:18:39 -05004636 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004637 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004638 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004639 enforceConnectivityInternalPermission();
4640
Rubin Xu1bb5c082017-09-05 18:40:49 +01004641 LinkProperties lp = new LinkProperties(linkProperties);
4642 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004643 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4644 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004645 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004646 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004647 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004648 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004649 // Make sure the network capabilities reflect what the agent info says.
4650 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004651 synchronized (this) {
4652 nai.networkMonitor.systemReady = mSystemReady;
4653 }
Chalard Jeand771aa02018-04-26 16:16:10 +09004654 final String extraInfo = networkInfo.getExtraInfo();
4655 final String name = TextUtils.isEmpty(extraInfo)
4656 ? nai.networkCapabilities.getSSID() : extraInfo;
4657 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network, name);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004658 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004659 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004660 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004661 }
4662
Erik Kline117e7f32018-03-04 21:01:01 +09004663 private void handleRegisterNetworkAgent(NetworkAgentInfo nai) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004664 if (VDBG) log("Got NetworkAgent Messenger");
Erik Kline117e7f32018-03-04 21:01:01 +09004665 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004666 synchronized (mNetworkForNetId) {
Erik Kline117e7f32018-03-04 21:01:01 +09004667 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004668 }
Erik Kline117e7f32018-03-04 21:01:01 +09004669 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
4670 NetworkInfo networkInfo = nai.networkInfo;
4671 nai.networkInfo = null;
4672 updateNetworkInfo(nai, networkInfo);
4673 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004674 }
4675
4676 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4677 LinkProperties newLp = networkAgent.linkProperties;
4678 int netId = networkAgent.network.netId;
4679
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004680 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4681 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004682 if (networkAgent.clatd != null) {
4683 networkAgent.clatd.fixupLinkProperties(oldLp);
4684 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004685
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004686 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004687 updateMtu(newLp, oldLp);
4688 // TODO - figure out what to do for clat
4689// for (LinkProperties lp : newLp.getStackedLinks()) {
4690// updateMtu(lp, null);
4691// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004692 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004693
Erik Kline94887872016-04-05 13:30:49 +09004694 updateRoutes(newLp, oldLp, netId);
4695 updateDnses(newLp, oldLp, netId);
dalyk1fcb7392018-03-05 12:42:22 -05004696 // Make sure LinkProperties represents the latest private DNS status.
4697 // This does not need to be done before updateDnses because the
4698 // LinkProperties are not the source of the private DNS configuration.
4699 // updateDnses will fetch the private DNS configuration from DnsManager.
4700 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004701
Hugo Benichi6f62b732017-06-27 15:13:20 +09004702 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004703 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004704 if (isDefaultNetwork(networkAgent)) {
4705 handleApplyDefaultProxy(newLp.getHttpProxy());
4706 } else {
4707 updateProxy(newLp, oldLp, networkAgent);
4708 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004709 // TODO - move this check to cover the whole function
4710 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004711 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004712 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4713 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004714
4715 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004716 }
4717
Joel Scherpelz668370b2017-06-08 15:35:21 +09004718 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004719 // Marks are only available on WiFi interaces. Checking for
4720 // marks on unsupported interfaces is harmless.
4721 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4722 return;
4723 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004724
Joel Scherpelz668370b2017-06-08 15:35:21 +09004725 int mark = mContext.getResources().getInteger(
4726 com.android.internal.R.integer.config_networkWakeupPacketMark);
4727 int mask = mContext.getResources().getInteger(
4728 com.android.internal.R.integer.config_networkWakeupPacketMask);
4729
4730 // Mask/mark of zero will not detect anything interesting.
4731 // Don't install rules unless both values are nonzero.
4732 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004733 return;
4734 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004735
4736 final String prefix = "iface:" + iface;
4737 try {
4738 if (add) {
4739 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4740 } else {
4741 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4742 }
4743 } catch (Exception e) {
4744 loge("Exception modifying wakeup packet monitoring: " + e);
4745 }
4746
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004747 }
4748
4749 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4750 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004751 CompareResult<String> interfaceDiff = new CompareResult<String>(
4752 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4753 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004754 for (String iface : interfaceDiff.added) {
4755 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004756 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004757 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004758 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004759 } catch (Exception e) {
4760 loge("Exception adding interface: " + e);
4761 }
4762 }
4763 for (String iface : interfaceDiff.removed) {
4764 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004765 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004766 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004767 mNetd.removeInterfaceFromNetwork(iface, netId);
4768 } catch (Exception e) {
4769 loge("Exception removing interface: " + e);
4770 }
4771 }
4772 }
4773
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004774 /**
4775 * Have netd update routes from oldLp to newLp.
4776 * @return true if routes changed between oldLp and newLp
4777 */
4778 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004779 // Compare the route diff to determine which routes should be added and removed.
4780 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4781 oldLp != null ? oldLp.getAllRoutes() : null,
4782 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004783
4784 // add routes before removing old in case it helps with continuous connectivity
4785
4786 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4787 for (RouteInfo route : routeDiff.added) {
4788 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004789 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004790 try {
4791 mNetd.addRoute(netId, route);
4792 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004793 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4794 loge("Exception in addRoute for non-gateway: " + e);
4795 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004796 }
4797 }
4798 for (RouteInfo route : routeDiff.added) {
4799 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004800 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004801 try {
4802 mNetd.addRoute(netId, route);
4803 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004804 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4805 loge("Exception in addRoute for gateway: " + e);
4806 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004807 }
4808 }
4809
4810 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004811 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004812 try {
4813 mNetd.removeRoute(netId, route);
4814 } catch (Exception e) {
4815 loge("Exception in removeRoute: " + e);
4816 }
4817 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004818 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004819 }
Erik Kline41368502015-06-17 13:19:54 +09004820
Erik Kline94887872016-04-05 13:30:49 +09004821 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4822 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4823 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004824 }
Erik Kline94887872016-04-05 13:30:49 +09004825
Erik Kline1742fe12017-12-13 19:40:49 +09004826 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4827 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4828
Erik Klinea24d4592018-01-11 21:07:29 +09004829 if (DBG) {
4830 final Collection<InetAddress> dnses = newLp.getDnsServers();
4831 log("Setting DNS servers for network " + netId + " to " + dnses);
4832 }
Erik Kline94887872016-04-05 13:30:49 +09004833 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004834 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004835 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004836 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004837 }
Erik Kline4edba012017-04-07 15:29:29 +09004838 }
4839
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004840 private String getNetworkPermission(NetworkCapabilities nc) {
4841 // TODO: make these permission strings AIDL constants instead.
4842 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4843 return NetworkManagementService.PERMISSION_SYSTEM;
4844 }
4845 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4846 return NetworkManagementService.PERMISSION_NETWORK;
4847 }
4848 return null;
4849 }
4850
Paul Jensen3d194ea2015-06-16 14:27:36 -04004851 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004852 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4853 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4854 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004855 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004856 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004857 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004858 if (nai.everConnected &&
4859 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4860 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004861 // does not cause any request (that is not a listen) currently matching that agent to
4862 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004863 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09004864 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004865 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09004866 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004867 }
4868
Paul Jensen3d194ea2015-06-16 14:27:36 -04004869 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004870 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004871 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004872 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004873 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004874 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004875 }
Paul Jensene0988542015-06-25 15:30:08 -04004876 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004877 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004878 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004879 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004880 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004881 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004882 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004883 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004884 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004885 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004886 if (nai.isSuspended()) {
4887 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4888 } else {
4889 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4890 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004891
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004892 return newNc;
4893 }
4894
4895 /**
4896 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4897 *
4898 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4899 * capabilities we manage and store in {@code nai}, such as validated status and captive
4900 * portal status)
4901 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4902 * potentially triggers rematches.
4903 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4904 * change.)
4905 *
4906 * @param oldScore score of the network before any of the changes that prompted us
4907 * to call this function.
4908 * @param nai the network having its capabilities updated.
4909 * @param nc the new network capabilities.
4910 */
4911 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4912 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4913
4914 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004915
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004916 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004917 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004918 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004919 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004920 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004921 } catch (RemoteException e) {
4922 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004923 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004924 }
4925
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004926 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004927 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004928 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004929 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004930 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004931
Chalard Jeanf213ca12018-01-16 18:43:05 +09004932 updateUids(nai, prevNc, newNc);
4933
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004934 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004935 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4936 // the change we're processing can't affect any requests, it can only affect the listens
4937 // on this network. We might have been called by rematchNetworkAndRequests when a
4938 // network changed foreground state.
4939 processListenRequests(nai, true);
4940 } else {
4941 // If the requestable capabilities have changed or the score changed, we can't have been
4942 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004943 rematchAllNetworksAndRequests(nai, oldScore);
4944 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004945 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004946
4947 // Report changes that are interesting for network statistics tracking.
4948 if (prevNc != null) {
4949 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004950 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004951 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004952 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004953 if (meteredChanged || roamingChanged) {
4954 notifyIfacesChangedForNetworkStats();
4955 }
4956 }
4957
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004958 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004959 // Tell VPNs about updated capabilities, since they may need to
4960 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09004961 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004962 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004963 }
4964
Chalard Jeanf213ca12018-01-16 18:43:05 +09004965 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4966 NetworkCapabilities newNc) {
4967 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4968 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4969 if (null == prevRanges) prevRanges = new ArraySet<>();
4970 if (null == newRanges) newRanges = new ArraySet<>();
4971 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4972
4973 prevRanges.removeAll(newRanges);
4974 newRanges.removeAll(prevRangesCopy);
4975
4976 try {
4977 if (!newRanges.isEmpty()) {
4978 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4979 newRanges.toArray(addedRangesArray);
4980 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4981 }
4982 if (!prevRanges.isEmpty()) {
4983 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4984 prevRanges.toArray(removedRangesArray);
4985 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4986 }
4987 } catch (Exception e) {
4988 // Never crash!
4989 loge("Exception in updateUids: " + e);
4990 }
4991 }
4992
Hugo Benichief502882017-09-01 01:23:32 +00004993 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Erik Kline79c6d052018-03-21 07:18:33 -07004994 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00004995 // Ignore updates for disconnected networks
4996 return;
4997 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004998 // newLp is already a defensive copy.
4999 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00005000 if (VDBG) {
5001 log("Update of LinkProperties for " + nai.name() +
5002 "; created=" + nai.created +
5003 "; everConnected=" + nai.everConnected);
5004 }
5005 LinkProperties oldLp = nai.linkProperties;
5006 synchronized (nai) {
5007 nai.linkProperties = newLp;
5008 }
5009 if (nai.everConnected) {
5010 updateLinkProperties(nai, oldLp);
5011 }
5012 }
5013
Paul Jensenc8b9a742014-09-30 15:37:41 -04005014 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005015 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5016 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005017 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005018 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04005019 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
5020 }
5021 }
5022
Robert Greenwalt7b816022014-04-18 15:25:25 -07005023 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
5024 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07005025 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07005026 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
5027 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005028 }
5029 }
5030
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005031 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5032 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005033 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005034 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005035 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5036 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005037 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005038 sendIntent(nri.mPendingIntent, intent);
5039 }
5040 // else not handled
5041 }
5042
5043 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5044 mPendingIntentWakeLock.acquire();
5045 try {
5046 if (DBG) log("Sending " + pendingIntent);
5047 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5048 } catch (PendingIntent.CanceledException e) {
5049 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5050 mPendingIntentWakeLock.release();
5051 releasePendingNetworkRequest(pendingIntent);
5052 }
5053 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5054 }
5055
5056 @Override
5057 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5058 String resultData, Bundle resultExtras) {
5059 if (DBG) log("Finished sending " + pendingIntent);
5060 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005061 // Release with a delay so the receiving client has an opportunity to put in its
5062 // own request.
5063 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005064 }
5065
Chalard Jeanf19db372018-01-26 19:24:40 +09005066 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005067 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005068 if (nri.messenger == null) {
5069 return; // Default request has no msgr
5070 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005071 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005072 // TODO: check if defensive copies of data is needed.
5073 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005074 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005075 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5076 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005077 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005078 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005079 case ConnectivityManager.CALLBACK_AVAILABLE: {
5080 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
5081 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
5082 break;
5083 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005084 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005085 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005086 break;
5087 }
5088 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005089 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005090 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005091 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005092 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005093 break;
5094 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005095 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005096 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005097 break;
5098 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005099 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005100 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005101 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005102 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005103 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005104 String notification = ConnectivityManager.getCallbackName(notificationType);
5105 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005106 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005107 nri.messenger.send(msg);
5108 } catch (RemoteException e) {
5109 // may occur naturally in the race of binder death.
5110 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5111 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005112 }
5113
Hugo Benichidba33db2017-03-23 22:40:44 +09005114 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5115 bundle.putParcelable(t.getClass().getSimpleName(), t);
5116 }
5117
Paul Jensenc8b9a742014-09-30 15:37:41 -04005118 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005119 if (nai.numRequestNetworkRequests() != 0) {
5120 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5121 NetworkRequest nr = nai.requestAt(i);
5122 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005123 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005124 loge("Dead network still had at least " + nr);
5125 break;
5126 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005127 }
5128 nai.asyncChannel.disconnect();
5129 }
5130
Robert Greenwalt7b816022014-04-18 15:25:25 -07005131 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5132 if (oldNetwork == null) {
5133 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5134 return;
5135 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005136 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005137
5138 // If we get here it means that the last linger timeout for this network expired. So there
5139 // must be no other active linger timers, and we must stop lingering.
5140 oldNetwork.clearLingerState();
5141
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005142 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005143 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005144 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005145 } else {
5146 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005147 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5148 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005149 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005150 }
5151
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005152 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005153 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005154 setupDataActivityTracking(newNetwork);
5155 try {
5156 mNetd.setDefaultNetId(newNetwork.network.netId);
5157 } catch (Exception e) {
5158 loge("Exception setting default network :" + e);
5159 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005160
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005161 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005162 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005163 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005164 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005165 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005166 }
5167
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005168 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005169 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5170 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5171 NetworkRequest nr = nri.request;
5172 if (!nr.isListen()) continue;
5173 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5174 nai.removeRequest(nri.request.requestId);
5175 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5176 }
5177 }
5178
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005179 if (capabilitiesChanged) {
5180 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5181 }
5182
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005183 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5184 NetworkRequest nr = nri.request;
5185 if (!nr.isListen()) continue;
5186 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5187 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005188 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005189 }
5190 }
5191 }
5192
Paul Jensen2161a8e2014-09-11 11:00:39 -04005193 // Handles a network appearing or improving its score.
5194 //
5195 // - Evaluates all current NetworkRequests that can be
5196 // satisfied by newNetwork, and reassigns to newNetwork
5197 // any such requests for which newNetwork is the best.
5198 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005199 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005200 // needed. A network is needed if it is the best network for
5201 // one or more NetworkRequests, or if it is a VPN.
5202 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005203 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005204 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005205 //
5206 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5207 // networks that have no chance (i.e. even if validated)
5208 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005209 //
5210 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5211 // it does not remove NetworkRequests that other Networks could better satisfy.
5212 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5213 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5214 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005215 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005216 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005217 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5218 // performed to tear down unvalidated networks that have no chance (i.e. even if
5219 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005220 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005221 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005222 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005223 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005224 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005225 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005226
5227 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5228 final int score = newNetwork.getCurrentScore();
5229
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005230 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005231
Paul Jensen2161a8e2014-09-11 11:00:39 -04005232 // Find and migrate to this Network any NetworkRequests for
5233 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07005234 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04005235 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005236 NetworkCapabilities nc = newNetwork.networkCapabilities;
5237 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005238 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005239 // Process requests in the first pass and listens in the second pass. This allows us to
5240 // change a network's capabilities depending on which requests it has. This is only
5241 // correct if the change in capabilities doesn't affect whether the network satisfies
5242 // requests or not, and doesn't affect the network's score.
5243 if (nri.request.isListen()) continue;
5244
Hugo Benichicd952782017-09-20 11:20:14 +09005245 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005246 final boolean satisfies = newNetwork.satisfies(nri.request);
5247 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005248 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005249 log("Network " + newNetwork.name() + " was already satisfying" +
5250 " request " + nri.request.requestId + ". No change.");
5251 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005252 keep = true;
5253 continue;
5254 }
5255
5256 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005257 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005258 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005259 // next check if it's better than any current network we're using for
5260 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005261 if (VDBG) {
5262 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005263 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005264 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005265 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005266 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005267 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005268 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005269 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005270 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005271 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005272 affectedNetworks.add(currentNetwork);
5273 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005274 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005275 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005276 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005277 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005278 if (!newNetwork.addRequest(nri.request)) {
5279 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5280 }
5281 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005282 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005283 // Tell NetworkFactories about the new score, so they can stop
5284 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005285 // TODO - this could get expensive if we have alot of requests for this
5286 // network. Think about if there is a way to reduce this. Push
5287 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005288 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005289 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005290 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005291 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005292 if (currentNetwork != null) {
5293 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5294 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005295 }
5296 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005297 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005298 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5299 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005300 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005301 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5302 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5303 // This means this code doesn't have to handle the case where "currentNetwork" no
5304 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5305 if (DBG) {
5306 log("Network " + newNetwork.name() + " stopped satisfying" +
5307 " request " + nri.request.requestId);
5308 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005309 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005310 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005311 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005312 sendUpdatedScoreToFactories(nri.request, 0);
5313 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005314 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5315 newNetwork.name() +
5316 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005317 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005318 // TODO: Technically, sending CALLBACK_LOST here is
5319 // incorrect if there is a replacement network currently
5320 // connected that can satisfy nri, which is a request
5321 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005322 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5323 // so this code is only incorrect for a network that loses
5324 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005325 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005326 }
5327 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005328 if (isNewDefault) {
5329 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005330 makeDefault(newNetwork);
5331 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005332 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005333 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005334 // Have a new default network, release the transition wakelock in
5335 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005336 }
5337
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005338 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5339 Slog.wtf(TAG, String.format(
5340 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005341 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005342 }
5343 if (newNetwork.getCurrentScore() != score) {
5344 Slog.wtf(TAG, String.format(
5345 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005346 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005347 }
5348
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005349 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005350 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5351 // If the network went from background to foreground or vice versa, we need to update
5352 // its foreground state. It is safe to do this after rematching the requests because
5353 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5354 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005355 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005356 } else {
5357 processListenRequests(newNetwork, false);
5358 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005359
Paul Jensencf4c2c62015-07-01 14:16:32 -04005360 // do this after the default net is switched, but
5361 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005362 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005363
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005364 // Linger any networks that are no longer needed. This should be done after sending the
5365 // available callback for newNetwork.
5366 for (NetworkAgentInfo nai : affectedNetworks) {
5367 updateLingerState(nai, now);
5368 }
5369 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5370 // does not need to be done in any particular order.
5371 updateLingerState(newNetwork, now);
5372
Paul Jensencf4c2c62015-07-01 14:16:32 -04005373 if (isNewDefault) {
5374 // Maintain the illusion: since the legacy API only
5375 // understands one network at a time, we must pretend
5376 // that the current default network disconnected before
5377 // the new one connected.
5378 if (oldDefaultNetwork != null) {
5379 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5380 oldDefaultNetwork, true);
5381 }
5382 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5383 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5384 notifyLockdownVpn(newNetwork);
5385 }
5386
Robert Greenwalt7b816022014-04-18 15:25:25 -07005387 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005388 // Notify battery stats service about this network, both the normal
5389 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005390 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005391 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005392 final IBatteryStats bs = BatteryStatsService.getService();
5393 final int type = newNetwork.networkInfo.getType();
5394
5395 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5396 bs.noteNetworkInterfaceType(baseIface, type);
5397 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5398 final String stackedIface = stacked.getInterfaceName();
5399 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005400 }
5401 } catch (RemoteException ignored) {
5402 }
5403
Robert Greenwalt152ed372014-12-17 17:19:53 -08005404 // This has to happen after the notifyNetworkCallbacks as that tickles each
5405 // ConnectivityManager instance so that legacy requests correctly bind dns
5406 // requests to this network. The legacy users are listening for this bcast
5407 // and will generally do a dns request so they can ensureRouteToHost and if
5408 // they do that before the callbacks happen they'll use the default network.
5409 //
5410 // TODO: Is there still a race here? We send the broadcast
5411 // after sending the callback, but if the app can receive the
5412 // broadcast before the callback, it might still break.
5413 //
5414 // This *does* introduce a race where if the user uses the new api
5415 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5416 // they may get old info. Reverse this after the old startUsing api is removed.
5417 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005418 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5419 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005420 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005421 // legacy type tracker filters out repeat adds
5422 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5423 }
5424 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005425
5426 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5427 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5428 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5429 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5430 if (newNetwork.isVPN()) {
5431 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5432 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005433 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005434 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5435 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005436 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005437 if (nai.getLingerExpiry() > 0) {
5438 // This network has active linger timers and no requests, but is not
5439 // lingering. Linger it.
5440 //
5441 // One way (the only way?) this can happen if this network is unvalidated
5442 // and became unneeded due to another network improving its score to the
5443 // point where this network will no longer be able to satisfy any requests
5444 // even if it validates.
5445 updateLingerState(nai, now);
5446 } else {
5447 if (DBG) log("Reaping " + nai.name());
5448 teardownUnneededNetwork(nai);
5449 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005450 }
5451 }
5452 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005453 }
5454
Paul Jensen1c7ba022015-06-16 14:27:36 -04005455 /**
5456 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5457 * being disconnected.
5458 * @param changed If only one Network's score or capabilities have been modified since the last
5459 * time this function was called, pass this Network in this argument, otherwise pass
5460 * null.
5461 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5462 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5463 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5464 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5465 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005466 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005467 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005468 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5469 // to avoid the slowness. It is not simply enough to process just "changed", for
5470 // example in the case where "changed"'s score decreases and another network should begin
5471 // satifying a NetworkRequest that "changed" currently satisfies.
5472
5473 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5474 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5475 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005476 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005477 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005478 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005479 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005480 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5481 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5482 // Rematch higher scoring networks first to prevent requests first matching a lower
5483 // scoring network and then a higher scoring network, which could produce multiple
5484 // callbacks and inadvertently unlinger networks.
5485 Arrays.sort(nais);
5486 for (NetworkAgentInfo nai : nais) {
5487 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005488 // Only reap the last time through the loop. Reaping before all rematching
5489 // is complete could incorrectly teardown a network that hasn't yet been
5490 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005491 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005492 : ReapUnvalidatedNetworks.REAP,
5493 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005494 }
5495 }
5496 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005497
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005498 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005499 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005500 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005501 // For now only update icons for default connection.
5502 // TODO: Update WiFi and cellular icons separately. b/17237507
5503 if (!isDefaultNetwork(nai)) return;
5504
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005505 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005506 // Don't repeat publish.
5507 if (newInetCondition == mDefaultInetConditionPublished) return;
5508
5509 mDefaultInetConditionPublished = newInetCondition;
5510 sendInetConditionBroadcast(nai.networkInfo);
5511 }
5512
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005513 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005514 synchronized (mVpns) {
5515 if (mLockdownTracker != null) {
5516 if (nai != null && nai.isVPN()) {
5517 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5518 } else {
5519 mLockdownTracker.onNetworkInfoChanged();
5520 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005521 }
5522 }
5523 }
5524
Robert Greenwalt7b816022014-04-18 15:25:25 -07005525 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005526 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005527 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005528 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005529 synchronized (networkAgent) {
5530 oldInfo = networkAgent.networkInfo;
5531 networkAgent.networkInfo = newInfo;
5532 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005533 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005534
Robert Greenwalt7b816022014-04-18 15:25:25 -07005535 if (DBG) {
5536 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5537 (oldInfo == null ? "null" : oldInfo.getState()) +
5538 " to " + state);
5539 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005540
Robin Lee585e2482016-05-01 23:00:00 +01005541 if (!networkAgent.created
5542 && (state == NetworkInfo.State.CONNECTED
5543 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005544
5545 // A network that has just connected has zero requests and is thus a foreground network.
5546 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5547
Robert Greenwalt7b816022014-04-18 15:25:25 -07005548 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005549 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005550 if (networkAgent.isVPN()) {
5551 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005552 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5553 (networkAgent.networkMisc == null ||
5554 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005555 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005556 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005557 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005558 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005559 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005560 loge("Error creating network " + networkAgent.network.netId + ": "
5561 + e.getMessage());
5562 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005563 }
Paul Jenseneec75412014-08-04 12:21:19 -04005564 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005565 }
5566
5567 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5568 networkAgent.everConnected = true;
5569
Erik Kline79c6d052018-03-21 07:18:33 -07005570 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005571 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005572 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005573
Paul Jensenca8f16a2014-05-09 12:47:55 -04005574 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005575 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005576
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005577 if (networkAgent.isVPN()) {
5578 // Temporarily disable the default proxy (not global).
5579 synchronized (mProxyLock) {
5580 if (!mDefaultProxyDisabled) {
5581 mDefaultProxyDisabled = true;
5582 if (mGlobalProxy == null && mDefaultProxy != null) {
5583 sendProxyBroadcast(null);
5584 }
5585 }
5586 }
5587 // TODO: support proxy per network.
5588 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005589
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005590 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5591 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5592 // capabilities, so it only needs to be done once on initial connect, not every time the
5593 // network's capabilities change. Note that we do this before rematching the network,
5594 // so we could decide to tear it down immediately afterwards. That's fine though - on
5595 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5596 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005597 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005598
Paul Jensen2161a8e2014-09-11 11:00:39 -04005599 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005600 final long now = SystemClock.elapsedRealtime();
5601 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005602
5603 // This has to happen after matching the requests, because callbacks are just requests.
5604 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005605 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005606 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005607 if (networkAgent.isVPN()) {
5608 synchronized (mProxyLock) {
5609 if (mDefaultProxyDisabled) {
5610 mDefaultProxyDisabled = false;
5611 if (mGlobalProxy == null && mDefaultProxy != null) {
5612 sendProxyBroadcast(mDefaultProxy);
5613 }
5614 }
5615 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005616 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005617 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005618 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5619 state == NetworkInfo.State.SUSPENDED) {
5620 // going into or coming out of SUSPEND: rescore and notify
5621 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005622 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005623 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005624 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5625 networkAgent.networkCapabilities);
5626 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5627 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005628 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5629 ConnectivityManager.CALLBACK_SUSPENDED :
5630 ConnectivityManager.CALLBACK_RESUMED));
5631 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005632 }
5633 }
5634
Robert Greenwaltac96c522014-06-03 16:43:57 -07005635 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005636 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005637 if (score < 0) {
5638 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5639 "). Bumping score to min of 0");
5640 score = 0;
5641 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005642
Paul Jensen2161a8e2014-09-11 11:00:39 -04005643 final int oldScore = nai.getCurrentScore();
5644 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005645
Paul Jensen85cf78e2015-06-25 13:25:07 -04005646 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005647
Paul Jensenc8b9a742014-09-30 15:37:41 -04005648 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005649 }
5650
Erik Klinec75d4fa2017-02-15 19:59:17 +09005651 // Notify only this one new request of the current state. Transfer all the
5652 // current state by calling NetworkCapabilities and LinkProperties callbacks
5653 // so that callers can be guaranteed to have as close to atomicity in state
5654 // transfer as can be supported by this current API.
5655 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005656 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005657 if (nri.mPendingIntent != null) {
5658 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5659 // Attempt no subsequent state pushes where intents are involved.
5660 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005661 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005662
5663 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005664 }
5665
Robert Greenwalt8d482522015-06-24 13:23:42 -07005666 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005667 // The NetworkInfo we actually send out has no bearing on the real
5668 // state of affairs. For example, if the default connection is mobile,
5669 // and a request for HIPRI has just gone away, we need to pretend that
5670 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5671 // the state to DISCONNECTED, even though the network is of type MOBILE
5672 // and is still connected.
5673 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5674 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005675 if (state != DetailedState.DISCONNECTED) {
5676 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005677 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005678 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005679 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005680 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5681 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5682 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5683 if (info.isFailover()) {
5684 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5685 nai.networkInfo.setFailover(false);
5686 }
5687 if (info.getReason() != null) {
5688 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5689 }
5690 if (info.getExtraInfo() != null) {
5691 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5692 }
5693 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005694 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005695 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005696 if (newDefaultAgent != null) {
5697 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5698 newDefaultAgent.networkInfo);
5699 } else {
5700 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5701 }
5702 }
5703 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5704 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005705 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005706 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005707 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005708 }
5709 }
5710 }
5711
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005712 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005713 if (VDBG) {
5714 String notification = ConnectivityManager.getCallbackName(notifyType);
5715 log("notifyType " + notification + " for " + networkAgent.name());
5716 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005717 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5718 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005719 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5720 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005721 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5722 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005723 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005724 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005725 } else {
5726 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5727 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005728 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005729 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005730
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005731 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5732 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5733 }
5734
Jeff Sharkey69736342014-12-08 14:50:12 -08005735 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005736 * Returns the list of all interfaces that could be used by network traffic that does not
5737 * explicitly specify a network. This includes the default network, but also all VPNs that are
5738 * currently connected.
5739 *
5740 * Must be called on the handler thread.
5741 */
5742 private Network[] getDefaultNetworks() {
5743 ArrayList<Network> defaultNetworks = new ArrayList<>();
5744 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5745 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5746 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5747 defaultNetworks.add(nai.network);
5748 }
5749 }
5750 return defaultNetworks.toArray(new Network[0]);
5751 }
5752
5753 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005754 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5755 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005756 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005757 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005758 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005759 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005760 } catch (Exception ignored) {
5761 }
5762 }
5763
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005764 @Override
5765 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005766 int user = UserHandle.getUserId(Binder.getCallingUid());
5767 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005768 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005769 return mVpns.get(user).addAddress(address, prefixLength);
5770 }
5771 }
5772
5773 @Override
5774 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005775 int user = UserHandle.getUserId(Binder.getCallingUid());
5776 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005777 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005778 return mVpns.get(user).removeAddress(address, prefixLength);
5779 }
5780 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005781
5782 @Override
5783 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005784 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005785 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005786 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005787 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005788 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005789 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005790 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005791 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005792 }
5793 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005794 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005795
5796 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005797 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07005798 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005799 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005800 }
5801
5802 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005803 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5804 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5805 enforceKeepalivePermission();
5806 mKeepaliveTracker.startNattKeepalive(
5807 getNetworkAgentInfoForNetwork(network),
5808 intervalSeconds, messenger, binder,
5809 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5810 }
5811
5812 @Override
5813 public void stopKeepalive(Network network, int slot) {
5814 mHandler.sendMessage(mHandler.obtainMessage(
5815 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5816 }
5817
5818 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005819 public void factoryReset() {
5820 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005821
5822 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5823 return;
5824 }
5825
Robin Lee3b3dd942015-05-12 18:14:58 +01005826 final int userId = UserHandle.getCallingUserId();
5827
Stuart Scottf1fb3972015-04-02 18:00:02 -07005828 // Turn airplane mode off
5829 setAirplaneMode(false);
5830
Stuart Scotte3e314d2015-04-20 14:07:45 -07005831 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5832 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005833 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005834 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005835 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005836 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005837 }
5838
Stuart Scotte3e314d2015-04-20 14:07:45 -07005839 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005840 // Remove always-on package
5841 synchronized (mVpns) {
5842 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5843 if (alwaysOnPackage != null) {
5844 setAlwaysOnVpnPackage(userId, null, false);
5845 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5846 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005847
Hugo Benichi69744342017-11-27 10:57:16 +09005848 // Turn Always-on VPN off
5849 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5850 final long ident = Binder.clearCallingIdentity();
5851 try {
5852 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5853 mLockdownEnabled = false;
5854 setLockdownTracker(null);
5855 } finally {
5856 Binder.restoreCallingIdentity(ident);
5857 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005858 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005859
Hugo Benichi69744342017-11-27 10:57:16 +09005860 // Turn VPN off
5861 VpnConfig vpnConfig = getVpnConfig(userId);
5862 if (vpnConfig != null) {
5863 if (vpnConfig.legacy) {
5864 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5865 } else {
5866 // Prevent this app (packagename = vpnConfig.user) from initiating
5867 // VPN connections in the future without user intervention.
5868 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005869
Hugo Benichi69744342017-11-27 10:57:16 +09005870 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5871 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005872 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005873 }
5874 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005875
5876 Settings.Global.putString(mContext.getContentResolver(),
5877 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005878 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005879
Ricky Wai44dcbde2018-01-23 04:09:45 +00005880 @Override
5881 public byte[] getNetworkWatchlistConfigHash() {
5882 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
5883 if (nwm == null) {
5884 loge("Unable to get NetworkWatchlistManager");
5885 return null;
5886 }
5887 // Redirect it to network watchlist service to access watchlist file and calculate hash.
5888 return nwm.getWatchlistConfigHash();
5889 }
5890
Paul Jensencf4c2c62015-07-01 14:16:32 -04005891 @VisibleForTesting
5892 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5893 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5894 return new NetworkMonitor(context, handler, nai, defaultRequest);
5895 }
Erik Kline48f12f22016-04-14 17:30:59 +09005896
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005897 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005898 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5899 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005900 }
5901
5902 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005903 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5904 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5905 }
5906
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005907 @VisibleForTesting
5908 public boolean hasService(String name) {
5909 return ServiceManager.checkService(name) != null;
5910 }
5911
Hugo Benichi64901e52017-10-19 14:42:40 +09005912 @VisibleForTesting
5913 protected IpConnectivityMetrics.Logger metricsLogger() {
5914 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5915 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005916 }
5917
5918 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005919 int[] transports = nai.networkCapabilities.getTransportTypes();
5920 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005921 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005922
5923 private static boolean toBool(int encodedBoolean) {
5924 return encodedBoolean != 0; // Only 0 means false.
5925 }
5926
5927 private static int encodeBool(boolean b) {
5928 return b ? 1 : 0;
5929 }
mswest46386886f2018-03-12 10:34:34 -07005930
5931 @Override
5932 public void onShellCommand(FileDescriptor in, FileDescriptor out,
5933 FileDescriptor err, String[] args, ShellCallback callback,
5934 ResultReceiver resultReceiver) {
5935 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
5936 }
5937
5938 private class ShellCmd extends ShellCommand {
5939
5940 @Override
5941 public int onCommand(String cmd) {
5942 if (cmd == null) {
5943 return handleDefaultCommands(cmd);
5944 }
5945 final PrintWriter pw = getOutPrintWriter();
5946 try {
5947 switch (cmd) {
5948 case "airplane-mode":
5949 final String action = getNextArg();
5950 if ("enable".equals(action)) {
5951 setAirplaneMode(true);
5952 return 0;
5953 } else if ("disable".equals(action)) {
5954 setAirplaneMode(false);
5955 return 0;
5956 } else if (action == null) {
5957 final ContentResolver cr = mContext.getContentResolver();
5958 final int enabled = Settings.Global.getInt(cr,
5959 Settings.Global.AIRPLANE_MODE_ON);
5960 pw.println(enabled == 0 ? "disabled" : "enabled");
5961 return 0;
5962 } else {
5963 onHelp();
5964 return -1;
5965 }
5966 default:
5967 return handleDefaultCommands(cmd);
5968 }
5969 } catch (Exception e) {
5970 pw.println(e);
5971 }
5972 return -1;
5973 }
5974
5975 @Override
5976 public void onHelp() {
5977 PrintWriter pw = getOutPrintWriter();
5978 pw.println("Connectivity service commands:");
5979 pw.println(" help");
5980 pw.println(" Print this help text.");
5981 pw.println(" airplane-mode [enable|disable]");
5982 pw.println(" Turn airplane mode on or off.");
5983 pw.println(" airplane-mode");
5984 pw.println(" Get airplane mode.");
5985 }
5986 }
Erik Kline79c6d052018-03-21 07:18:33 -07005987}