blob: 5afb0a622208da14e3187cd06ba48ce2700b5f42 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Chalard Jeanb552c462018-02-21 18:43:54 +090020import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey961e3042011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050022import static android.net.ConnectivityManager.NETID_UNSET;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090023import static android.net.ConnectivityManager.TYPE_ETHERNET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070024import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070025import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070026import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070027import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040028import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090029import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090030import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
32import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060033import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jean804b8fb2018-01-30 22:41:41 +090034import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
Chalard Jeandda156a2018-01-10 21:19:32 +090035import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090036import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060037import static android.net.NetworkCapabilities.TRANSPORT_VPN;
38
Hugo Benichia0385682017-03-22 17:07:57 +090039import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060040
Wenchao Tongf5ea3402015-03-04 13:26:38 -080041import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080042import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090043import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070044import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070045import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.ContentResolver;
47import android.content.Context;
48import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070049import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070050import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070051import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090053import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.net.IConnectivityManager;
dalyk1fcb7392018-03-05 12:42:22 -050055import android.net.IIpConnectivityMetrics;
56import android.net.INetdEventCallback;
Haoyu Baidb3c8672012-06-20 14:29:57 -070057import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070058import android.net.INetworkPolicyListener;
59import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070060import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080061import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070062import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010063import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070064import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070065import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070066import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070067import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070069import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070070import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090071import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070072import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070073import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070074import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070075import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070076import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +000077import android.net.NetworkWatchlistManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070078import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040079import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070080import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040081import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040082import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060083import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +090084import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090085import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090086import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080088import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070089import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040090import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070092import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070093import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070094import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.os.Looper;
96import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070097import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070098import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +090099import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700100import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -0700101import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700102import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800103import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900104import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900105import android.os.ServiceSpecificException;
mswest46386886f2018-03-12 10:34:34 -0700106import android.os.ShellCallback;
107import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900108import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700109import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400110import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700112import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700113import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700114import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700115import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900116import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700117import android.util.LocalLog;
118import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600119import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800120import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700121import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500122import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700123import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700124import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125
Wink Savilleab9321d2013-06-29 21:10:57 -0700126import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400127import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400128import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700129import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700130import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700131import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700132import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800133import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700134import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700135import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600136import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700137import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900138import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900139import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700140import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700141import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400142import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900143import com.android.server.connectivity.DnsManager;
Erik Klinea24d4592018-01-11 21:07:29 +0900144import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
dalyk1fcb7392018-03-05 12:42:22 -0500145import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900146import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900147import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100148import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700149import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900150import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700151import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600152import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400153import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900154import com.android.server.connectivity.NetworkNotificationManager;
155import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400156import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700157import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800158import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700159import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100160import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk1fcb7392018-03-05 12:42:22 -0500161import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700162import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700163import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900164import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700165import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600166
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700167import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700168
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700169import org.xmlpull.v1.XmlPullParser;
170import org.xmlpull.v1.XmlPullParserException;
171
172import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700174import java.io.FileNotFoundException;
175import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700176import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700178import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700179import java.net.InetAddress;
180import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700181import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700182import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700183import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700184import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700185import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700186import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700187import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700188import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700189import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900190import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600191import java.util.SortedSet;
192import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
194/**
195 * @hide
196 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800197public class ConnectivityService extends IConnectivityManager.Stub
198 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900199 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
Erik Kline7747fd42017-05-12 16:52:48 +0900201 public static final String DIAG_ARG = "--diag";
202 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900203 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900204
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900205 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700206 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207
Jake Hamby786e71a2014-02-06 14:43:50 -0800208 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900209 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700210
Jeff Sharkey899223b2012-08-04 15:24:58 -0700211 // TODO: create better separation between radio types and network types
212
Robert Greenwalt42acef32009-08-12 16:08:25 -0700213 // how long to wait before switching back to a radio's default network
214 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
215 // system property that can override the above value
216 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
217 "android.telephony.apn-restore";
218
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900219 // How long to wait before putting up a "This network doesn't have an Internet connection,
220 // connect anyway?" dialog after the user selects a network that doesn't validate.
221 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
222
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900223 // Default to 30s linger time-out. Modifiable only for testing.
224 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
225 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
226 @VisibleForTesting
227 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
228
Jeremy Joslin79294842014-12-03 17:15:28 -0800229 // How long to delay to removal of a pending intent based request.
230 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
231 private final int mReleasePendingIntentDelayMs;
232
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900233 private MockableSystemProperties mSystemProperties;
234
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800235 private Tethering mTethering;
236
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700237 private final PermissionMonitor mPermissionMonitor;
238
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700239 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700240
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700241 @GuardedBy("mVpns")
242 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700243
Hugo Benichi69744342017-11-27 10:57:16 +0900244 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
245 // a direct call to LockdownVpnTracker.isEnabled().
246 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700247 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900248 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700249 private LockdownVpnTracker mLockdownTracker;
250
Erik Klineda4bfa82015-04-30 12:58:40 +0900251 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700253 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700254 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700257 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700259 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800260 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700261 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900262 private NetworkPolicyManagerInternal mPolicyManagerInternal;
dalyk1fcb7392018-03-05 12:42:22 -0500263 private IIpConnectivityMetrics mIpConnectivityMetrics;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700264
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700265 private String mCurrentTcpBufferSizes;
266
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700267 private static final int ENABLED = 1;
268 private static final int DISABLED = 0;
269
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900270 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900271 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
272 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900273
Paul Jensenb10e37f2014-11-25 12:33:08 -0500274 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400275 // Tear down networks that have no chance (e.g. even if validated) of becoming
276 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500277 // all networks have been rematched against all NetworkRequests.
278 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400279 // Don't reap networks. This should be passed when some networks have not yet been
280 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500281 DONT_REAP
282 };
283
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900284 private enum UnneededFor {
285 LINGER, // Determine whether this network is unneeded and should be lingered.
286 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
287 }
288
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700289 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700290 * used internally to change our mobile data enabled flag
291 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700292 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700293
294 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700295 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700296 * from one net to another. Clear happens when we get a new
297 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
298 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700299 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700300 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700301
Robert Greenwalt434203a2010-10-11 16:00:27 -0700302 /**
303 * used internally to reload global proxy settings
304 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700305 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700306
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700307 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400308 * PAC manager has received new port.
309 */
310 private static final int EVENT_PROXY_HAS_CHANGED = 16;
311
Robert Greenwalte049c232014-04-11 15:53:27 -0700312 /**
313 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700314 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700315 */
316 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
317
Robert Greenwalt7b816022014-04-18 15:25:25 -0700318 /**
319 * used internally when registering NetworkAgents
320 * obj = Messenger
321 */
322 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
323
Robert Greenwalt9258c642014-03-26 16:47:06 -0700324 /**
325 * used to add a network request
326 * includes a NetworkRequestInfo
327 */
328 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
329
330 /**
331 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900332 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700333 * cancel it.
334 * includes a NetworkRequestInfo
335 */
336 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
337
338 /**
339 * used to add a network listener - no request
340 * includes a NetworkRequestInfo
341 */
342 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
343
344 /**
345 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400346 * arg1 = UID of caller
347 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700348 */
349 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
350
Robert Greenwalta67be032014-05-16 15:49:14 -0700351 /**
352 * used internally when registering NetworkFactories
353 * obj = Messenger
354 */
355 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
356
Robert Greenwalt27711812014-06-25 16:45:57 -0700357 /**
358 * used internally to expire a wakelock when transitioning
359 * from one net to another. Expire happens when we fail to find
360 * a new network (typically after 1 minute) -
361 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
362 * a replacement network.
363 */
364 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
365
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700366 /**
367 * Used internally to indicate the system is ready.
368 */
369 private static final int EVENT_SYSTEM_READY = 25;
370
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800371 /**
372 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400373 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800374 */
375 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
376
377 /**
378 * used to remove a pending intent and its associated network request.
379 * arg1 = UID of caller
380 * obj = PendingIntent
381 */
382 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
383
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900384 /**
385 * used to specify whether a network should be used even if unvalidated.
386 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
387 * arg2 = whether to remember this choice in the future (1 or 0)
388 * obj = network
389 */
390 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
391
392 /**
393 * used to ask the user to confirm a connection to an unvalidated network.
394 * obj = network
395 */
396 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700397
Erik Klineda4bfa82015-04-30 12:58:40 +0900398 /**
399 * used internally to (re)configure mobile data always-on settings.
400 */
401 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
402
Paul Jensen694f2b82015-06-17 14:15:39 -0400403 /**
404 * used to add a network listener with a pending intent
405 * obj = NetworkRequestInfo
406 */
407 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
408
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900409 /**
410 * used to specify whether a network should not be penalized when it becomes unvalidated.
411 */
412 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
413
414 /**
415 * used to trigger revalidation of a network.
416 */
417 private static final int EVENT_REVALIDATE_NETWORK = 36;
418
Erik Klinea24d4592018-01-11 21:07:29 +0900419 // Handle changes in Private DNS settings.
420 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
421
dalyk1fcb7392018-03-05 12:42:22 -0500422 // Handle private DNS validation status updates.
423 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
424
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900425 private static String eventName(int what) {
426 return sMagicDecoderRing.get(what, Integer.toString(what));
427 }
428
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900429 /** Handler thread used for both of the handlers below. */
430 @VisibleForTesting
431 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700432 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700433 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700434 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700435 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900436 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700437
Mike Lockwood0f79b542009-08-14 14:18:49 -0400438 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800439 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400440
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700441 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700442 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800443 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700444
Robert Greenwalt434203a2010-10-11 16:00:27 -0700445 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400446 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700447 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700448 private boolean mDefaultProxyDisabled = false;
449
Robert Greenwalt434203a2010-10-11 16:00:27 -0700450 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400451 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700452
Jason Monk602b2322013-07-03 17:04:33 -0400453 private PacManager mPacManager = null;
454
Erik Klineda4bfa82015-04-30 12:58:40 +0900455 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700456
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400457 private UserManager mUserManager;
458
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700459 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700460 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700461
Robert Greenwalt50393202011-06-21 17:26:14 -0700462 // the set of network types that can only be enabled by system/sig apps
463 List mProtectedNetworks;
464
John Spurlockbf991a82013-06-24 14:20:23 -0400465 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700466
Wink Savilleab9321d2013-06-29 21:10:57 -0700467 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400468
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900469 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900470 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900471 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900472
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700473 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800474 private static final int MIN_NET_ID = 100; // some reserved marks
475 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700476 private int mNextNetId = MIN_NET_ID;
477
Robert Greenwalt34524f02014-05-18 16:22:10 -0700478 // sequence number of NetworkRequests
479 private int mNextNetworkRequestId = 1;
480
Erik Kline7523eb32015-07-09 18:24:03 +0900481 // NetworkRequest activity String log entries.
482 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
483 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
484
Hugo Benichic2ae2872016-07-11 11:05:12 +0900485 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900486 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900487 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
488
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900489 private static final int MAX_WAKELOCK_LOGS = 20;
490 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900491 private int mTotalWakelockAcquisitions = 0;
492 private int mTotalWakelockReleases = 0;
493 private long mTotalWakelockDurationMs = 0;
494 private long mMaxWakelockDurationMs = 0;
495 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900496
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700497 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
498 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400499 private static class ValidationLog {
500 final Network mNetwork;
501 final String mNetworkExtraInfo;
502 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700503
Paul Jensen0808eb82016-06-03 13:51:21 -0400504 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
505 mNetwork = network;
506 mNetworkExtraInfo = networkExtraInfo;
507 mLog = log;
508 }
509 }
510 private final ArrayDeque<ValidationLog> mValidationLogs =
511 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
512
513 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900514 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700515 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
516 mValidationLogs.removeLast();
517 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400518 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700519 }
520 }
521
Hugo Benichif9fdf872016-07-28 17:53:06 +0900522 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900523
Erik Kline065ab6e2016-10-02 18:02:14 +0900524 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900525 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900526
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900527 @VisibleForTesting
528 final MultipathPolicyTracker mMultipathPolicyTracker;
529
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700530 /**
531 * Implements support for the legacy "one network per network type" model.
532 *
533 * We used to have a static array of NetworkStateTrackers, one for each
534 * network type, but that doesn't work any more now that we can have,
535 * for example, more that one wifi network. This class stores all the
536 * NetworkAgentInfo objects that support a given type, but the legacy
537 * API will only see the first one.
538 *
539 * It serves two main purposes:
540 *
541 * 1. Provide information about "the network for a given type" (since this
542 * API only supports one).
543 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
544 * the first network for a given type changes, or if the default network
545 * changes.
546 */
547 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900548
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900549 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900550 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900551
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700552 /**
553 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
554 * Each list holds references to all NetworkAgentInfos that are used to
555 * satisfy requests for that network type.
556 *
557 * This array is built out at startup such that an unsupported network
558 * doesn't get an ArrayList instance, making this a tristate:
559 * unsupported, supported but not active and active.
560 *
561 * The actual lists are populated when we scan the network types that
562 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900563 *
564 * Threading model:
565 * - addSupportedType() is only called in the constructor
566 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
567 * They are therefore not thread-safe with respect to each other.
568 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
569 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
570 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700571 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900572 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700573
574 public LegacyTypeTracker() {
575 mTypeLists = (ArrayList<NetworkAgentInfo>[])
576 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
577 }
578
579 public void addSupportedType(int type) {
580 if (mTypeLists[type] != null) {
581 throw new IllegalStateException(
582 "legacy list for type " + type + "already initialized");
583 }
584 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
585 }
586
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700587 public boolean isTypeSupported(int type) {
588 return isNetworkTypeValid(type) && mTypeLists[type] != null;
589 }
590
591 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900592 synchronized (mTypeLists) {
593 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
594 return mTypeLists[type].get(0);
595 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700596 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900597 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700598 }
599
Robert Greenwalt8d482522015-06-24 13:23:42 -0700600 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900601 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900602 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700603 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900604 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900605 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900606 }
607 }
608
609 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700610 public void add(int type, NetworkAgentInfo nai) {
611 if (!isTypeSupported(type)) {
612 return; // Invalid network type.
613 }
614 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
615
616 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
617 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700618 return;
619 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900620 synchronized (mTypeLists) {
621 list.add(nai);
622 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900623
624 // Send a broadcast if this is the first network of its type or if it's the default.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900625 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900626 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700627 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
628 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700629 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700630 }
631
Lorenzo Colittia793a672014-07-31 23:20:17 +0900632 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900633 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900634 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
635 if (list == null || list.isEmpty()) {
636 return;
637 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900638 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900639
Hugo Benichi78caa2582016-06-21 09:48:07 +0900640 synchronized (mTypeLists) {
641 if (!list.remove(nai)) {
642 return;
643 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900644 }
645
Robert Greenwalt8d482522015-06-24 13:23:42 -0700646 final DetailedState state = DetailedState.DISCONNECTED;
647
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900648 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700649 maybeLogBroadcast(nai, state, type, wasDefault);
650 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900651 }
652
653 if (!list.isEmpty() && wasFirstNetwork) {
654 if (DBG) log("Other network available for type " + type +
655 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900656 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700657 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
658 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900659 }
660 }
661
662 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900663 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
664 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700665 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900666 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700667 }
668 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700669
Robert Greenwalt8d482522015-06-24 13:23:42 -0700670 // send out another legacy broadcast - currently only used for suspend/unsuspend
671 // toggle
672 public void update(NetworkAgentInfo nai) {
673 final boolean isDefault = isDefaultNetwork(nai);
674 final DetailedState state = nai.networkInfo.getDetailedState();
675 for (int type = 0; type < mTypeLists.length; type++) {
676 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700677 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900678 final boolean isFirst = contains && (nai == list.get(0));
679 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700680 maybeLogBroadcast(nai, state, type, isDefault);
681 sendLegacyNetworkBroadcast(nai, state, type);
682 }
683 }
684 }
685
Lorenzo Colittia793a672014-07-31 23:20:17 +0900686 private String naiToString(NetworkAgentInfo nai) {
687 String name = (nai != null) ? nai.name() : "null";
688 String state = (nai.networkInfo != null) ?
689 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
690 "???/???";
691 return name + " " + state;
692 }
693
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700694 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900695 pw.println("mLegacyTypeTracker:");
696 pw.increaseIndent();
697 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700698 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900699 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700700 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900701 pw.println();
702 pw.println("Current state:");
703 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900704 synchronized (mTypeLists) {
705 for (int type = 0; type < mTypeLists.length; type++) {
706 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
707 for (NetworkAgentInfo nai : mTypeLists[type]) {
708 pw.println(type + " " + naiToString(nai));
709 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900710 }
711 }
712 pw.decreaseIndent();
713 pw.decreaseIndent();
714 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700715 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700716 }
717 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
718
Vishnu Nair5c010902017-10-26 10:08:50 -0700719 /**
720 * Helper class which parses out priority arguments and dumps sections according to their
721 * priority. If priority arguments are omitted, function calls the legacy dump command.
722 */
723 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
724 @Override
725 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
726 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
727 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
728 }
729
730 @Override
731 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
732 doDump(fd, pw, args, asProto);
733 }
734
735 @Override
736 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
737 doDump(fd, pw, args, asProto);
738 }
739 };
740
Jeff Sharkey899223b2012-08-04 15:24:58 -0700741 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700742 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900743 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
744 }
745
746 @VisibleForTesting
747 protected ConnectivityService(Context context, INetworkManagementService netManager,
748 INetworkStatsService statsService, INetworkPolicyManager policyManager,
749 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800750 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800751
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900752 mSystemProperties = getSystemProperties();
753
Hugo Benichif9fdf872016-07-28 17:53:06 +0900754 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900755 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900756 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900757 mNetworkRequests.put(mDefaultRequest, defaultNRI);
758 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900759
Chalard Jeandda156a2018-01-10 21:19:32 +0900760 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900761 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700762
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900763 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900764 mHandlerThread.start();
765 mHandler = new InternalHandler(mHandlerThread.getLooper());
766 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700767
Jeremy Joslin79294842014-12-03 17:15:28 -0800768 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
769 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
770
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900771 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900772
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700773 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700774 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800775 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700776 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900777 mPolicyManagerInternal = checkNotNull(
778 LocalServices.getService(NetworkPolicyManagerInternal.class),
779 "missing NetworkPolicyManagerInternal");
780
Jeff Sharkey82f85212012-08-24 11:17:25 -0700781 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700782 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700783
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700784 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900785 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700786 } catch (RemoteException e) {
787 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700788 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700789 }
790
791 final PowerManager powerManager = (PowerManager) context.getSystemService(
792 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700793 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
794 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
795 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800796 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700797
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700798 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700799
Wink Saville51f456f2013-04-23 14:26:51 -0700800 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900801 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700802 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700803 String[] naStrings = context.getResources().getStringArray(
804 com.android.internal.R.array.networkAttributes);
805 for (String naString : naStrings) {
806 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700807 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700808 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700809 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800810 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700811 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700812 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700813 }
Wink Saville51f456f2013-04-23 14:26:51 -0700814 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
815 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
816 n.type);
817 continue;
818 }
Wink Saville975c8482011-04-07 14:23:45 -0700819 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800820 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700821 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700822 continue;
823 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700824 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700825
Wink Saville975c8482011-04-07 14:23:45 -0700826 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700827 mNetworksDefined++;
828 } catch(Exception e) {
829 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700830 }
831 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700832
833 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
834 if (mNetConfigs[TYPE_VPN] == null) {
835 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
836 // don't need to add TYPE_VPN to mNetConfigs.
837 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
838 mNetworksDefined++; // used only in the log() statement below.
839 }
840
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900841 // Do the same for Ethernet, since it's often not specified in the configs, although many
842 // devices can use it via USB host adapters.
843 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
844 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
845 mNetworksDefined++;
846 }
847
Wink Saville5e56bc52013-07-29 15:00:57 -0700848 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700849
Robert Greenwalt50393202011-06-21 17:26:14 -0700850 mProtectedNetworks = new ArrayList<Integer>();
851 int[] protectedNetworks = context.getResources().getIntArray(
852 com.android.internal.R.array.config_protectedNetworks);
853 for (int p : protectedNetworks) {
854 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
855 mProtectedNetworks.add(p);
856 } else {
857 if (DBG) loge("Ignoring protectedNetwork " + p);
858 }
859 }
860
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900861 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
862 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700863
Erik Kline47222fc2017-04-30 19:36:15 +0900864 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800865
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700866 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
867
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700868 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700869 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100870 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700871 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700872 intentFilter.addAction(Intent.ACTION_USER_ADDED);
873 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000874 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700875 mContext.registerReceiverAsUser(
876 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000877 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
878 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900879
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700880 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700881 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700882 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700883 } catch (RemoteException e) {
884 loge("Error registering observer :" + e);
885 }
886
Erik Klineda4bfa82015-04-30 12:58:40 +0900887 mSettingsObserver = new SettingsObserver(mContext, mHandler);
888 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800889
John Spurlockbf991a82013-06-24 14:20:23 -0400890 mDataConnectionStats = new DataConnectionStats(mContext);
891 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400892
Jason Monkdecd2952013-10-10 14:02:51 -0400893 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700894
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400895 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900896
897 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900898 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
899 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900900
901 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
902 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
903 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
904 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
905 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
906 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
907 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900908
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900909 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900910 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900911 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900912
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900913 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
914
Erik Kline1742fe12017-12-13 19:40:49 +0900915 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900916 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700918
Erik Kline47222fc2017-04-30 19:36:15 +0900919 private Tethering makeTethering() {
920 // TODO: Move other elements into @Overridden getters.
Erik Kline7a26ba32018-03-09 14:18:02 +0900921 final TetheringDependencies deps = new TetheringDependencies() {
922 @Override
923 public boolean isTetheringSupported() {
924 return ConnectivityService.this.isTetheringSupported();
925 }
926 };
Erik Kline47222fc2017-04-30 19:36:15 +0900927 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
928 IoThread.get().getLooper(), new MockableSystemProperties(),
929 deps);
930 }
931
Chalard Jeandda156a2018-01-10 21:19:32 +0900932 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900933 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900934 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900935 netCap.addCapability(NET_CAPABILITY_INTERNET);
936 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900937 if (transportType > -1) {
938 netCap.addTransportType(transportType);
939 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900940 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900941 }
942
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900943 // Used only for testing.
944 // TODO: Delete this and either:
Erik Kline79c6d052018-03-21 07:18:33 -0700945 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900946 // changing ContentResolver to make registerContentObserver non-final).
947 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
948 // by subclassing SettingsObserver.
949 @VisibleForTesting
950 void updateMobileDataAlwaysOn() {
951 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
952 }
953
Erik Kline79c6d052018-03-21 07:18:33 -0700954 // See FakeSettingsProvider comment above.
955 @VisibleForTesting
956 void updatePrivateDnsSettings() {
957 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
958 }
959
Erik Klineda4bfa82015-04-30 12:58:40 +0900960 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900961 final boolean enable = toBool(Settings.Global.getInt(
962 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900963 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
964 if (enable == isEnabled) {
965 return; // Nothing to do.
966 }
967
968 if (enable) {
969 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900970 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900971 } else {
972 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
973 }
974 }
975
976 private void registerSettingsCallbacks() {
977 // Watch for global HTTP proxy changes.
978 mSettingsObserver.observe(
979 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
980 EVENT_APPLY_GLOBAL_HTTP_PROXY);
981
982 // Watch for whether or not to keep mobile data always on.
983 mSettingsObserver.observe(
984 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
985 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
986 }
987
Erik Klinea24d4592018-01-11 21:07:29 +0900988 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline79c6d052018-03-21 07:18:33 -0700989 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
990 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +0900991 }
992 }
993
Robert Greenwalt34524f02014-05-18 16:22:10 -0700994 private synchronized int nextNetworkRequestId() {
995 return mNextNetworkRequestId++;
996 }
997
Paul Jensen67b0b072015-06-10 11:22:17 -0400998 @VisibleForTesting
999 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001000 synchronized (mNetworkForNetId) {
1001 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1002 int netId = mNextNetId;
1003 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1004 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001005 if (!mNetIdInUse.get(netId)) {
1006 mNetIdInUse.put(netId, true);
1007 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001008 }
1009 }
1010 }
1011 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001012 }
1013
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001014 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001015 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001016 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1017 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001018 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001019 state = nai.getNetworkState();
1020 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001021 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001022 final NetworkInfo info = new NetworkInfo(networkType, 0,
1023 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001024 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1025 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001026 final NetworkCapabilities capabilities = new NetworkCapabilities();
1027 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1028 !info.isRoaming());
1029 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001030 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001031 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001032 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001033 return state;
1034 } else {
1035 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001036 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001037 }
1038
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001039 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
1040 if (network == null) {
1041 return null;
1042 }
Erik Kline79c6d052018-03-21 07:18:33 -07001043 return getNetworkAgentInfoForNetId(network.netId);
1044 }
1045
1046 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001047 synchronized (mNetworkForNetId) {
Erik Kline79c6d052018-03-21 07:18:33 -07001048 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001049 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001050 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001051
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001052 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001053 synchronized (mVpns) {
1054 if (!mLockdownEnabled) {
1055 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001056 Vpn vpn = mVpns.get(user);
1057 if (vpn != null && vpn.appliesToUid(uid)) {
1058 return vpn.getUnderlyingNetworks();
1059 }
1060 }
1061 }
1062 return null;
1063 }
1064
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001065 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001066 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001067
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001068 final Network[] networks = getVpnUnderlyingNetworks(uid);
1069 if (networks != null) {
1070 // getUnderlyingNetworks() returns:
1071 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1072 // empty array => the VPN explicitly said "no default network".
1073 // non-empty array => the VPN specified one or more default networks; we use the
1074 // first one.
1075 if (networks.length > 0) {
1076 nai = getNetworkAgentInfoForNetwork(networks[0]);
1077 } else {
1078 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001079 }
1080 }
1081
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001082 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001083 return nai.getNetworkState();
1084 } else {
1085 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001086 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001087 }
1088
1089 /**
1090 * Check if UID should be blocked from using the network with the given LinkProperties.
1091 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001092 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1093 boolean ignoreBlocked) {
1094 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001095 if (ignoreBlocked) {
1096 return false;
1097 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001098 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001099 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1100 if (isSystem(uid)) {
1101 return false;
1102 }
Robin Lee17e61832016-05-09 13:46:28 +01001103 synchronized (mVpns) {
1104 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1105 if (vpn != null && vpn.isBlockingUid(uid)) {
1106 return true;
1107 }
1108 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001109 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001110 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001111 }
1112
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001113 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001114 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1115 return;
1116 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001117 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001118 synchronized (mBlockedAppUids) {
1119 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001120 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001121 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001122 blocked = false;
1123 } else {
1124 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001125 }
1126 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001127 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1128 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1129 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001130 }
1131
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001132 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001133 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1134 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001135 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001136 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001137 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001138 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1139
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001140 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001141 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001142 }
Hugo Benichi69744342017-11-27 10:57:16 +09001143 synchronized (mVpns) {
1144 if (mLockdownTracker != null) {
1145 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1146 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001147 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001148 }
1149
1150 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 * Return NetworkInfo for the active (i.e., connected) network interface.
1152 * It is assumed that at most one network is active at a time. If more
1153 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001154 * @return the info for the active network, or {@code null} if none is
1155 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001157 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001159 enforceAccessPermission();
1160 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001161 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001162 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001163 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1164 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 }
1166
Paul Jensen31a94f42015-02-13 14:18:39 -05001167 @Override
1168 public Network getActiveNetwork() {
1169 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001170 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001171 }
1172
1173 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001174 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001175 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001176 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001177 }
1178
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001179 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001180 final int user = UserHandle.getUserId(uid);
1181 int vpnNetId = NETID_UNSET;
1182 synchronized (mVpns) {
1183 final Vpn vpn = mVpns.get(user);
1184 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1185 }
1186 NetworkAgentInfo nai;
1187 if (vpnNetId != NETID_UNSET) {
Erik Kline79c6d052018-03-21 07:18:33 -07001188 nai = getNetworkAgentInfoForNetId(vpnNetId);
Paul Jensen31a94f42015-02-13 14:18:39 -05001189 if (nai != null) return nai.network;
1190 }
1191 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001192 if (nai != null
1193 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1194 nai = null;
1195 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001196 return nai != null ? nai.network : null;
1197 }
1198
Lorenzo Colitti18660282016-07-04 12:55:44 +09001199 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001200 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1201 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001202 final int uid = Binder.getCallingUid();
1203 NetworkState state = getUnfilteredActiveNetworkState(uid);
1204 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001205 }
1206
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001207 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001208 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001209 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001210 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001211 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001212 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001213 }
1214
1215 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 public NetworkInfo getNetworkInfo(int networkType) {
1217 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001218 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001219 if (getVpnUnderlyingNetworks(uid) != null) {
1220 // A VPN is active, so we may need to return one of its underlying networks. This
1221 // information is not available in LegacyTypeTracker, so we have to get it from
1222 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001223 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001224 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001225 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001226 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001227 }
1228 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001229 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001230 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 }
1232
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001233 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001234 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001235 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001236 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001237 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001238 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001239 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001240 return state.networkInfo;
1241 } else {
1242 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001243 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001244 }
1245
1246 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 public NetworkInfo[] getAllNetworkInfo() {
1248 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001249 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001250 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1251 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001252 NetworkInfo info = getNetworkInfo(networkType);
1253 if (info != null) {
1254 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001257 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 }
1259
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001260 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001261 public Network getNetworkForType(int networkType) {
1262 enforceAccessPermission();
1263 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001264 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1265 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001266 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001267 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001268 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001269 }
1270
1271 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001272 public Network[] getAllNetworks() {
1273 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001274 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001275 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001276 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001277 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001278 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001279 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001280 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001281 }
1282
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001283 @Override
1284 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1285 // The basic principle is: if an app's traffic could possibly go over a
1286 // network, without the app doing anything multinetwork-specific,
1287 // (hence, by "default"), then include that network's capabilities in
1288 // the array.
1289 //
1290 // In the normal case, app traffic only goes over the system's default
1291 // network connection, so that's the only network returned.
1292 //
1293 // With a VPN in force, some app traffic may go into the VPN, and thus
1294 // over whatever underlying networks the VPN specifies, while other app
1295 // traffic may go over the system default network (e.g.: a split-tunnel
1296 // VPN, or an app disallowed by the VPN), so the set of networks
1297 // returned includes the VPN's underlying networks and the system
1298 // default.
1299 enforceAccessPermission();
1300
1301 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1302
1303 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001304 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001305 if (nc != null) {
1306 result.put(nai.network, nc);
1307 }
1308
Hugo Benichi69744342017-11-27 10:57:16 +09001309 synchronized (mVpns) {
1310 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001311 Vpn vpn = mVpns.get(userId);
1312 if (vpn != null) {
1313 Network[] networks = vpn.getUnderlyingNetworks();
1314 if (networks != null) {
1315 for (Network network : networks) {
1316 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001317 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001318 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001319 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001320 }
1321 }
1322 }
1323 }
1324 }
1325 }
1326
1327 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1328 out = result.values().toArray(out);
1329 return out;
1330 }
1331
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001332 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001333 public boolean isNetworkSupported(int networkType) {
1334 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001335 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001336 }
1337
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001338 /**
1339 * Return LinkProperties for the active (i.e., connected) default
1340 * network interface. It is assumed that at most one default network
1341 * is active at a time. If more than one is active, it is indeterminate
1342 * which will be returned.
1343 * @return the ip properties for the active network, or {@code null} if
1344 * none is active
1345 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001346 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001347 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001348 enforceAccessPermission();
1349 final int uid = Binder.getCallingUid();
1350 NetworkState state = getUnfilteredActiveNetworkState(uid);
1351 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001352 }
1353
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001354 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001355 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001356 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001357 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1358 if (nai != null) {
1359 synchronized (nai) {
1360 return new LinkProperties(nai.linkProperties);
1361 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001362 }
1363 return null;
1364 }
1365
Robert Greenwalt12e67352014-05-13 21:41:06 -07001366 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001367 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001368 public LinkProperties getLinkProperties(Network network) {
1369 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001370 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1371 }
1372
1373 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1374 if (nai == null) {
1375 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001376 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001377 synchronized (nai) {
1378 return new LinkProperties(nai.linkProperties);
1379 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001380 }
1381
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001382 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001383 if (nai != null) {
1384 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001385 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001386 return networkCapabilitiesRestrictedForCallerPermissions(
1387 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001388 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001389 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001390 }
1391 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001392 return null;
1393 }
1394
1395 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001396 public NetworkCapabilities getNetworkCapabilities(Network network) {
1397 enforceAccessPermission();
1398 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1399 }
1400
Chalard Jeanb03a6222018-04-11 21:09:10 +09001401 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001402 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001403 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
1404 if (!checkSettingsPermission(callerPid, callerUid)) newNc.setUids(null);
Chalard Jeanb5120ca2018-04-16 12:25:22 +09001405 if (!checkSettingsPermission(callerPid, callerUid)) newNc.setSSID(null);
Chalard Jeanb03a6222018-04-11 21:09:10 +09001406 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001407 }
1408
Chalard Jeanb552c462018-02-21 18:43:54 +09001409 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1410 if (!checkSettingsPermission()) {
1411 nc.setSingleUid(Binder.getCallingUid());
1412 }
1413 }
1414
Chalard Jean26aa91a2018-03-20 19:13:57 +09001415 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1416 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1417 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1418 }
1419 }
1420
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001421 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001422 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001423 // Require internal since we're handing out IMSI details
1424 enforceConnectivityInternalPermission();
1425
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001426 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001427 for (Network network : getAllNetworks()) {
1428 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1429 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001430 // TODO (b/73321673) : NetworkState contains a copy of the
1431 // NetworkCapabilities, which may contain UIDs of apps to which the
1432 // network applies. Should the UIDs be cleared so as not to leak or
1433 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001434 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001435 }
1436 }
1437 return result.toArray(new NetworkState[result.size()]);
1438 }
1439
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001440 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001441 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001442 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001443 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1444 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1445 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001446 }
1447
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001448 @Override
1449 public boolean isActiveNetworkMetered() {
1450 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001451
Eric Enslenc81ef192018-02-07 18:03:53 -08001452 final int uid = Binder.getCallingUid();
1453 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001454 if (caps != null) {
1455 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1456 } else {
1457 // Always return the most conservative value
1458 return true;
1459 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001460 }
1461
Jeff Sharkey216c1812012-08-05 14:29:23 -07001462 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1463 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001464 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001465 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001466 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001467 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001468 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001469
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001470 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 * Ensure that a network route exists to deliver traffic to the specified
1472 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001473 * @param networkType the type of the network over which traffic to the
1474 * specified host is to be routed
1475 * @param hostAddress the IP address of the host to which the route is
1476 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 * @return {@code true} on success, {@code false} on failure
1478 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001479 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001480 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001482 if (mProtectedNetworks.contains(networkType)) {
1483 enforceConnectivityInternalPermission();
1484 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001485
Chad Brubakerc0234532014-02-14 13:24:29 -08001486 InetAddress addr;
1487 try {
1488 addr = InetAddress.getByAddress(hostAddress);
1489 } catch (UnknownHostException e) {
1490 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1491 return false;
1492 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001495 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 return false;
1497 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001498
1499 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1500 if (nai == null) {
1501 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1502 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1503 } else {
1504 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1505 }
1506 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001507 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001508
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001509 DetailedState netState;
1510 synchronized (nai) {
1511 netState = nai.networkInfo.getDetailedState();
1512 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001513
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001514 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001515 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001516 log("requestRouteToHostAddress on down network "
1517 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001518 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001519 }
1520 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001522
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001523 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001524 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001525 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001526 LinkProperties lp;
1527 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001528 synchronized (nai) {
1529 lp = nai.linkProperties;
1530 netId = nai.network.netId;
1531 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001532 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001533 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1534 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001535 } finally {
1536 Binder.restoreCallingIdentity(token);
1537 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001538 }
1539
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001540 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001541 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001542 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001543 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001544 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001545 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001546 if (bestRoute.getGateway().equals(addr)) {
1547 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001548 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001549 } else {
1550 // if we will connect to this through another route, add a direct route
1551 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001552 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001553 }
1554 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001555 if (DBG) log("Adding legacy route " + bestRoute +
1556 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001557 try {
1558 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1559 } catch (Exception e) {
1560 // never crash - catch them all
1561 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001562 return false;
1563 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001564 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 }
1566
dalyk1fcb7392018-03-05 12:42:22 -05001567 @VisibleForTesting
1568 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1569 @Override
1570 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1571 String hostname, boolean validated) {
1572 try {
1573 mHandler.sendMessage(mHandler.obtainMessage(
1574 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1575 new PrivateDnsValidationUpdate(netId,
1576 InetAddress.parseNumericAddress(ipAddress),
1577 hostname, validated)));
1578 } catch (IllegalArgumentException e) {
1579 loge("Error parsing ip address in validation event");
1580 }
1581 }
1582 };
1583
1584 @VisibleForTesting
1585 protected void registerNetdEventCallback() {
1586 mIpConnectivityMetrics =
1587 (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1588 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1589 if (mIpConnectivityMetrics == null) {
1590 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
1591 }
1592
1593 try {
1594 mIpConnectivityMetrics.addNetdEventCallback(
1595 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1596 mNetdEventCallback);
1597 } catch (Exception e) {
1598 loge("Error registering netd callback: " + e);
1599 }
1600 }
1601
Jeff Sharkey75d31892018-01-18 22:01:59 +09001602 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001603 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001604 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001605 // TODO: notify UID when it has requested targeted updates
1606 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001607 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001608 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001609 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001610 if (restrictBackground) {
1611 log("onRestrictBackgroundChanged(true): disabling tethering");
1612 mTethering.untetherAll();
1613 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001614 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001615 };
1616
Robin Lee3b3dd942015-05-12 18:14:58 +01001617 /**
1618 * Require that the caller is either in the same user or has appropriate permission to interact
1619 * across users.
1620 *
1621 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1622 */
1623 private void enforceCrossUserPermission(int userId) {
1624 if (userId == UserHandle.getCallingUserId()) {
1625 // Not a cross-user call.
1626 return;
1627 }
1628 mContext.enforceCallingOrSelfPermission(
1629 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1630 "ConnectivityService");
1631 }
1632
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001633 private void enforceInternetPermission() {
1634 mContext.enforceCallingOrSelfPermission(
1635 android.Manifest.permission.INTERNET,
1636 "ConnectivityService");
1637 }
1638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001640 mContext.enforceCallingOrSelfPermission(
1641 android.Manifest.permission.ACCESS_NETWORK_STATE,
1642 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 }
1644
1645 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001646 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 }
1648
Charles He36738632017-05-15 17:07:18 +01001649 private void enforceSettingsPermission() {
1650 mContext.enforceCallingOrSelfPermission(
1651 android.Manifest.permission.NETWORK_SETTINGS,
1652 "ConnectivityService");
1653 }
1654
Chalard Jeanb552c462018-02-21 18:43:54 +09001655 private boolean checkSettingsPermission() {
1656 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1657 android.Manifest.permission.NETWORK_SETTINGS);
1658 }
1659
1660 private boolean checkSettingsPermission(int pid, int uid) {
1661 return PERMISSION_GRANTED == mContext.checkPermission(
1662 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1663 }
1664
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001665 private void enforceTetherAccessPermission() {
1666 mContext.enforceCallingOrSelfPermission(
1667 android.Manifest.permission.ACCESS_NETWORK_STATE,
1668 "ConnectivityService");
1669 }
1670
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001671 private void enforceConnectivityInternalPermission() {
1672 mContext.enforceCallingOrSelfPermission(
1673 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1674 "ConnectivityService");
1675 }
1676
Hugo Benichi514da602016-07-19 15:59:27 +09001677 private void enforceConnectivityRestrictedNetworksPermission() {
1678 try {
1679 mContext.enforceCallingOrSelfPermission(
1680 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1681 "ConnectivityService");
1682 return;
1683 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1684 enforceConnectivityInternalPermission();
1685 }
1686
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001687 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001688 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001689 }
1690
Lorenzo Colitti18660282016-07-04 12:55:44 +09001691 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001692 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001693 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001694 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001695 }
1696
1697 private void sendInetConditionBroadcast(NetworkInfo info) {
1698 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1699 }
1700
Wink Saville628b0852011-08-04 15:01:58 -07001701 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001702 synchronized (mVpns) {
1703 if (mLockdownTracker != null) {
1704 info = new NetworkInfo(info);
1705 mLockdownTracker.augmentNetworkInfo(info);
1706 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001707 }
1708
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001709 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001710 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001711 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 if (info.isFailover()) {
1713 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1714 info.setFailover(false);
1715 }
1716 if (info.getReason() != null) {
1717 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1718 }
1719 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001720 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1721 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001723 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001724 return intent;
1725 }
1726
1727 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1728 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1729 }
1730
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001731 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001732 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1733 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1734 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001735 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001736 final long ident = Binder.clearCallingIdentity();
1737 try {
1738 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1739 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1740 } finally {
1741 Binder.restoreCallingIdentity(ident);
1742 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001743 }
1744
Mike Lockwood0f79b542009-08-14 14:18:49 -04001745 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001746 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001747 if (!mSystemReady) {
1748 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001749 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001750 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001751 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001752 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001753 }
1754
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001755 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001756 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001757 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001758 final NetworkInfo ni = intent.getParcelableExtra(
1759 ConnectivityManager.EXTRA_NETWORK_INFO);
1760 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1761 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1762 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001763 } else {
1764 BroadcastOptions opts = BroadcastOptions.makeBasic();
1765 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1766 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001767 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001768 final IBatteryStats bs = BatteryStatsService.getService();
1769 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001770 bs.noteConnectivityChanged(intent.getIntExtra(
1771 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1772 ni != null ? ni.getState().toString() : "?");
1773 } catch (RemoteException e) {
1774 }
Chad Brubakerac925012018-03-08 10:37:09 -08001775 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001776 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001777 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001778 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001779 } finally {
1780 Binder.restoreCallingIdentity(ident);
1781 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001782 }
1783 }
1784
1785 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001786 loadGlobalProxy();
dalyk1fcb7392018-03-05 12:42:22 -05001787 registerNetdEventCallback();
Wink Saville948282b2013-08-29 08:55:16 -07001788
Hugo Benichi20035e02017-04-26 14:53:28 +09001789 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001790 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001791 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001792 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001793 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001794 }
1795 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001796 // load the global proxy at startup
1797 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001798
Robin Lee244ce8e2016-01-05 18:03:46 +00001799 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1800 // for user to unlock device too.
1801 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001802
Erik Klineda4bfa82015-04-30 12:58:40 +09001803 // Configure whether mobile data is always on.
1804 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1805
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001806 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001807
1808 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
1810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001812 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001813 *
1814 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001815 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001816 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001817 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1818 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001819
1820 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001821 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001822
Robert Greenwalt7b816022014-04-18 15:25:25 -07001823 if (networkAgent.networkCapabilities.hasTransport(
1824 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001825 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1826 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001827 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001828 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001829 } else if (networkAgent.networkCapabilities.hasTransport(
1830 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001831 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1832 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001833 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001834 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001835 } else {
1836 // do not track any other networks
1837 timeout = 0;
1838 }
1839
Robert Greenwalt7b816022014-04-18 15:25:25 -07001840 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001841 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001842 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001843 } catch (Exception e) {
1844 // You shall not crash!
1845 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001846 }
1847 }
1848 }
1849
1850 /**
1851 * Remove data activity tracking when network disconnects.
1852 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001853 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1854 final String iface = networkAgent.linkProperties.getInterfaceName();
1855 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001856
Robert Greenwalt7b816022014-04-18 15:25:25 -07001857 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1858 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001859 try {
1860 // the call fails silently if no idletimer setup for this interface
1861 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001862 } catch (Exception e) {
1863 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001864 }
1865 }
1866 }
1867
1868 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001869 * Reads the network specific MTU size from reources.
1870 * and set it on it's iface.
1871 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001872 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1873 final String iface = newLp.getInterfaceName();
1874 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001875 if (oldLp == null && mtu == 0) {
1876 // Silently ignore unset MTU value.
1877 return;
1878 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001879 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1880 if (VDBG) log("identical MTU - not setting");
1881 return;
1882 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001883 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001884 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001885 return;
1886 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001887
w1997615afd812014-08-05 15:18:11 -07001888 // Cannot set MTU without interface name
1889 if (TextUtils.isEmpty(iface)) {
1890 loge("Setting MTU size with null iface.");
1891 return;
1892 }
1893
Robert Greenwalt7b816022014-04-18 15:25:25 -07001894 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001895 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001896 mNetd.setMtu(iface, mtu);
1897 } catch (Exception e) {
1898 Slog.e(TAG, "exception in setMtu()" + e);
1899 }
1900 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001901
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001902 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001903 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1904
1905 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001906 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001907 protected MockableSystemProperties getSystemProperties() {
1908 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001909 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001910
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001911 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1912 if (isDefaultNetwork(nai) == false) {
1913 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001914 }
1915
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001916 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1917 String[] values = null;
1918 if (tcpBufferSizes != null) {
1919 values = tcpBufferSizes.split(",");
1920 }
1921
1922 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001923 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001924 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1925 values = tcpBufferSizes.split(",");
1926 }
1927
1928 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1929
1930 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001931 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001932
1933 final String prefix = "/sys/kernel/ipv4/tcp_";
1934 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1935 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1936 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1937 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1938 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1939 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1940 mCurrentTcpBufferSizes = tcpBufferSizes;
1941 } catch (IOException e) {
1942 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001943 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001944
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001945 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001946 Settings.Global.TCP_DEFAULT_INIT_RWND,
1947 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001948 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1949 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001950 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001951 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001952 }
1953
Robert Greenwalt562cc542014-05-15 18:07:26 -07001954 @Override
1955 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001956 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001957 NETWORK_RESTORE_DELAY_PROP_NAME);
1958 if(restoreDefaultNetworkDelayStr != null &&
1959 restoreDefaultNetworkDelayStr.length() != 0) {
1960 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001961 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001962 } catch (NumberFormatException e) {
1963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001965 // if the system property isn't set, use the value for the apn type
1966 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1967
1968 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1969 (mNetConfigs[networkType] != null)) {
1970 ret = mNetConfigs[networkType].restoreTime;
1971 }
1972 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 }
1974
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001975 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001976 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001977 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001978 }
1979 return false;
1980 }
1981
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001982 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1983 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1984 final long DIAG_TIME_MS = 5000;
1985 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1986 // Start gathering diagnostic information.
1987 netDiags.add(new NetworkDiagnostics(
1988 nai.network,
1989 new LinkProperties(nai.linkProperties), // Must be a copy.
1990 DIAG_TIME_MS));
1991 }
1992
1993 for (NetworkDiagnostics netDiag : netDiags) {
1994 pw.println();
1995 netDiag.waitForMeasurements();
1996 netDiag.dump(pw);
1997 }
1998 }
1999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002001 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002002 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2003 }
2004
2005 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002006 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002007 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002008 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002009
Erik Kline7747fd42017-05-12 16:52:48 +09002010 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002011 dumpNetworkDiagnostics(pw);
2012 return;
Erik Klineee363c42017-05-29 09:11:03 +09002013 } else if (argsContain(args, TETHERING_ARG)) {
2014 mTethering.dump(fd, pw, args);
2015 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002016 }
Erik Kline379747a2015-06-05 17:47:34 +09002017
Lorenzo Colittie3805462015-06-03 11:18:24 +09002018 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002019 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002020 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002021 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002022 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002023 pw.println();
2024
Paul Jensen85cf78e2015-06-25 13:25:07 -04002025 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002026 pw.print("Active default network: ");
2027 if (defaultNai == null) {
2028 pw.println("none");
2029 } else {
2030 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002032 pw.println();
2033
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002034 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002035 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002036 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2037 pw.println(nai.toString());
2038 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002039 pw.println(String.format(
2040 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2041 nai.numForegroundNetworkRequests(),
2042 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2043 nai.numBackgroundNetworkRequests(),
2044 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002045 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002046 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2047 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002048 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002049 pw.decreaseIndent();
2050 pw.println("Lingered:");
2051 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002052 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002053 pw.decreaseIndent();
2054 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002055 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002056 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002057 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002058
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002059 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002060 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002061 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2062 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002063 }
2064 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002065 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002066
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002067 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002068
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002069 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002070 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002071
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002072 pw.println();
2073 mKeepaliveTracker.dump(pw);
2074
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002075 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002076 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002077
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002078 pw.println();
2079 mMultipathPolicyTracker.dump(pw);
2080
Erik Kline7747fd42017-05-12 16:52:48 +09002081 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002082 pw.println();
2083 synchronized (mValidationLogs) {
2084 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002085 for (ValidationLog p : mValidationLogs) {
2086 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002087 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002088 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002089 pw.decreaseIndent();
2090 }
2091 }
Erik Kline7523eb32015-07-09 18:24:03 +09002092
2093 pw.println();
2094 pw.println("mNetworkRequestInfoLogs (most recent first):");
2095 pw.increaseIndent();
2096 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2097 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002098
2099 pw.println();
2100 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2101 pw.increaseIndent();
2102 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2103 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002104
2105 pw.println();
2106 pw.println("NetTransition WakeLock activity (most recent first):");
2107 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002108 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2109 pw.println("total releases: " + mTotalWakelockReleases);
2110 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2111 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2112 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2113 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2114 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2115 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002116 mWakelockLogs.reverseDump(fd, pw, args);
2117 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 }
2120
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002121 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002122 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002123 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002124 if (officialNai != null && officialNai.equals(nai)) return true;
2125 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002126 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002127 " - " + nai);
2128 }
2129 return false;
2130 }
2131
Robert Greenwalt42acef32009-08-12 16:08:25 -07002132 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002133 private class NetworkStateTrackerHandler extends Handler {
2134 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002135 super(looper);
2136 }
2137
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002138 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002140 default:
2141 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002142 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002143 handleAsyncChannelHalfConnect(msg);
2144 break;
2145 }
2146 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2147 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2148 if (nai != null) nai.asyncChannel.disconnect();
2149 break;
2150 }
2151 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2152 handleAsyncChannelDisconnected(msg);
2153 break;
2154 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002155 }
2156 return true;
2157 }
2158
2159 private void maybeHandleNetworkAgentMessage(Message msg) {
2160 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2161 if (nai == null) {
2162 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002163 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002164 }
2165 return;
2166 }
2167
2168 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002169 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002170 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2171 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002172 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2173 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002174 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002175 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002176 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002177 break;
2178 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002179 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002180 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002181 break;
2182 }
2183 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002184 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002185 updateNetworkInfo(nai, info);
2186 break;
2187 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002188 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002189 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002190 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002191 break;
2192 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002193 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002194 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2195 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002196 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002197 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002198 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002199 break;
2200 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002201 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002202 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2203 break;
2204 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002205 }
2206 }
2207
2208 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2209 switch (msg.what) {
2210 default:
2211 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002212 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Erik Kline79c6d052018-03-21 07:18:33 -07002213 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002214 if (nai == null) break;
2215
2216 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2217 final boolean wasValidated = nai.lastValidated;
2218 final boolean wasDefault = isDefaultNetwork(nai);
2219
Erik Klinea24d4592018-01-11 21:07:29 +09002220 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2221
Erik Klinea24d4592018-01-11 21:07:29 +09002222 if (DBG) {
Erik Kline79c6d052018-03-21 07:18:33 -07002223 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2224 ? " with redirect to " + redirectUrl
2225 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002226 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2227 }
Erik Klinea24d4592018-01-11 21:07:29 +09002228 if (valid != nai.lastValidated) {
2229 if (wasDefault) {
2230 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2231 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002232 }
Erik Klinea24d4592018-01-11 21:07:29 +09002233 final int oldScore = nai.getCurrentScore();
2234 nai.lastValidated = valid;
2235 nai.everValidated |= valid;
2236 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2237 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2238 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2239 }
2240 updateInetCondition(nai);
2241 // Let the NetworkAgent know the state of its network
2242 Bundle redirectUrlBundle = new Bundle();
2243 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2244 nai.asyncChannel.sendMessage(
2245 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2246 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2247 0, redirectUrlBundle);
2248 if (wasValidated && !nai.lastValidated) {
2249 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002250 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002251 break;
2252 }
Paul Jensen869868be2014-05-15 10:33:05 -04002253 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002254 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002255 final boolean visible = toBool(msg.arg1);
Erik Kline79c6d052018-03-21 07:18:33 -07002256 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002257 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002258 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002259 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002260 nai.lastCaptivePortalDetected = visible;
2261 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002262 if (nai.lastCaptivePortalDetected &&
2263 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2264 if (DBG) log("Avoiding captive portal network: " + nai.name());
2265 nai.asyncChannel.sendMessage(
2266 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2267 teardownUnneededNetwork(nai);
2268 break;
2269 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002270 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002271 }
2272 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002273 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002274 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002275 if (nai == null) {
2276 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2277 break;
2278 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002279 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002280 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002281 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002282 }
Paul Jensen869868be2014-05-15 10:33:05 -04002283 }
Paul Jensen869868be2014-05-15 10:33:05 -04002284 break;
2285 }
Erik Klinea24d4592018-01-11 21:07:29 +09002286 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline79c6d052018-03-21 07:18:33 -07002287 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002288 if (nai == null) break;
2289
Erik Kline79c6d052018-03-21 07:18:33 -07002290 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002291 break;
2292 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002293 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002294 return true;
2295 }
2296
Calvin Onbe96da12016-10-11 15:10:46 -07002297 private int getCaptivePortalMode() {
2298 return Settings.Global.getInt(mContext.getContentResolver(),
2299 Settings.Global.CAPTIVE_PORTAL_MODE,
2300 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2301 }
2302
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002303 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2304 switch (msg.what) {
2305 default:
2306 return false;
2307 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2308 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2309 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2310 handleLingerComplete(nai);
2311 }
2312 break;
2313 }
2314 }
2315 return true;
2316 }
2317
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002318 @Override
2319 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002320 if (!maybeHandleAsyncChannelMessage(msg) &&
2321 !maybeHandleNetworkMonitorMessage(msg) &&
2322 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002323 maybeHandleNetworkAgentMessage(msg);
2324 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002325 }
2326 }
2327
Erik Kline79c6d052018-03-21 07:18:33 -07002328 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
2329 return NetworkMonitor.isValidationRequired(
2330 mDefaultRequest.networkCapabilities, nai.networkCapabilities);
2331 }
2332
Erik Klinea24d4592018-01-11 21:07:29 +09002333 private void handlePrivateDnsSettingsChanged() {
2334 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2335
2336 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline79c6d052018-03-21 07:18:33 -07002337 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk1fcb7392018-03-05 12:42:22 -05002338 if (networkRequiresValidation(nai)) {
2339 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2340 }
Erik Klinea24d4592018-01-11 21:07:29 +09002341 }
2342 }
2343
Erik Kline79c6d052018-03-21 07:18:33 -07002344 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2345 // Private DNS only ever applies to networks that might provide
2346 // Internet access and therefore also require validation.
2347 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002348
Erik Kline79c6d052018-03-21 07:18:33 -07002349 // Notify the NetworkMonitor thread in case it needs to cancel or
2350 // schedule DNS resolutions. If a DNS resolution is required the
2351 // result will be sent back to us.
2352 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2353
2354 // With Private DNS bypass support, we can proceed to update the
2355 // Private DNS config immediately, even if we're in strict mode
2356 // and have not yet resolved the provider name into a set of IPs.
2357 updatePrivateDns(nai, cfg);
2358 }
2359
2360 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2361 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002362 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002363 }
2364
dalyk1fcb7392018-03-05 12:42:22 -05002365 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2366 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2367 if (nai == null) {
2368 return;
2369 }
2370 mDnsManager.updatePrivateDnsValidation(update);
2371 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2372 }
2373
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002374 private void updateLingerState(NetworkAgentInfo nai, long now) {
2375 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2376 // 2. If the network was lingering and there are now requests, unlinger it.
2377 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2378 // one lingered request, start lingering.
2379 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002380 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002381 if (DBG) log("Unlingering " + nai.name());
2382 nai.unlinger();
2383 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002384 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002385 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002386 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002387 nai.linger();
2388 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2389 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2390 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002391 }
2392
Robert Greenwalt7b816022014-04-18 15:25:25 -07002393 private void handleAsyncChannelHalfConnect(Message msg) {
2394 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002395 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002396 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2397 if (VDBG) log("NetworkFactory connected");
2398 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002399 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002400 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002401 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002402 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002403 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002404 }
2405 } else {
2406 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002407 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002408 }
2409 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2410 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2411 if (VDBG) log("NetworkAgent connected");
2412 // A network agent has requested a connection. Establish the connection.
2413 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2414 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2415 } else {
2416 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002417 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002418 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002419 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002420 synchronized (mNetworkForNetId) {
2421 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002422 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002423 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002424 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002425 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002426 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002427 }
2428 }
2429 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002430
Robert Greenwalt7b816022014-04-18 15:25:25 -07002431 private void handleAsyncChannelDisconnected(Message msg) {
2432 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2433 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002434 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002435 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002436 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002437 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002438 // TODO - if we move the logic to the network agent (have them disconnect
2439 // because they lost all their requests or because their score isn't good)
2440 // then they would disconnect organically, report their new state and then
2441 // disconnect the channel.
2442 if (nai.networkInfo.isConnected()) {
2443 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2444 null, null);
2445 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002446 final boolean wasDefault = isDefaultNetwork(nai);
2447 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002448 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002449 // Log default network disconnection before required book-keeping.
2450 // Let rematchAllNetworksAndRequests() below record a new default network event
2451 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2452 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002453 long now = SystemClock.elapsedRealtime();
2454 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002455 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002456 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002457 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2458 // by other networks that are already connected. Perhaps that can be done by
2459 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2460 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002461 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002462 mKeepaliveTracker.handleStopAllKeepalives(nai,
2463 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002464 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2465 // Disable wakeup packet monitoring for each interface.
2466 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2467 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002468 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002469 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002470 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002471 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002472 // Remove the NetworkAgent, but don't mark the netId as
2473 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002474 mNetworkForNetId.remove(nai.network.netId);
2475 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002476 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002477 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2478 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002479 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002480 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002481 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002482 sendUpdatedScoreToFactories(request, 0);
2483 }
2484 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002485 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002486 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002487 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002488 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002489 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002490 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002491 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002492 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002493 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002494 if (nai.created) {
2495 // Tell netd to clean up the configuration for this network
2496 // (routing rules, DNS, etc).
2497 // This may be slow as it requires a lot of netd shelling out to ip and
2498 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2499 // after we've rematched networks with requests which should make a potential
2500 // fallback network the default or requested a new network from the
2501 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2502 // long time.
2503 try {
2504 mNetd.removeNetwork(nai.network.netId);
2505 } catch (Exception e) {
2506 loge("Exception removing network: " + e);
2507 }
Erik Klinea24d4592018-01-11 21:07:29 +09002508 mDnsManager.removeNetwork(nai.network);
Paul Jensen62d30802015-06-17 14:42:30 -04002509 }
2510 synchronized (mNetworkForNetId) {
2511 mNetIdInUse.delete(nai.network.netId);
2512 }
2513 } else {
2514 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2515 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002516 }
2517 }
2518
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002519 // If this method proves to be too slow then we can maintain a separate
2520 // pendingIntent => NetworkRequestInfo map.
2521 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2522 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2523 Intent intent = pendingIntent.getIntent();
2524 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2525 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2526 if (existingPendingIntent != null &&
2527 existingPendingIntent.getIntent().filterEquals(intent)) {
2528 return entry.getValue();
2529 }
2530 }
2531 return null;
2532 }
2533
2534 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2535 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2536
2537 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2538 if (existingRequest != null) { // remove the existing request.
2539 if (DBG) log("Replacing " + existingRequest.request + " with "
2540 + nri.request + " because their intents matched.");
2541 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2542 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002543 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002544 }
2545
Erik Klineda4bfa82015-04-30 12:58:40 +09002546 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002547 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002548 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002549 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002550 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002551 if (nri.request.networkCapabilities.hasSignalStrength() &&
2552 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2553 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002554 }
2555 }
2556 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002557 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002558 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002559 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002560 }
2561 }
2562
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002563 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2564 int callingUid) {
2565 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2566 if (nri != null) {
2567 handleReleaseNetworkRequest(nri.request, callingUid);
2568 }
2569 }
2570
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002571 // Determines whether the network is the best (or could become the best, if it validated), for
2572 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2573 // on the value of reason:
2574 //
2575 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2576 // then it should be torn down.
2577 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2578 // then it should be lingered.
2579 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2580 final int numRequests;
2581 switch (reason) {
2582 case TEARDOWN:
2583 numRequests = nai.numRequestNetworkRequests();
2584 break;
2585 case LINGER:
2586 numRequests = nai.numForegroundNetworkRequests();
2587 break;
2588 default:
2589 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2590 return true;
2591 }
2592
2593 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002594 return false;
2595 }
Paul Jensene0988542015-06-25 15:30:08 -04002596 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002597 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2598 // Background requests don't affect lingering.
2599 continue;
2600 }
2601
Paul Jensene0988542015-06-25 15:30:08 -04002602 // If this Network is already the highest scoring Network for a request, or if
2603 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002604 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002605 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002606 // Note that this catches two important cases:
2607 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2608 // is currently satisfying the request. This is desirable when
2609 // cellular ends up validating but WiFi does not.
2610 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002611 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002612 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002613 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002614 nai.getCurrentScoreAsValidated())) {
2615 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002616 }
2617 }
Paul Jensene0988542015-06-25 15:30:08 -04002618 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002619 }
2620
Erik Klineacdd6392016-07-07 16:50:58 +09002621 private NetworkRequestInfo getNriForAppRequest(
2622 NetworkRequest request, int callingUid, String requestedOperation) {
2623 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2624
Robert Greenwalt9258c642014-03-26 16:47:06 -07002625 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002626 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002627 log(String.format("UID %d attempted to %s for unowned request %s",
2628 callingUid, requestedOperation, nri));
2629 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002630 }
Erik Klineacdd6392016-07-07 16:50:58 +09002631 }
2632
2633 return nri;
2634 }
2635
Erik Kline57faba92015-11-25 12:49:38 +09002636 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002637 if (mNetworkRequests.get(nri.request) == null) {
2638 return;
Erik Kline57faba92015-11-25 12:49:38 +09002639 }
Hugo Benichicd952782017-09-20 11:20:14 +09002640 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002641 return;
2642 }
2643 if (VDBG || (DBG && nri.request.isRequest())) {
2644 log("releasing " + nri.request + " (timeout)");
2645 }
2646 handleRemoveNetworkRequest(nri);
2647 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002648 }
2649
Erik Klineacdd6392016-07-07 16:50:58 +09002650 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002651 final NetworkRequestInfo nri =
2652 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2653 if (nri == null) {
2654 return;
Erik Kline57faba92015-11-25 12:49:38 +09002655 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002656 if (VDBG || (DBG && nri.request.isRequest())) {
2657 log("releasing " + nri.request + " (release request)");
2658 }
2659 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002660 }
Erik Klineacdd6392016-07-07 16:50:58 +09002661
Hugo Benichidba33db2017-03-23 22:40:44 +09002662 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002663 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002664 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002665
Erik Klineacdd6392016-07-07 16:50:58 +09002666 synchronized (mUidToNetworkRequestCount) {
2667 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2668 if (requests < 1) {
2669 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2670 nri.mUid);
2671 } else if (requests == 1) {
2672 mUidToNetworkRequestCount.removeAt(
2673 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2674 } else {
2675 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2676 }
2677 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002678
Erik Klineacdd6392016-07-07 16:50:58 +09002679 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2680 if (nri.request.isRequest()) {
2681 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002682 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002683 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002684 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002685 nai.removeRequest(nri.request.requestId);
2686 if (VDBG) {
2687 log(" Removing from current network " + nai.name() +
2688 ", leaving " + nai.numNetworkRequests() + " requests.");
2689 }
2690 // If there are still lingered requests on this network, don't tear it down,
2691 // but resume lingering instead.
2692 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002693 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002694 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2695 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002696 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002697 wasKept = true;
2698 }
Hugo Benichicd952782017-09-20 11:20:14 +09002699 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002700 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2701 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002702 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002703 }
Erik Klineacdd6392016-07-07 16:50:58 +09002704 }
2705
2706 // TODO: remove this code once we know that the Slog.wtf is never hit.
2707 //
2708 // Find all networks that are satisfying this request and remove the request
2709 // from their request lists.
2710 // TODO - it's my understanding that for a request there is only a single
2711 // network satisfying it, so this loop is wasteful
2712 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2713 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2714 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2715 otherNai.name() + ", but mNetworkAgentInfos says " +
2716 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002717 }
2718 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002719
Erik Klineacdd6392016-07-07 16:50:58 +09002720 // Maintain the illusion. When this request arrived, we might have pretended
2721 // that a network connected to serve it, even though the network was already
2722 // connected. Now that this request has gone away, we might have to pretend
2723 // that the network disconnected. LegacyTypeTracker will generate that
2724 // phantom disconnect for this type.
2725 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2726 boolean doRemove = true;
2727 if (wasKept) {
2728 // check if any of the remaining requests for this network are for the
2729 // same legacy type - if so, don't remove the nai
2730 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2731 NetworkRequest otherRequest = nai.requestAt(i);
2732 if (otherRequest.legacyType == nri.request.legacyType &&
2733 otherRequest.isRequest()) {
2734 if (DBG) log(" still have other legacy request - leaving");
2735 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002736 }
2737 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002738 }
2739
Erik Klineacdd6392016-07-07 16:50:58 +09002740 if (doRemove) {
2741 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002742 }
2743 }
Erik Klineacdd6392016-07-07 16:50:58 +09002744
2745 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2746 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2747 nri.request);
2748 }
2749 } else {
2750 // listens don't have a singular affectedNetwork. Check all networks to see
2751 // if this listen request applies and remove it.
2752 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2753 nai.removeRequest(nri.request.requestId);
2754 if (nri.request.networkCapabilities.hasSignalStrength() &&
2755 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2756 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2757 }
2758 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002759 }
2760 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002761
Lorenzo Colitti18660282016-07-04 12:55:44 +09002762 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002763 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2764 enforceConnectivityInternalPermission();
2765 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002766 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002767 }
2768
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002769 @Override
2770 public void setAvoidUnvalidated(Network network) {
2771 enforceConnectivityInternalPermission();
2772 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2773 }
2774
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002775 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2776 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2777 " accept=" + accept + " always=" + always);
2778
2779 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2780 if (nai == null) {
2781 // Nothing to do.
2782 return;
2783 }
2784
2785 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002786 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002787 return;
2788 }
2789
2790 if (!nai.networkMisc.explicitlySelected) {
2791 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2792 }
2793
2794 if (accept != nai.networkMisc.acceptUnvalidated) {
2795 int oldScore = nai.getCurrentScore();
2796 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002797 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002798 sendUpdatedScoreToFactories(nai);
2799 }
2800
2801 if (always) {
2802 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002803 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002804 }
2805
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002806 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002807 // Tell the NetworkAgent to not automatically reconnect to the network.
2808 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2809 // Teardown the nework.
2810 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002811 }
2812
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002813 }
2814
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002815 private void handleSetAvoidUnvalidated(Network network) {
2816 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2817 if (nai == null || nai.lastValidated) {
2818 // Nothing to do. The network either disconnected or revalidated.
2819 return;
2820 }
2821 if (!nai.avoidUnvalidated) {
2822 int oldScore = nai.getCurrentScore();
2823 nai.avoidUnvalidated = true;
2824 rematchAllNetworksAndRequests(nai, oldScore);
2825 sendUpdatedScoreToFactories(nai);
2826 }
2827 }
2828
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002829 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002830 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002831 mHandler.sendMessageDelayed(
2832 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2833 PROMPT_UNVALIDATED_DELAY_MS);
2834 }
2835
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002836 @Override
2837 public void startCaptivePortalApp(Network network) {
2838 enforceConnectivityInternalPermission();
2839 mHandler.post(() -> {
2840 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2841 if (nai == null) return;
2842 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2843 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2844 });
2845 }
2846
Hugo Benichic8e9e122016-09-14 23:23:08 +00002847 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002848 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002849 }
2850
Erik Kline065ab6e2016-10-02 18:02:14 +09002851 private void rematchForAvoidBadWifiUpdate() {
2852 rematchAllNetworksAndRequests(null, 0);
2853 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2854 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2855 sendUpdatedScoreToFactories(nai);
2856 }
2857 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002858 }
2859
Erik Kline065ab6e2016-10-02 18:02:14 +09002860 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002861 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002862 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002863 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002864 if (!configRestrict) {
2865 pw.println("Bad Wi-Fi avoidance: unrestricted");
2866 return;
2867 }
2868
2869 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2870 pw.increaseIndent();
2871 pw.println("Config restrict: " + configRestrict);
2872
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002873 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002874 String description;
2875 // Can't use a switch statement because strings are legal case labels, but null is not.
2876 if ("0".equals(value)) {
2877 description = "get stuck";
2878 } else if (value == null) {
2879 description = "prompt";
2880 } else if ("1".equals(value)) {
2881 description = "avoid";
2882 } else {
2883 description = value + " (?)";
2884 }
2885 pw.println("User setting: " + description);
2886 pw.println("Network overrides:");
2887 pw.increaseIndent();
2888 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2889 if (nai.avoidUnvalidated) {
2890 pw.println(nai.name());
2891 }
2892 }
2893 pw.decreaseIndent();
2894 pw.decreaseIndent();
2895 }
2896
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002897 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2898 final String action;
2899 switch (type) {
2900 case NO_INTERNET:
2901 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2902 break;
2903 case LOST_INTERNET:
2904 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2905 break;
2906 default:
2907 Slog.wtf(TAG, "Unknown notification type " + type);
2908 return;
2909 }
2910
2911 Intent intent = new Intent(action);
2912 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2913 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2914 intent.setClassName("com.android.settings",
2915 "com.android.settings.wifi.WifiNoInternetDialog");
2916
2917 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2918 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2919 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2920 }
2921
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002922 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002923 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002924 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2925
2926 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2927 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002928 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002929 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002930 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2931 return;
2932 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002933 showValidationNotification(nai, NotificationType.NO_INTERNET);
2934 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002935
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002936 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2937 NetworkCapabilities nc = nai.networkCapabilities;
2938 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002939
Erik Kline065ab6e2016-10-02 18:02:14 +09002940 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002941 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002942 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2943 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002944 }
2945
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002946 @Override
2947 public int getMultipathPreference(Network network) {
2948 enforceAccessPermission();
2949
2950 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002951 if (nai != null && nai.networkCapabilities
2952 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002953 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2954 }
2955
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002956 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
2957 if (networkPreference != null) {
2958 return networkPreference;
2959 }
2960
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002961 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2962 }
2963
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002964 private class InternalHandler extends Handler {
2965 public InternalHandler(Looper looper) {
2966 super(looper);
2967 }
2968
2969 @Override
2970 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002971 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002972 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002973 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002974 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002975 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002976 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002977 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002978 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002979 break;
2980 }
Jason Monkdecd2952013-10-10 14:02:51 -04002981 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002982 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002983 break;
2984 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002985 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002986 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2987 break;
2988 }
2989 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2990 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002991 break;
2992 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002993 case EVENT_REGISTER_NETWORK_AGENT: {
2994 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2995 break;
2996 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002997 case EVENT_REGISTER_NETWORK_REQUEST:
2998 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002999 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003000 break;
3001 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003002 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3003 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003004 handleRegisterNetworkRequestWithIntent(msg);
3005 break;
3006 }
Erik Kline57faba92015-11-25 12:49:38 +09003007 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3008 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3009 handleTimedOutNetworkRequest(nri);
3010 break;
3011 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003012 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3013 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3014 break;
3015 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003016 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003017 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003018 break;
3019 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003020 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003021 Network network = (Network) msg.obj;
3022 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003023 break;
3024 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003025 case EVENT_SET_AVOID_UNVALIDATED: {
3026 handleSetAvoidUnvalidated((Network) msg.obj);
3027 break;
3028 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003029 case EVENT_PROMPT_UNVALIDATED: {
3030 handlePromptUnvalidated((Network) msg.obj);
3031 break;
3032 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003033 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
3034 handleMobileDataAlwaysOn();
3035 break;
3036 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003037 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3038 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3039 mKeepaliveTracker.handleStartKeepalive(msg);
3040 break;
3041 }
3042 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3043 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3044 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3045 int slot = msg.arg1;
3046 int reason = msg.arg2;
3047 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3048 break;
3049 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003050 case EVENT_SYSTEM_READY: {
3051 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3052 nai.networkMonitor.systemReady = true;
3053 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003054 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003055 break;
3056 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003057 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003058 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003059 break;
3060 }
Erik Klinea24d4592018-01-11 21:07:29 +09003061 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3062 handlePrivateDnsSettingsChanged();
3063 break;
dalyk1fcb7392018-03-05 12:42:22 -05003064 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3065 handlePrivateDnsValidationUpdate(
3066 (PrivateDnsValidationUpdate) msg.obj);
3067 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068 }
3069 }
3070 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003071
3072 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003073 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003074 public int tether(String iface, String callerPkg) {
3075 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003076 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003077 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003078 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003079 } else {
3080 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3081 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003082 }
3083
3084 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003085 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003086 public int untether(String iface, String callerPkg) {
3087 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003088
3089 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003090 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003091 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003092 } else {
3093 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3094 }
3095 }
3096
3097 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003098 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003099 public int getLastTetherError(String iface) {
3100 enforceTetherAccessPermission();
3101
3102 if (isTetheringSupported()) {
3103 return mTethering.getLastTetherError(iface);
3104 } else {
3105 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3106 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003107 }
3108
3109 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003110 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003111 public String[] getTetherableUsbRegexs() {
3112 enforceTetherAccessPermission();
3113 if (isTetheringSupported()) {
3114 return mTethering.getTetherableUsbRegexs();
3115 } else {
3116 return new String[0];
3117 }
3118 }
3119
Lorenzo Colitti18660282016-07-04 12:55:44 +09003120 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003121 public String[] getTetherableWifiRegexs() {
3122 enforceTetherAccessPermission();
3123 if (isTetheringSupported()) {
3124 return mTethering.getTetherableWifiRegexs();
3125 } else {
3126 return new String[0];
3127 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003128 }
3129
Lorenzo Colitti18660282016-07-04 12:55:44 +09003130 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003131 public String[] getTetherableBluetoothRegexs() {
3132 enforceTetherAccessPermission();
3133 if (isTetheringSupported()) {
3134 return mTethering.getTetherableBluetoothRegexs();
3135 } else {
3136 return new String[0];
3137 }
3138 }
3139
Lorenzo Colitti18660282016-07-04 12:55:44 +09003140 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003141 public int setUsbTethering(boolean enable, String callerPkg) {
3142 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003143 if (isTetheringSupported()) {
3144 return mTethering.setUsbTethering(enable);
3145 } else {
3146 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3147 }
3148 }
3149
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003150 // TODO - move iface listing, queries, etc to new module
3151 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003152 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003153 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003154 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003155 return mTethering.getTetherableIfaces();
3156 }
3157
Lorenzo Colitti18660282016-07-04 12:55:44 +09003158 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003159 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003160 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003161 return mTethering.getTetheredIfaces();
3162 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003163
Lorenzo Colitti18660282016-07-04 12:55:44 +09003164 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003165 public String[] getTetheringErroredIfaces() {
3166 enforceTetherAccessPermission();
3167 return mTethering.getErroredIfaces();
3168 }
3169
Lorenzo Colitti18660282016-07-04 12:55:44 +09003170 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003171 public String[] getTetheredDhcpRanges() {
3172 enforceConnectivityInternalPermission();
3173 return mTethering.getTetheredDhcpRanges();
3174 }
3175
Udam Saini0e94c362017-06-07 12:06:28 -07003176 @Override
3177 public boolean isTetheringSupported(String callerPkg) {
3178 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3179 return isTetheringSupported();
3180 }
3181
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003182 // if ro.tether.denied = true we default to no tethering
3183 // gservices could set the secure setting to 1 though to enable it on a build where it
3184 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003185 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003186 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3187 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3188 Settings.Global.TETHER_SUPPORTED, defaultVal));
3189 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003190 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003191
3192 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3193 boolean adminUser = false;
3194 final long token = Binder.clearCallingIdentity();
3195 try {
3196 adminUser = mUserManager.isAdminUser();
3197 } finally {
3198 Binder.restoreCallingIdentity(token);
3199 }
3200
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003201 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003202 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003203
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003204 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003205 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3206 String callerPkg) {
3207 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003208 if (!isTetheringSupported()) {
3209 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3210 return;
3211 }
3212 mTethering.startTethering(type, receiver, showProvisioningUi);
3213 }
3214
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003215 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003216 public void stopTethering(int type, String callerPkg) {
3217 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003218 mTethering.stopTethering(type);
3219 }
3220
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003221 // Called when we lose the default network and have no replacement yet.
3222 // This will automatically be cleared after X seconds or a new default network
3223 // becomes CONNECTED, whichever happens first. The timer is started by the
3224 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003225 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003226 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003227 if (mNetTransitionWakeLock.isHeld()) {
3228 return;
3229 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003230 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003231 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3232 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003233 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003234 mWakelockLogs.log("ACQUIRE for " + forWhom);
3235 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3236 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003237 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003238
Hugo Benichi4c31b342017-03-30 23:18:10 +09003239 // Called when we gain a new default network to release the network transition wakelock in a
3240 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3241 // message is cancelled.
3242 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003243 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003244 if (!mNetTransitionWakeLock.isHeld()) {
3245 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003246 }
3247 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003248 // Cancel self timeout on wakelock hold.
3249 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3250 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3251 mHandler.sendMessageDelayed(msg, 1000);
3252 }
3253
3254 // Called when either message of ensureNetworkTransitionWakelock or
3255 // scheduleReleaseNetworkTransitionWakelock is processed.
3256 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3257 String event = eventName(eventId);
3258 synchronized (this) {
3259 if (!mNetTransitionWakeLock.isHeld()) {
3260 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3261 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3262 return;
3263 }
3264 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003265 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3266 mTotalWakelockDurationMs += lockDuration;
3267 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3268 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003269 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003270 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003271 }
3272
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003273 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003274 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003275 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003276 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003277 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003278 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003279 }
3280
Lorenzo Colitti18660282016-07-04 12:55:44 +09003281 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003282 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003283 enforceAccessPermission();
3284 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003285 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003286 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003287 mHandler.sendMessage(
3288 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3289 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003290
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003291 private void handleReportNetworkConnectivity(
3292 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003293 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003294 if (network == null) {
3295 nai = getDefaultNetwork();
3296 } else {
3297 nai = getNetworkAgentInfoForNetwork(network);
3298 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003299 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3300 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3301 return;
3302 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003303 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003304 if (hasConnectivity == nai.lastValidated) {
3305 return;
3306 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003307 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003308 int netid = nai.network.netId;
3309 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003310 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003311 // Validating a network that has not yet connected could result in a call to
3312 // rematchNetworkAndRequests() which is not meant to work on such networks.
3313 if (!nai.everConnected) {
3314 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003315 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003316 LinkProperties lp = getLinkProperties(nai);
3317 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3318 return;
3319 }
Erik Kline79c6d052018-03-21 07:18:33 -07003320 nai.networkMonitor.forceReevaluation(uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003321 }
3322
Paul Jensencee9b512015-05-06 07:32:40 -04003323 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003324 // this information is already available as a world read/writable jvm property
3325 // so this API change wouldn't have a benifit. It also breaks the passing
3326 // of proxy info to all the JVMs.
3327 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003328 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003329 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003330 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3331 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003332 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003333 }
3334
Lorenzo Colitti18660282016-07-04 12:55:44 +09003335 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003336 public ProxyInfo getProxyForNetwork(Network network) {
3337 if (network == null) return getDefaultProxy();
3338 final ProxyInfo globalProxy = getGlobalProxy();
3339 if (globalProxy != null) return globalProxy;
3340 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3341 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3342 // caller may not have.
3343 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3344 if (nai == null) return null;
3345 synchronized (nai) {
3346 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3347 if (proxyInfo == null) return null;
3348 return new ProxyInfo(proxyInfo);
3349 }
3350 }
3351
Paul Jensene0bef712014-12-10 15:12:18 -05003352 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3353 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3354 // proxy is null then there is no proxy in place).
3355 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3356 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3357 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3358 proxy = null;
3359 }
3360 return proxy;
3361 }
3362
3363 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3364 // better for determining if a new proxy broadcast is necessary:
3365 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3366 // avoid unnecessary broadcasts.
3367 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3368 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3369 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3370 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3371 // all set.
3372 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3373 a = canonicalizeProxyInfo(a);
3374 b = canonicalizeProxyInfo(b);
3375 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3376 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3377 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3378 }
3379
Jason Monk207900c2014-04-25 15:00:09 -04003380 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003381 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003382
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003383 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003384 if (proxyProperties == mGlobalProxy) return;
3385 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3386 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3387
3388 String host = "";
3389 int port = 0;
3390 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003391 String pacFileUrl = "";
3392 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003393 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003394 if (!proxyProperties.isValid()) {
3395 if (DBG)
3396 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3397 return;
3398 }
Jason Monk207900c2014-04-25 15:00:09 -04003399 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003400 host = mGlobalProxy.getHost();
3401 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003402 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003403 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003404 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003405 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003406 } else {
3407 mGlobalProxy = null;
3408 }
3409 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003410 final long token = Binder.clearCallingIdentity();
3411 try {
3412 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3413 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3414 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3415 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003416 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003417 } finally {
3418 Binder.restoreCallingIdentity(token);
3419 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003420
Jason Monkcf0f97a2014-10-02 15:39:38 -04003421 if (mGlobalProxy == null) {
3422 proxyProperties = mDefaultProxy;
3423 }
3424 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003425 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003426 }
3427
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003428 private void loadGlobalProxy() {
3429 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003430 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3431 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3432 String exclList = Settings.Global.getString(res,
3433 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003434 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3435 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003436 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003437 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003438 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003439 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003440 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003441 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003442 if (!proxyProperties.isValid()) {
3443 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3444 return;
3445 }
3446
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003447 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003448 mGlobalProxy = proxyProperties;
3449 }
3450 }
3451 }
3452
Jason Monk207900c2014-04-25 15:00:09 -04003453 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003454 // this information is already available as a world read/writable jvm property
3455 // so this API change wouldn't have a benifit. It also breaks the passing
3456 // of proxy info to all the JVMs.
3457 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003458 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003459 return mGlobalProxy;
3460 }
3461 }
3462
Jason Monk207900c2014-04-25 15:00:09 -04003463 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003464 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003465 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003466 proxy = null;
3467 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003468 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003469 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003470 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003471 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003472 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3473 return;
3474 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003475
3476 // This call could be coming from the PacManager, containing the port of the local
3477 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3478 // global (to get the correct local port), and send a broadcast.
3479 // TODO: Switch PacManager to have its own message to send back rather than
3480 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003481 if ((mGlobalProxy != null) && (proxy != null)
3482 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003483 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3484 mGlobalProxy = proxy;
3485 sendProxyBroadcast(mGlobalProxy);
3486 return;
3487 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003488 mDefaultProxy = proxy;
3489
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003490 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003491 if (!mDefaultProxyDisabled) {
3492 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003493 }
3494 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003495 }
3496
Paul Jensene0bef712014-12-10 15:12:18 -05003497 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3498 // This method gets called when any network changes proxy, but the broadcast only ever contains
3499 // the default proxy (even if it hasn't changed).
3500 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3501 // world where an app might be bound to a non-default network.
3502 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3503 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3504 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3505
3506 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3507 sendProxyBroadcast(getDefaultProxy());
3508 }
3509 }
3510
Robert Greenwalt434203a2010-10-11 16:00:27 -07003511 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003512 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3513 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003514 if (!TextUtils.isEmpty(proxy)) {
3515 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003516 if (data.length == 0) {
3517 return;
3518 }
3519
Robert Greenwalt434203a2010-10-11 16:00:27 -07003520 String proxyHost = data[0];
3521 int proxyPort = 8080;
3522 if (data.length > 1) {
3523 try {
3524 proxyPort = Integer.parseInt(data[1]);
3525 } catch (NumberFormatException e) {
3526 return;
3527 }
3528 }
Jason Monk207900c2014-04-25 15:00:09 -04003529 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003530 setGlobalProxy(p);
3531 }
3532 }
3533
Jason Monk207900c2014-04-25 15:00:09 -04003534 private void sendProxyBroadcast(ProxyInfo proxy) {
3535 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003536 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003537 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003538 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003539 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3540 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003541 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003542 final long ident = Binder.clearCallingIdentity();
3543 try {
3544 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3545 } finally {
3546 Binder.restoreCallingIdentity(ident);
3547 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003548 }
3549
3550 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003551 final private HashMap<Uri, Integer> mUriEventMap;
3552 final private Context mContext;
3553 final private Handler mHandler;
3554
3555 SettingsObserver(Context context, Handler handler) {
3556 super(null);
3557 mUriEventMap = new HashMap<Uri, Integer>();
3558 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003559 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003560 }
3561
Erik Klineda4bfa82015-04-30 12:58:40 +09003562 void observe(Uri uri, int what) {
3563 mUriEventMap.put(uri, what);
3564 final ContentResolver resolver = mContext.getContentResolver();
3565 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003566 }
3567
3568 @Override
3569 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003570 Slog.wtf(TAG, "Should never be reached.");
3571 }
3572
3573 @Override
3574 public void onChange(boolean selfChange, Uri uri) {
3575 final Integer what = mUriEventMap.get(uri);
3576 if (what != null) {
3577 mHandler.obtainMessage(what.intValue()).sendToTarget();
3578 } else {
3579 loge("No matching event to send for URI=" + uri);
3580 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003581 }
3582 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003583
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003584 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003585 Slog.d(TAG, s);
3586 }
3587
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003588 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003589 Slog.e(TAG, s);
3590 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003591
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003592 private static void loge(String s, Throwable t) {
3593 Slog.e(TAG, s, t);
3594 }
3595
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003596 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003597 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003598 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3599 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3600 *
3601 * @param oldPackage Package name of the application which currently controls VPN, which will
3602 * be replaced. If there is no such application, this should should either be
3603 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3604 * @param newPackage Package name of the application which should gain control of VPN, or
3605 * {@code null} to disable.
3606 * @param userId User for whom to prepare the new VPN.
3607 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003608 * @hide
3609 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003610 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003611 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3612 int userId) {
3613 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003614
Hugo Benichi20035e02017-04-26 14:53:28 +09003615 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003616 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003617 Vpn vpn = mVpns.get(userId);
3618 if (vpn != null) {
3619 return vpn.prepare(oldPackage, newPackage);
3620 } else {
3621 return false;
3622 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003623 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003624 }
3625
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003626 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003627 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3628 * This method is used by system-privileged apps.
3629 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3630 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3631 *
3632 * @param packageName The package for which authorization state should change.
3633 * @param userId User for whom {@code packageName} is installed.
3634 * @param authorized {@code true} if this app should be able to start a VPN connection without
3635 * explicit user approval, {@code false} if not.
3636 *
Jeff Davidson05542602014-08-11 14:07:27 -07003637 * @hide
3638 */
3639 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003640 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3641 enforceCrossUserPermission(userId);
3642
Hugo Benichi20035e02017-04-26 14:53:28 +09003643 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003644 Vpn vpn = mVpns.get(userId);
3645 if (vpn != null) {
3646 vpn.setPackageAuthorization(packageName, authorized);
3647 }
Jeff Davidson05542602014-08-11 14:07:27 -07003648 }
3649 }
3650
3651 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003652 * Configure a TUN interface and return its file descriptor. Parameters
3653 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003654 * and not available in ConnectivityManager. Permissions are checked in
3655 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003656 * @hide
3657 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003658 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003659 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003660 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003661 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003662 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003663 return mVpns.get(user).establish(config);
3664 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003665 }
3666
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003667 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003668 * Start legacy VPN, controlling native daemons as needed. Creates a
3669 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003670 */
3671 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003672 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003673 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003674 final LinkProperties egress = getActiveLinkProperties();
3675 if (egress == null) {
3676 throw new IllegalStateException("Missing active network connection");
3677 }
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 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3681 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003682 }
3683
3684 /**
3685 * Return the information of the ongoing legacy VPN. This method is used
3686 * by VpnSettings and not available in ConnectivityManager. Permissions
3687 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003688 */
3689 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003690 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3691 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003692
Hugo Benichi20035e02017-04-26 14:53:28 +09003693 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003694 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003695 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003696 }
3697
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003698 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003699 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3700 * and not available in ConnectivityManager.
3701 */
3702 @Override
3703 public VpnInfo[] getAllVpnInfo() {
3704 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003705 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003706 if (mLockdownEnabled) {
3707 return new VpnInfo[0];
3708 }
3709
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003710 List<VpnInfo> infoList = new ArrayList<>();
3711 for (int i = 0; i < mVpns.size(); i++) {
3712 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3713 if (info != null) {
3714 infoList.add(info);
3715 }
3716 }
3717 return infoList.toArray(new VpnInfo[infoList.size()]);
3718 }
3719 }
3720
3721 /**
3722 * @return VPN information for accounting, or null if we can't retrieve all required
3723 * information, e.g primary underlying iface.
3724 */
3725 @Nullable
3726 private VpnInfo createVpnInfo(Vpn vpn) {
3727 VpnInfo info = vpn.getVpnInfo();
3728 if (info == null) {
3729 return null;
3730 }
3731 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3732 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3733 // the underlyingNetworks list.
3734 if (underlyingNetworks == null) {
3735 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3736 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3737 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3738 }
3739 } else if (underlyingNetworks.length > 0) {
3740 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3741 if (linkProperties != null) {
3742 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3743 }
3744 }
3745 return info.primaryUnderlyingIface == null ? null : info;
3746 }
3747
3748 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003749 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3750 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003751 * Permissions are checked in Vpn class.
3752 * @hide
3753 */
3754 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003755 public VpnConfig getVpnConfig(int userId) {
3756 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003757 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003758 Vpn vpn = mVpns.get(userId);
3759 if (vpn != null) {
3760 return vpn.getVpnConfig();
3761 } else {
3762 return null;
3763 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003764 }
3765 }
3766
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003767 @Override
3768 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003769 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3770 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3771 return false;
3772 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003773
Hugo Benichi69744342017-11-27 10:57:16 +09003774 synchronized (mVpns) {
3775 // Tear down existing lockdown if profile was removed
3776 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3777 if (mLockdownEnabled) {
3778 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3779 if (profileTag == null) {
3780 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3781 return false;
3782 }
3783 String profileName = new String(profileTag);
3784 final VpnProfile profile = VpnProfile.decode(
3785 profileName, mKeyStore.get(Credentials.VPN + profileName));
3786 if (profile == null) {
3787 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3788 setLockdownTracker(null);
3789 return true;
3790 }
3791 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003792 Vpn vpn = mVpns.get(user);
3793 if (vpn == null) {
3794 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3795 return false;
3796 }
3797 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003798 } else {
3799 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003800 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003801 }
3802
3803 return true;
3804 }
3805
3806 /**
3807 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3808 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3809 */
Hugo Benichi69744342017-11-27 10:57:16 +09003810 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003811 private void setLockdownTracker(LockdownVpnTracker tracker) {
3812 // Shutdown any existing tracker
3813 final LockdownVpnTracker existing = mLockdownTracker;
3814 mLockdownTracker = null;
3815 if (existing != null) {
3816 existing.shutdown();
3817 }
3818
Robin Leec3736bc2017-03-10 16:19:54 +00003819 if (tracker != null) {
3820 mLockdownTracker = tracker;
3821 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003822 }
3823 }
3824
Hugo Benichi69744342017-11-27 10:57:16 +09003825 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003826 private void throwIfLockdownEnabled() {
3827 if (mLockdownEnabled) {
3828 throw new IllegalStateException("Unavailable in lockdown mode");
3829 }
3830 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003831
Robin Lee244ce8e2016-01-05 18:03:46 +00003832 /**
Robin Lee17e61832016-05-09 13:46:28 +01003833 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3834 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003835 *
Robin Lee17e61832016-05-09 13:46:28 +01003836 * @return {@code true} if the service was started, the service was already connected, or there
3837 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003838 */
Robin Lee17e61832016-05-09 13:46:28 +01003839 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003840 synchronized (mVpns) {
3841 Vpn vpn = mVpns.get(userId);
3842 if (vpn == null) {
3843 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3844 // exists already.
3845 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3846 return false;
3847 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003848
Robin Lee812800c2016-05-13 15:38:08 +01003849 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003850 }
3851 }
3852
3853 @Override
Charles He36738632017-05-15 17:07:18 +01003854 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3855 enforceSettingsPermission();
3856 enforceCrossUserPermission(userId);
3857
3858 synchronized (mVpns) {
3859 Vpn vpn = mVpns.get(userId);
3860 if (vpn == null) {
3861 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3862 return false;
3863 }
3864 return vpn.isAlwaysOnPackageSupported(packageName);
3865 }
3866 }
3867
3868 @Override
Robin Leedc679712016-05-03 13:23:03 +01003869 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003870 enforceConnectivityInternalPermission();
3871 enforceCrossUserPermission(userId);
3872
Robin Lee244ce8e2016-01-05 18:03:46 +00003873 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003874 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3875 if (LockdownVpnTracker.isEnabled()) {
3876 return false;
3877 }
3878
Robin Lee244ce8e2016-01-05 18:03:46 +00003879 Vpn vpn = mVpns.get(userId);
3880 if (vpn == null) {
3881 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3882 return false;
3883 }
Robin Lee17e61832016-05-09 13:46:28 +01003884 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003885 return false;
3886 }
Robin Lee17e61832016-05-09 13:46:28 +01003887 if (!startAlwaysOnVpn(userId)) {
3888 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003889 return false;
3890 }
3891 }
3892 return true;
3893 }
3894
3895 @Override
3896 public String getAlwaysOnVpnPackage(int userId) {
3897 enforceConnectivityInternalPermission();
3898 enforceCrossUserPermission(userId);
3899
3900 synchronized (mVpns) {
3901 Vpn vpn = mVpns.get(userId);
3902 if (vpn == null) {
3903 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3904 return null;
3905 }
3906 return vpn.getAlwaysOnPackage();
3907 }
3908 }
3909
Wink Savilleab9321d2013-06-29 21:10:57 -07003910 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003911 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003912 // TODO: Remove? Any reason to trigger a provisioning check?
3913 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003914 }
3915
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003916 /** Location to an updatable file listing carrier provisioning urls.
3917 * An example:
3918 *
3919 * <?xml version="1.0" encoding="utf-8"?>
3920 * <provisioningUrls>
3921 * <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 -07003922 * </provisioningUrls>
3923 */
3924 private static final String PROVISIONING_URL_PATH =
3925 "/data/misc/radio/provisioning_urls.xml";
3926 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003927
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003928 /** XML tag for root element. */
3929 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3930 /** XML tag for individual url */
3931 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003932 /** XML attribute for mcc */
3933 private static final String ATTR_MCC = "mcc";
3934 /** XML attribute for mnc */
3935 private static final String ATTR_MNC = "mnc";
3936
Paul Jensen434dde82015-06-11 09:43:30 -04003937 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003938 FileReader fileReader = null;
3939 XmlPullParser parser = null;
3940 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003941
3942 try {
3943 fileReader = new FileReader(mProvisioningUrlFile);
3944 parser = Xml.newPullParser();
3945 parser.setInput(fileReader);
3946 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3947
3948 while (true) {
3949 XmlUtils.nextElement(parser);
3950
3951 String element = parser.getName();
3952 if (element == null) break;
3953
Paul Jensen434dde82015-06-11 09:43:30 -04003954 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003955 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3956 try {
3957 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3958 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3959 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3960 parser.next();
3961 if (parser.getEventType() == XmlPullParser.TEXT) {
3962 return parser.getText();
3963 }
3964 }
3965 }
3966 } catch (NumberFormatException e) {
3967 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3968 }
3969 }
3970 }
3971 return null;
3972 } catch (FileNotFoundException e) {
3973 loge("Carrier Provisioning Urls file not found");
3974 } catch (XmlPullParserException e) {
3975 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3976 } catch (IOException e) {
3977 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3978 } finally {
3979 if (fileReader != null) {
3980 try {
3981 fileReader.close();
3982 } catch (IOException e) {}
3983 }
3984 }
3985 return null;
3986 }
3987
Wink Saville42d4f082013-07-20 20:31:59 -07003988 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003989 public String getMobileProvisioningUrl() {
3990 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003991 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003992 if (TextUtils.isEmpty(url)) {
3993 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003994 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003995 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003996 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003997 }
Wink Saville8cf35602013-07-10 23:00:07 -07003998 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003999 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004000 String phoneNumber = mTelephonyManager.getLine1Number();
4001 if (TextUtils.isEmpty(phoneNumber)) {
4002 phoneNumber = "0000000000";
4003 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004004 url = String.format(url,
4005 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4006 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07004007 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004008 }
4009
Wink Savilleab9321d2013-06-29 21:10:57 -07004010 return url;
4011 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004012
Wink Saville948282b2013-08-29 08:55:16 -07004013 @Override
4014 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004015 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004016 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004017 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4018 return;
4019 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004020 final long ident = Binder.clearCallingIdentity();
4021 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004022 // Concatenate the range of types onto the range of NetIDs.
4023 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4024 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004025 } finally {
4026 Binder.restoreCallingIdentity(ident);
4027 }
Wink Saville948282b2013-08-29 08:55:16 -07004028 }
Wink Saville7788c612013-08-29 14:57:08 -07004029
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004030 @Override
4031 public void setAirplaneMode(boolean enable) {
4032 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004033 final long ident = Binder.clearCallingIdentity();
4034 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004035 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004036 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004037 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4038 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004039 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004040 } finally {
4041 Binder.restoreCallingIdentity(ident);
4042 }
4043 }
4044
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004045 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004046 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004047 Vpn userVpn = mVpns.get(userId);
4048 if (userVpn != null) {
4049 loge("Starting user already has a VPN");
4050 return;
4051 }
Paul Jensene75b9e32015-04-06 11:54:53 -04004052 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004053 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004054 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4055 updateLockdownVpn();
4056 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004057 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004058 }
4059
4060 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004061 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004062 Vpn userVpn = mVpns.get(userId);
4063 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004064 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004065 return;
4066 }
Robin Lee17e61832016-05-09 13:46:28 +01004067 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004068 mVpns.delete(userId);
4069 }
4070 }
4071
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004072 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004073 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004074 final int vpnsSize = mVpns.size();
4075 for (int i = 0; i < vpnsSize; i++) {
4076 Vpn vpn = mVpns.valueAt(i);
4077 vpn.onUserAdded(userId);
4078 }
4079 }
4080 }
4081
4082 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004083 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004084 final int vpnsSize = mVpns.size();
4085 for (int i = 0; i < vpnsSize; i++) {
4086 Vpn vpn = mVpns.valueAt(i);
4087 vpn.onUserRemoved(userId);
4088 }
4089 }
4090 }
4091
Robin Lee89e7a692016-02-29 14:38:17 +00004092 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004093 synchronized (mVpns) {
4094 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4095 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4096 updateLockdownVpn();
4097 } else {
4098 startAlwaysOnVpn(userId);
4099 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004100 }
4101 }
4102
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004103 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4104 @Override
4105 public void onReceive(Context context, Intent intent) {
4106 final String action = intent.getAction();
4107 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4108 if (userId == UserHandle.USER_NULL) return;
4109
Robin Lee323f29d2016-05-04 16:38:06 +01004110 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004111 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004112 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004113 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004114 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4115 onUserAdded(userId);
4116 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4117 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004118 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4119 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004120 }
4121 }
4122 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004123
Robin Lee95204e02017-01-27 11:59:22 +00004124 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4125 @Override
4126 public void onReceive(Context context, Intent intent) {
4127 // Try creating lockdown tracker, since user present usually means
4128 // unlocked keystore.
4129 updateLockdownVpn();
4130 mContext.unregisterReceiver(this);
4131 }
4132 };
4133
Robert Greenwalta67be032014-05-16 15:49:14 -07004134 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4135 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004136 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4137 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004138
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004139 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4140 // Map from UID to number of NetworkRequests that UID has filed.
4141 @GuardedBy("mUidToNetworkRequestCount")
4142 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4143
Robert Greenwalta67be032014-05-16 15:49:14 -07004144 private static class NetworkFactoryInfo {
4145 public final String name;
4146 public final Messenger messenger;
4147 public final AsyncChannel asyncChannel;
4148
4149 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4150 this.name = name;
4151 this.messenger = messenger;
4152 this.asyncChannel = asyncChannel;
4153 }
4154 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004155
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004156 private void ensureNetworkRequestHasType(NetworkRequest request) {
4157 if (request.type == NetworkRequest.Type.NONE) {
4158 throw new IllegalArgumentException(
4159 "All NetworkRequests in ConnectivityService must have a type");
4160 }
4161 }
4162
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004163 /**
4164 * Tracks info about the requester.
4165 * Also used to notice when the calling process dies so we can self-expire
4166 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004167 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004168 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004169 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004170 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004171 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004172 final int mPid;
4173 final int mUid;
4174 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004175
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004176 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004177 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004178 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004179 mPendingIntent = pi;
4180 messenger = null;
4181 mBinder = null;
4182 mPid = getCallingPid();
4183 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004184 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004185 }
4186
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004187 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004188 super();
4189 messenger = m;
4190 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004191 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004192 mBinder = binder;
4193 mPid = getCallingPid();
4194 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004195 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004196 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004197
4198 try {
4199 mBinder.linkToDeath(this, 0);
4200 } catch (RemoteException e) {
4201 binderDied();
4202 }
4203 }
4204
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004205 private void enforceRequestCountLimit() {
4206 synchronized (mUidToNetworkRequestCount) {
4207 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4208 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004209 throw new ServiceSpecificException(
4210 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004211 }
4212 mUidToNetworkRequestCount.put(mUid, networkRequests);
4213 }
4214 }
4215
Robert Greenwalt9258c642014-03-26 16:47:06 -07004216 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004217 if (mBinder != null) {
4218 mBinder.unlinkToDeath(this, 0);
4219 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004220 }
4221
4222 public void binderDied() {
4223 log("ConnectivityService NetworkRequestInfo binderDied(" +
4224 request + ", " + mBinder + ")");
4225 releaseNetworkRequest(request);
4226 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004227
4228 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004229 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004230 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004231 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004232 }
4233
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004234 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4235 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4236 if (badCapability != null) {
4237 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004238 }
4239 }
4240
Chalard Jeanb03a6222018-04-11 21:09:10 +09004241 // This checks that the passed capabilities either do not request a specific SSID, or the
4242 // calling app has permission to do so.
4243 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4244 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004245 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004246 throw new SecurityException("Insufficient permissions to request a specific SSID");
4247 }
4248 }
4249
Erik Kline9d598e12015-07-13 16:37:51 +09004250 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004251 final SortedSet<Integer> thresholds = new TreeSet();
4252 synchronized (nai) {
4253 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4254 if (nri.request.networkCapabilities.hasSignalStrength() &&
4255 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4256 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4257 }
4258 }
4259 }
Erik Kline9d598e12015-07-13 16:37:51 +09004260 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004261 }
4262
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004263 private void updateSignalStrengthThresholds(
4264 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4265 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004266 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004267 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4268
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004269 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004270 String detail;
4271 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4272 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4273 } else {
4274 detail = reason;
4275 }
4276 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4277 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4278 }
4279
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004280 nai.asyncChannel.sendMessage(
4281 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004282 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004283 }
4284
Etan Cohen859748f2017-04-03 17:42:34 -07004285 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4286 if (nc == null) {
4287 return;
4288 }
4289 NetworkSpecifier ns = nc.getNetworkSpecifier();
4290 if (ns == null) {
4291 return;
4292 }
4293 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4294 ns.assertValidFromUid(Binder.getCallingUid());
4295 }
4296
Robert Greenwalt9258c642014-03-26 16:47:06 -07004297 @Override
4298 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004299 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004300 final NetworkRequest.Type type = (networkCapabilities == null)
4301 ? NetworkRequest.Type.TRACK_DEFAULT
4302 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004303 // If the requested networkCapabilities is null, take them instead from
4304 // the default network request. This allows callers to keep track of
4305 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004306 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004307 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004308 networkCapabilities.removeCapability(NET_CAPABILITY_NOT_VPN);
Erik Klinea2d29402016-03-16 15:31:39 +09004309 enforceAccessPermission();
4310 } else {
4311 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4312 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004313 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4314 // of the app when the request is filed, but we never change the request if the app
4315 // changes network state. http://b/29964605
4316 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004317 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004318 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004319 ensureSufficientPermissionsForRequest(networkCapabilities,
4320 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004321 // Set the UID range for this request to the single UID of the requester, or to an empty
4322 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004323 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4324 // are no visible methods to set the UIDs, an app could use reflection to try and get
4325 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004326 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004327
Etan Cohenba07c8c2017-02-05 10:42:27 -08004328 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004329 throw new IllegalArgumentException("Bad timeout specified");
4330 }
Etan Cohen859748f2017-04-03 17:42:34 -07004331 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004332
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004333 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004334 nextNetworkRequestId(), type);
4335 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004336 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004337
4338 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004339 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004340 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004341 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004342 }
4343 return networkRequest;
4344 }
4345
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004346 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004347 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004348 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004349 } else {
4350 enforceChangePermission();
4351 }
4352 }
4353
fenglub15e72b2015-03-20 11:29:56 -07004354 @Override
fengludb571472015-04-21 17:12:05 -07004355 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004356 enforceAccessPermission();
4357 NetworkAgentInfo nai = null;
4358 if (network == null) {
4359 return false;
4360 }
4361 synchronized (mNetworkForNetId) {
4362 nai = mNetworkForNetId.get(network.netId);
4363 }
4364 if (nai != null) {
4365 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4366 return true;
4367 }
4368 return false;
4369 }
4370
Felipe Lemeee27cab2016-06-20 16:36:29 -07004371 private boolean isSystem(int uid) {
4372 return uid < Process.FIRST_APPLICATION_UID;
4373 }
fenglub15e72b2015-03-20 11:29:56 -07004374
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004375 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004376 final int uid = Binder.getCallingUid();
4377 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004378 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004379 return;
4380 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004381 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4382 // Policy already enforced.
4383 return;
4384 }
4385 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4386 // If UID is restricted, don't allow them to bring up metered APNs.
4387 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004388 }
4389 }
4390
Robert Greenwalt9258c642014-03-26 16:47:06 -07004391 @Override
4392 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4393 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004394 checkNotNull(operation, "PendingIntent cannot be null.");
4395 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4396 enforceNetworkRequestPermissions(networkCapabilities);
4397 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004398 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004399 ensureSufficientPermissionsForRequest(networkCapabilities,
4400 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07004401 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004402 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004403
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004404 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004405 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4406 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004407 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004408 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4409 nri));
4410 return networkRequest;
4411 }
4412
Jeremy Joslin79294842014-12-03 17:15:28 -08004413 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4414 mHandler.sendMessageDelayed(
4415 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4416 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4417 }
4418
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004419 @Override
4420 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004421 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004422 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4423 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004424 }
4425
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004426 // In order to implement the compatibility measure for pre-M apps that call
4427 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4428 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4429 // This ensures it has permission to do so.
4430 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4431 if (nc == null) {
4432 return false;
4433 }
4434 int[] transportTypes = nc.getTransportTypes();
4435 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4436 return false;
4437 }
4438 try {
4439 mContext.enforceCallingOrSelfPermission(
4440 android.Manifest.permission.ACCESS_WIFI_STATE,
4441 "ConnectivityService");
4442 } catch (SecurityException e) {
4443 return false;
4444 }
4445 return true;
4446 }
4447
Robert Greenwalt9258c642014-03-26 16:47:06 -07004448 @Override
4449 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4450 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004451 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4452 enforceAccessPermission();
4453 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004454
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004455 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004456 ensureSufficientPermissionsForRequest(networkCapabilities,
4457 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004458 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09004459 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4460 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4461 // onLost and onAvailable callbacks when networks move in and out of the background.
4462 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4463 // can't request networks.
4464 restrictBackgroundRequestForCaller(nc);
4465 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004466
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004467 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004468 NetworkRequest.Type.LISTEN);
4469 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004470 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004471
4472 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4473 return networkRequest;
4474 }
4475
4476 @Override
4477 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4478 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004479 checkNotNull(operation, "PendingIntent cannot be null.");
4480 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4481 enforceAccessPermission();
4482 }
Etan Cohen859748f2017-04-03 17:42:34 -07004483 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004484 ensureSufficientPermissionsForRequest(networkCapabilities,
4485 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004486
Chalard Jeandda156a2018-01-10 21:19:32 +09004487 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004488 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004489
4490 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004491 NetworkRequest.Type.LISTEN);
4492 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004493 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004494
4495 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004496 }
4497
Erik Klineacdd6392016-07-07 16:50:58 +09004498 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004499 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004500 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004501 mHandler.sendMessage(mHandler.obtainMessage(
4502 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004503 }
4504
4505 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004506 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004507 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004508 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4509 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004510 }
4511
Robert Greenwalta67be032014-05-16 15:49:14 -07004512 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004513 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004514 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4515 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4516 }
4517
4518 @Override
4519 public void unregisterNetworkFactory(Messenger messenger) {
4520 enforceConnectivityInternalPermission();
4521 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4522 }
4523
4524 private void handleUnregisterNetworkFactory(Messenger messenger) {
4525 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4526 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004527 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004528 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004529 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004530 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004531 }
4532
Robert Greenwalt7b816022014-04-18 15:25:25 -07004533 /**
4534 * NetworkAgentInfo supporting a request by requestId.
4535 * These have already been vetted (their Capabilities satisfy the request)
4536 * and the are the highest scored network available.
4537 * the are keyed off the Requests requestId.
4538 */
Hugo Benichicd952782017-09-20 11:20:14 +09004539 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4540 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004541 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4542 new SparseArray<NetworkAgentInfo>();
4543
Paul Jensen31a94f42015-02-13 14:18:39 -05004544 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4545 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004546 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4547 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004548 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4549 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4550 // there may not be a strict 1:1 correlation between the two.
4551 @GuardedBy("mNetworkForNetId")
4552 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004553
Robert Greenwalt7b816022014-04-18 15:25:25 -07004554 // NetworkAgentInfo keyed off its connecting messenger
4555 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004556 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004557 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4558 new HashMap<Messenger, NetworkAgentInfo>();
4559
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004560 @GuardedBy("mBlockedAppUids")
4561 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4562
Paul Jensen2c311d62014-11-17 12:34:51 -05004563 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004564 private final NetworkRequest mDefaultRequest;
4565
Erik Klineda4bfa82015-04-30 12:58:40 +09004566 // Request used to optionally keep mobile data active even when higher
4567 // priority networks like Wi-Fi are active.
4568 private final NetworkRequest mDefaultMobileDataRequest;
4569
Hugo Benichicd952782017-09-20 11:20:14 +09004570 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4571 synchronized (mNetworkForRequestId) {
4572 return mNetworkForRequestId.get(requestId);
4573 }
4574 }
4575
4576 private void clearNetworkForRequest(int requestId) {
4577 synchronized (mNetworkForRequestId) {
4578 mNetworkForRequestId.remove(requestId);
4579 }
4580 }
4581
4582 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4583 synchronized (mNetworkForRequestId) {
4584 mNetworkForRequestId.put(requestId, nai);
4585 }
4586 }
4587
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004588 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004589 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004590 }
4591
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004592 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004593 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004594 }
4595
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004596 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4597 return nri.request.requestId == mDefaultRequest.requestId;
4598 }
4599
Paul Jensen31a94f42015-02-13 14:18:39 -05004600 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004601 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004602 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004603 enforceConnectivityInternalPermission();
4604
Rubin Xu1bb5c082017-09-05 18:40:49 +01004605 LinkProperties lp = new LinkProperties(linkProperties);
4606 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004607 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4608 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004609 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004610 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004611 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004612 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004613 // Make sure the network capabilities reflect what the agent info says.
4614 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004615 synchronized (this) {
4616 nai.networkMonitor.systemReady = mSystemReady;
4617 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004618 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4619 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004620 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004621 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004622 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004623 }
4624
Erik Kline117e7f32018-03-04 21:01:01 +09004625 private void handleRegisterNetworkAgent(NetworkAgentInfo nai) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004626 if (VDBG) log("Got NetworkAgent Messenger");
Erik Kline117e7f32018-03-04 21:01:01 +09004627 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004628 synchronized (mNetworkForNetId) {
Erik Kline117e7f32018-03-04 21:01:01 +09004629 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004630 }
Erik Kline117e7f32018-03-04 21:01:01 +09004631 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
4632 NetworkInfo networkInfo = nai.networkInfo;
4633 nai.networkInfo = null;
4634 updateNetworkInfo(nai, networkInfo);
4635 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004636 }
4637
4638 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4639 LinkProperties newLp = networkAgent.linkProperties;
4640 int netId = networkAgent.network.netId;
4641
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004642 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4643 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004644 if (networkAgent.clatd != null) {
4645 networkAgent.clatd.fixupLinkProperties(oldLp);
4646 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004647
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004648 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004649 updateMtu(newLp, oldLp);
4650 // TODO - figure out what to do for clat
4651// for (LinkProperties lp : newLp.getStackedLinks()) {
4652// updateMtu(lp, null);
4653// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004654 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004655
Erik Kline94887872016-04-05 13:30:49 +09004656 updateRoutes(newLp, oldLp, netId);
4657 updateDnses(newLp, oldLp, netId);
dalyk1fcb7392018-03-05 12:42:22 -05004658 // Make sure LinkProperties represents the latest private DNS status.
4659 // This does not need to be done before updateDnses because the
4660 // LinkProperties are not the source of the private DNS configuration.
4661 // updateDnses will fetch the private DNS configuration from DnsManager.
4662 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004663
Hugo Benichi6f62b732017-06-27 15:13:20 +09004664 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004665 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004666 if (isDefaultNetwork(networkAgent)) {
4667 handleApplyDefaultProxy(newLp.getHttpProxy());
4668 } else {
4669 updateProxy(newLp, oldLp, networkAgent);
4670 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004671 // TODO - move this check to cover the whole function
4672 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004673 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004674 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4675 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004676
4677 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004678 }
4679
Joel Scherpelz668370b2017-06-08 15:35:21 +09004680 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004681 // Marks are only available on WiFi interaces. Checking for
4682 // marks on unsupported interfaces is harmless.
4683 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4684 return;
4685 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004686
Joel Scherpelz668370b2017-06-08 15:35:21 +09004687 int mark = mContext.getResources().getInteger(
4688 com.android.internal.R.integer.config_networkWakeupPacketMark);
4689 int mask = mContext.getResources().getInteger(
4690 com.android.internal.R.integer.config_networkWakeupPacketMask);
4691
4692 // Mask/mark of zero will not detect anything interesting.
4693 // Don't install rules unless both values are nonzero.
4694 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004695 return;
4696 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004697
4698 final String prefix = "iface:" + iface;
4699 try {
4700 if (add) {
4701 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4702 } else {
4703 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4704 }
4705 } catch (Exception e) {
4706 loge("Exception modifying wakeup packet monitoring: " + e);
4707 }
4708
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004709 }
4710
4711 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4712 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004713 CompareResult<String> interfaceDiff = new CompareResult<String>(
4714 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4715 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004716 for (String iface : interfaceDiff.added) {
4717 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004718 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004719 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004720 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004721 } catch (Exception e) {
4722 loge("Exception adding interface: " + e);
4723 }
4724 }
4725 for (String iface : interfaceDiff.removed) {
4726 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004727 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004728 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004729 mNetd.removeInterfaceFromNetwork(iface, netId);
4730 } catch (Exception e) {
4731 loge("Exception removing interface: " + e);
4732 }
4733 }
4734 }
4735
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004736 /**
4737 * Have netd update routes from oldLp to newLp.
4738 * @return true if routes changed between oldLp and newLp
4739 */
4740 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004741 // Compare the route diff to determine which routes should be added and removed.
4742 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4743 oldLp != null ? oldLp.getAllRoutes() : null,
4744 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004745
4746 // add routes before removing old in case it helps with continuous connectivity
4747
4748 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4749 for (RouteInfo route : routeDiff.added) {
4750 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004751 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004752 try {
4753 mNetd.addRoute(netId, route);
4754 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004755 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4756 loge("Exception in addRoute for non-gateway: " + e);
4757 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004758 }
4759 }
4760 for (RouteInfo route : routeDiff.added) {
4761 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004762 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004763 try {
4764 mNetd.addRoute(netId, route);
4765 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004766 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4767 loge("Exception in addRoute for gateway: " + e);
4768 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004769 }
4770 }
4771
4772 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004773 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004774 try {
4775 mNetd.removeRoute(netId, route);
4776 } catch (Exception e) {
4777 loge("Exception in removeRoute: " + e);
4778 }
4779 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004780 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004781 }
Erik Kline41368502015-06-17 13:19:54 +09004782
Erik Kline94887872016-04-05 13:30:49 +09004783 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4784 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4785 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004786 }
Erik Kline94887872016-04-05 13:30:49 +09004787
Erik Kline1742fe12017-12-13 19:40:49 +09004788 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4789 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4790
Erik Klinea24d4592018-01-11 21:07:29 +09004791 if (DBG) {
4792 final Collection<InetAddress> dnses = newLp.getDnsServers();
4793 log("Setting DNS servers for network " + netId + " to " + dnses);
4794 }
Erik Kline94887872016-04-05 13:30:49 +09004795 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004796 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004797 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004798 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004799 }
Erik Kline4edba012017-04-07 15:29:29 +09004800 }
4801
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004802 private String getNetworkPermission(NetworkCapabilities nc) {
4803 // TODO: make these permission strings AIDL constants instead.
4804 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4805 return NetworkManagementService.PERMISSION_SYSTEM;
4806 }
4807 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4808 return NetworkManagementService.PERMISSION_NETWORK;
4809 }
4810 return null;
4811 }
4812
Paul Jensen3d194ea2015-06-16 14:27:36 -04004813 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004814 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4815 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4816 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004817 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004818 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004819 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004820 if (nai.everConnected &&
4821 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4822 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004823 // does not cause any request (that is not a listen) currently matching that agent to
4824 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004825 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09004826 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004827 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09004828 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004829 }
4830
Paul Jensen3d194ea2015-06-16 14:27:36 -04004831 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004832 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004833 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004834 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004835 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004836 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004837 }
Paul Jensene0988542015-06-25 15:30:08 -04004838 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004839 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004840 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004841 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004842 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004843 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004844 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004845 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004846 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004847 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004848 if (nai.isSuspended()) {
4849 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4850 } else {
4851 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4852 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004853
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004854 return newNc;
4855 }
4856
4857 /**
4858 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4859 *
4860 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4861 * capabilities we manage and store in {@code nai}, such as validated status and captive
4862 * portal status)
4863 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4864 * potentially triggers rematches.
4865 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4866 * change.)
4867 *
4868 * @param oldScore score of the network before any of the changes that prompted us
4869 * to call this function.
4870 * @param nai the network having its capabilities updated.
4871 * @param nc the new network capabilities.
4872 */
4873 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4874 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4875
4876 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004877
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004878 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004879 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004880 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004881 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004882 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004883 } catch (RemoteException e) {
4884 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004885 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004886 }
4887
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004888 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004889 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004890 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004891 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004892 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004893
Chalard Jeanf213ca12018-01-16 18:43:05 +09004894 updateUids(nai, prevNc, newNc);
4895
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004896 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004897 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4898 // the change we're processing can't affect any requests, it can only affect the listens
4899 // on this network. We might have been called by rematchNetworkAndRequests when a
4900 // network changed foreground state.
4901 processListenRequests(nai, true);
4902 } else {
4903 // If the requestable capabilities have changed or the score changed, we can't have been
4904 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004905 rematchAllNetworksAndRequests(nai, oldScore);
4906 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004907 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004908
4909 // Report changes that are interesting for network statistics tracking.
4910 if (prevNc != null) {
4911 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004912 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004913 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004914 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004915 if (meteredChanged || roamingChanged) {
4916 notifyIfacesChangedForNetworkStats();
4917 }
4918 }
4919
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004920 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004921 // Tell VPNs about updated capabilities, since they may need to
4922 // bubble those changes through.
4923 synchronized (mVpns) {
4924 for (int i = 0; i < mVpns.size(); i++) {
4925 final Vpn vpn = mVpns.valueAt(i);
4926 vpn.updateCapabilities();
4927 }
4928 }
4929 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004930 }
4931
Chalard Jeanf213ca12018-01-16 18:43:05 +09004932 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4933 NetworkCapabilities newNc) {
4934 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4935 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4936 if (null == prevRanges) prevRanges = new ArraySet<>();
4937 if (null == newRanges) newRanges = new ArraySet<>();
4938 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4939
4940 prevRanges.removeAll(newRanges);
4941 newRanges.removeAll(prevRangesCopy);
4942
4943 try {
4944 if (!newRanges.isEmpty()) {
4945 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4946 newRanges.toArray(addedRangesArray);
4947 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4948 }
4949 if (!prevRanges.isEmpty()) {
4950 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4951 prevRanges.toArray(removedRangesArray);
4952 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4953 }
4954 } catch (Exception e) {
4955 // Never crash!
4956 loge("Exception in updateUids: " + e);
4957 }
4958 }
4959
Hugo Benichief502882017-09-01 01:23:32 +00004960 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Erik Kline79c6d052018-03-21 07:18:33 -07004961 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00004962 // Ignore updates for disconnected networks
4963 return;
4964 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004965 // newLp is already a defensive copy.
4966 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004967 if (VDBG) {
4968 log("Update of LinkProperties for " + nai.name() +
4969 "; created=" + nai.created +
4970 "; everConnected=" + nai.everConnected);
4971 }
4972 LinkProperties oldLp = nai.linkProperties;
4973 synchronized (nai) {
4974 nai.linkProperties = newLp;
4975 }
4976 if (nai.everConnected) {
4977 updateLinkProperties(nai, oldLp);
4978 }
4979 }
4980
Paul Jensenc8b9a742014-09-30 15:37:41 -04004981 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004982 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4983 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004984 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004985 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004986 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4987 }
4988 }
4989
Robert Greenwalt7b816022014-04-18 15:25:25 -07004990 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4991 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004992 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004993 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4994 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004995 }
4996 }
4997
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004998 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4999 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005000 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005001 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005002 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5003 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005004 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005005 sendIntent(nri.mPendingIntent, intent);
5006 }
5007 // else not handled
5008 }
5009
5010 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5011 mPendingIntentWakeLock.acquire();
5012 try {
5013 if (DBG) log("Sending " + pendingIntent);
5014 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5015 } catch (PendingIntent.CanceledException e) {
5016 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5017 mPendingIntentWakeLock.release();
5018 releasePendingNetworkRequest(pendingIntent);
5019 }
5020 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5021 }
5022
5023 @Override
5024 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5025 String resultData, Bundle resultExtras) {
5026 if (DBG) log("Finished sending " + pendingIntent);
5027 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005028 // Release with a delay so the receiving client has an opportunity to put in its
5029 // own request.
5030 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005031 }
5032
Chalard Jeanf19db372018-01-26 19:24:40 +09005033 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005034 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005035 if (nri.messenger == null) {
5036 return; // Default request has no msgr
5037 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005038 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005039 // TODO: check if defensive copies of data is needed.
5040 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005041 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005042 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5043 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005044 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005045 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005046 case ConnectivityManager.CALLBACK_AVAILABLE: {
5047 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
5048 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
5049 break;
5050 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005051 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005052 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005053 break;
5054 }
5055 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005056 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005057 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005058 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005059 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005060 break;
5061 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005062 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005063 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005064 break;
5065 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005066 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005067 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005068 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005069 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005070 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005071 String notification = ConnectivityManager.getCallbackName(notificationType);
5072 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005073 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005074 nri.messenger.send(msg);
5075 } catch (RemoteException e) {
5076 // may occur naturally in the race of binder death.
5077 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5078 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005079 }
5080
Hugo Benichidba33db2017-03-23 22:40:44 +09005081 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5082 bundle.putParcelable(t.getClass().getSimpleName(), t);
5083 }
5084
Paul Jensenc8b9a742014-09-30 15:37:41 -04005085 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005086 if (nai.numRequestNetworkRequests() != 0) {
5087 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5088 NetworkRequest nr = nai.requestAt(i);
5089 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005090 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005091 loge("Dead network still had at least " + nr);
5092 break;
5093 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005094 }
5095 nai.asyncChannel.disconnect();
5096 }
5097
Robert Greenwalt7b816022014-04-18 15:25:25 -07005098 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5099 if (oldNetwork == null) {
5100 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5101 return;
5102 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005103 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005104
5105 // If we get here it means that the last linger timeout for this network expired. So there
5106 // must be no other active linger timers, and we must stop lingering.
5107 oldNetwork.clearLingerState();
5108
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005109 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005110 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005111 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005112 } else {
5113 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005114 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5115 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005116 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005117 }
5118
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005119 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005120 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005121 setupDataActivityTracking(newNetwork);
5122 try {
5123 mNetd.setDefaultNetId(newNetwork.network.netId);
5124 } catch (Exception e) {
5125 loge("Exception setting default network :" + e);
5126 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005127
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005128 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005129 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005130 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005131 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005132 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005133 }
5134
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005135 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005136 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5137 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5138 NetworkRequest nr = nri.request;
5139 if (!nr.isListen()) continue;
5140 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5141 nai.removeRequest(nri.request.requestId);
5142 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5143 }
5144 }
5145
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005146 if (capabilitiesChanged) {
5147 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5148 }
5149
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005150 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5151 NetworkRequest nr = nri.request;
5152 if (!nr.isListen()) continue;
5153 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5154 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005155 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005156 }
5157 }
5158 }
5159
Paul Jensen2161a8e2014-09-11 11:00:39 -04005160 // Handles a network appearing or improving its score.
5161 //
5162 // - Evaluates all current NetworkRequests that can be
5163 // satisfied by newNetwork, and reassigns to newNetwork
5164 // any such requests for which newNetwork is the best.
5165 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005166 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005167 // needed. A network is needed if it is the best network for
5168 // one or more NetworkRequests, or if it is a VPN.
5169 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005170 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005171 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005172 //
5173 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5174 // networks that have no chance (i.e. even if validated)
5175 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005176 //
5177 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5178 // it does not remove NetworkRequests that other Networks could better satisfy.
5179 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5180 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5181 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005182 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005183 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005184 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5185 // performed to tear down unvalidated networks that have no chance (i.e. even if
5186 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005187 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005188 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005189 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005190 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005191 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005192 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005193
5194 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5195 final int score = newNetwork.getCurrentScore();
5196
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005197 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005198
Paul Jensen2161a8e2014-09-11 11:00:39 -04005199 // Find and migrate to this Network any NetworkRequests for
5200 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07005201 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04005202 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005203 NetworkCapabilities nc = newNetwork.networkCapabilities;
5204 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005205 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005206 // Process requests in the first pass and listens in the second pass. This allows us to
5207 // change a network's capabilities depending on which requests it has. This is only
5208 // correct if the change in capabilities doesn't affect whether the network satisfies
5209 // requests or not, and doesn't affect the network's score.
5210 if (nri.request.isListen()) continue;
5211
Hugo Benichicd952782017-09-20 11:20:14 +09005212 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005213 final boolean satisfies = newNetwork.satisfies(nri.request);
5214 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005215 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005216 log("Network " + newNetwork.name() + " was already satisfying" +
5217 " request " + nri.request.requestId + ". No change.");
5218 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005219 keep = true;
5220 continue;
5221 }
5222
5223 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005224 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005225 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005226 // next check if it's better than any current network we're using for
5227 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005228 if (VDBG) {
5229 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005230 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005231 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005232 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005233 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005234 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005235 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005236 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005237 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005238 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005239 affectedNetworks.add(currentNetwork);
5240 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005241 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005242 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005243 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005244 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005245 if (!newNetwork.addRequest(nri.request)) {
5246 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5247 }
5248 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005249 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005250 // Tell NetworkFactories about the new score, so they can stop
5251 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005252 // TODO - this could get expensive if we have alot of requests for this
5253 // network. Think about if there is a way to reduce this. Push
5254 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005255 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005256 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005257 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005258 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005259 if (currentNetwork != null) {
5260 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5261 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005262 }
5263 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005264 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005265 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5266 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005267 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005268 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5269 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5270 // This means this code doesn't have to handle the case where "currentNetwork" no
5271 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5272 if (DBG) {
5273 log("Network " + newNetwork.name() + " stopped satisfying" +
5274 " request " + nri.request.requestId);
5275 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005276 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005277 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005278 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005279 sendUpdatedScoreToFactories(nri.request, 0);
5280 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005281 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5282 newNetwork.name() +
5283 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005284 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005285 // TODO: Technically, sending CALLBACK_LOST here is
5286 // incorrect if there is a replacement network currently
5287 // connected that can satisfy nri, which is a request
5288 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005289 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5290 // so this code is only incorrect for a network that loses
5291 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005292 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005293 }
5294 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005295 if (isNewDefault) {
5296 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005297 makeDefault(newNetwork);
5298 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005299 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005300 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005301 // Have a new default network, release the transition wakelock in
5302 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005303 }
5304
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005305 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5306 Slog.wtf(TAG, String.format(
5307 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005308 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005309 }
5310 if (newNetwork.getCurrentScore() != score) {
5311 Slog.wtf(TAG, String.format(
5312 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005313 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005314 }
5315
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005316 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005317 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5318 // If the network went from background to foreground or vice versa, we need to update
5319 // its foreground state. It is safe to do this after rematching the requests because
5320 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5321 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005322 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005323 } else {
5324 processListenRequests(newNetwork, false);
5325 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005326
Paul Jensencf4c2c62015-07-01 14:16:32 -04005327 // do this after the default net is switched, but
5328 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005329 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005330
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005331 // Linger any networks that are no longer needed. This should be done after sending the
5332 // available callback for newNetwork.
5333 for (NetworkAgentInfo nai : affectedNetworks) {
5334 updateLingerState(nai, now);
5335 }
5336 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5337 // does not need to be done in any particular order.
5338 updateLingerState(newNetwork, now);
5339
Paul Jensencf4c2c62015-07-01 14:16:32 -04005340 if (isNewDefault) {
5341 // Maintain the illusion: since the legacy API only
5342 // understands one network at a time, we must pretend
5343 // that the current default network disconnected before
5344 // the new one connected.
5345 if (oldDefaultNetwork != null) {
5346 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5347 oldDefaultNetwork, true);
5348 }
5349 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5350 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5351 notifyLockdownVpn(newNetwork);
5352 }
5353
Robert Greenwalt7b816022014-04-18 15:25:25 -07005354 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005355 // Notify battery stats service about this network, both the normal
5356 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005357 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005358 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005359 final IBatteryStats bs = BatteryStatsService.getService();
5360 final int type = newNetwork.networkInfo.getType();
5361
5362 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5363 bs.noteNetworkInterfaceType(baseIface, type);
5364 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5365 final String stackedIface = stacked.getInterfaceName();
5366 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005367 }
5368 } catch (RemoteException ignored) {
5369 }
5370
Robert Greenwalt152ed372014-12-17 17:19:53 -08005371 // This has to happen after the notifyNetworkCallbacks as that tickles each
5372 // ConnectivityManager instance so that legacy requests correctly bind dns
5373 // requests to this network. The legacy users are listening for this bcast
5374 // and will generally do a dns request so they can ensureRouteToHost and if
5375 // they do that before the callbacks happen they'll use the default network.
5376 //
5377 // TODO: Is there still a race here? We send the broadcast
5378 // after sending the callback, but if the app can receive the
5379 // broadcast before the callback, it might still break.
5380 //
5381 // This *does* introduce a race where if the user uses the new api
5382 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5383 // they may get old info. Reverse this after the old startUsing api is removed.
5384 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005385 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5386 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005387 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005388 // legacy type tracker filters out repeat adds
5389 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5390 }
5391 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005392
5393 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5394 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5395 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5396 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5397 if (newNetwork.isVPN()) {
5398 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5399 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005400 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005401 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5402 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005403 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005404 if (nai.getLingerExpiry() > 0) {
5405 // This network has active linger timers and no requests, but is not
5406 // lingering. Linger it.
5407 //
5408 // One way (the only way?) this can happen if this network is unvalidated
5409 // and became unneeded due to another network improving its score to the
5410 // point where this network will no longer be able to satisfy any requests
5411 // even if it validates.
5412 updateLingerState(nai, now);
5413 } else {
5414 if (DBG) log("Reaping " + nai.name());
5415 teardownUnneededNetwork(nai);
5416 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005417 }
5418 }
5419 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005420 }
5421
Paul Jensen1c7ba022015-06-16 14:27:36 -04005422 /**
5423 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5424 * being disconnected.
5425 * @param changed If only one Network's score or capabilities have been modified since the last
5426 * time this function was called, pass this Network in this argument, otherwise pass
5427 * null.
5428 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5429 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5430 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5431 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5432 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005433 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005434 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005435 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5436 // to avoid the slowness. It is not simply enough to process just "changed", for
5437 // example in the case where "changed"'s score decreases and another network should begin
5438 // satifying a NetworkRequest that "changed" currently satisfies.
5439
5440 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5441 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5442 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005443 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005444 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005445 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005446 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005447 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5448 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5449 // Rematch higher scoring networks first to prevent requests first matching a lower
5450 // scoring network and then a higher scoring network, which could produce multiple
5451 // callbacks and inadvertently unlinger networks.
5452 Arrays.sort(nais);
5453 for (NetworkAgentInfo nai : nais) {
5454 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005455 // Only reap the last time through the loop. Reaping before all rematching
5456 // is complete could incorrectly teardown a network that hasn't yet been
5457 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005458 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005459 : ReapUnvalidatedNetworks.REAP,
5460 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005461 }
5462 }
5463 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005464
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005465 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005466 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005467 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005468 // For now only update icons for default connection.
5469 // TODO: Update WiFi and cellular icons separately. b/17237507
5470 if (!isDefaultNetwork(nai)) return;
5471
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005472 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005473 // Don't repeat publish.
5474 if (newInetCondition == mDefaultInetConditionPublished) return;
5475
5476 mDefaultInetConditionPublished = newInetCondition;
5477 sendInetConditionBroadcast(nai.networkInfo);
5478 }
5479
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005480 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005481 synchronized (mVpns) {
5482 if (mLockdownTracker != null) {
5483 if (nai != null && nai.isVPN()) {
5484 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5485 } else {
5486 mLockdownTracker.onNetworkInfoChanged();
5487 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005488 }
5489 }
5490 }
5491
Robert Greenwalt7b816022014-04-18 15:25:25 -07005492 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005493 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005494 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005495 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005496 synchronized (networkAgent) {
5497 oldInfo = networkAgent.networkInfo;
5498 networkAgent.networkInfo = newInfo;
5499 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005500 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005501
Robert Greenwalt7b816022014-04-18 15:25:25 -07005502 if (DBG) {
5503 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5504 (oldInfo == null ? "null" : oldInfo.getState()) +
5505 " to " + state);
5506 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005507
Robin Lee585e2482016-05-01 23:00:00 +01005508 if (!networkAgent.created
5509 && (state == NetworkInfo.State.CONNECTED
5510 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005511
5512 // A network that has just connected has zero requests and is thus a foreground network.
5513 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5514
Robert Greenwalt7b816022014-04-18 15:25:25 -07005515 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005516 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005517 if (networkAgent.isVPN()) {
5518 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005519 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5520 (networkAgent.networkMisc == null ||
5521 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005522 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005523 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005524 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005525 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005526 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005527 loge("Error creating network " + networkAgent.network.netId + ": "
5528 + e.getMessage());
5529 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005530 }
Paul Jenseneec75412014-08-04 12:21:19 -04005531 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005532 }
5533
5534 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5535 networkAgent.everConnected = true;
5536
Erik Kline79c6d052018-03-21 07:18:33 -07005537 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005538 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005539 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005540
Paul Jensenca8f16a2014-05-09 12:47:55 -04005541 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005542 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005543
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005544 if (networkAgent.isVPN()) {
5545 // Temporarily disable the default proxy (not global).
5546 synchronized (mProxyLock) {
5547 if (!mDefaultProxyDisabled) {
5548 mDefaultProxyDisabled = true;
5549 if (mGlobalProxy == null && mDefaultProxy != null) {
5550 sendProxyBroadcast(null);
5551 }
5552 }
5553 }
5554 // TODO: support proxy per network.
5555 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005556
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005557 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5558 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5559 // capabilities, so it only needs to be done once on initial connect, not every time the
5560 // network's capabilities change. Note that we do this before rematching the network,
5561 // so we could decide to tear it down immediately afterwards. That's fine though - on
5562 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5563 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005564 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005565
Paul Jensen2161a8e2014-09-11 11:00:39 -04005566 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005567 final long now = SystemClock.elapsedRealtime();
5568 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005569
5570 // This has to happen after matching the requests, because callbacks are just requests.
5571 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005572 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005573 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005574 if (networkAgent.isVPN()) {
5575 synchronized (mProxyLock) {
5576 if (mDefaultProxyDisabled) {
5577 mDefaultProxyDisabled = false;
5578 if (mGlobalProxy == null && mDefaultProxy != null) {
5579 sendProxyBroadcast(mDefaultProxy);
5580 }
5581 }
5582 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005583 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005584 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005585 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5586 state == NetworkInfo.State.SUSPENDED) {
5587 // going into or coming out of SUSPEND: rescore and notify
5588 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005589 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005590 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005591 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5592 networkAgent.networkCapabilities);
5593 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5594 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005595 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5596 ConnectivityManager.CALLBACK_SUSPENDED :
5597 ConnectivityManager.CALLBACK_RESUMED));
5598 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005599 }
5600 }
5601
Robert Greenwaltac96c522014-06-03 16:43:57 -07005602 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005603 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005604 if (score < 0) {
5605 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5606 "). Bumping score to min of 0");
5607 score = 0;
5608 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005609
Paul Jensen2161a8e2014-09-11 11:00:39 -04005610 final int oldScore = nai.getCurrentScore();
5611 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005612
Paul Jensen85cf78e2015-06-25 13:25:07 -04005613 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005614
Paul Jensenc8b9a742014-09-30 15:37:41 -04005615 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005616 }
5617
Erik Klinec75d4fa2017-02-15 19:59:17 +09005618 // Notify only this one new request of the current state. Transfer all the
5619 // current state by calling NetworkCapabilities and LinkProperties callbacks
5620 // so that callers can be guaranteed to have as close to atomicity in state
5621 // transfer as can be supported by this current API.
5622 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005623 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005624 if (nri.mPendingIntent != null) {
5625 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5626 // Attempt no subsequent state pushes where intents are involved.
5627 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005628 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005629
5630 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005631 }
5632
Robert Greenwalt8d482522015-06-24 13:23:42 -07005633 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005634 // The NetworkInfo we actually send out has no bearing on the real
5635 // state of affairs. For example, if the default connection is mobile,
5636 // and a request for HIPRI has just gone away, we need to pretend that
5637 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5638 // the state to DISCONNECTED, even though the network is of type MOBILE
5639 // and is still connected.
5640 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5641 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005642 if (state != DetailedState.DISCONNECTED) {
5643 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005644 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005645 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005646 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005647 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5648 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5649 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5650 if (info.isFailover()) {
5651 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5652 nai.networkInfo.setFailover(false);
5653 }
5654 if (info.getReason() != null) {
5655 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5656 }
5657 if (info.getExtraInfo() != null) {
5658 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5659 }
5660 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005661 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005662 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005663 if (newDefaultAgent != null) {
5664 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5665 newDefaultAgent.networkInfo);
5666 } else {
5667 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5668 }
5669 }
5670 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5671 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005672 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005673 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005674 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005675 }
5676 }
5677 }
5678
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005679 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005680 if (VDBG) {
5681 String notification = ConnectivityManager.getCallbackName(notifyType);
5682 log("notifyType " + notification + " for " + networkAgent.name());
5683 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005684 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5685 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005686 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5687 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005688 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5689 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005690 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005691 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005692 } else {
5693 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5694 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005695 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005696 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005697
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005698 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5699 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5700 }
5701
Jeff Sharkey69736342014-12-08 14:50:12 -08005702 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005703 * Returns the list of all interfaces that could be used by network traffic that does not
5704 * explicitly specify a network. This includes the default network, but also all VPNs that are
5705 * currently connected.
5706 *
5707 * Must be called on the handler thread.
5708 */
5709 private Network[] getDefaultNetworks() {
5710 ArrayList<Network> defaultNetworks = new ArrayList<>();
5711 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5712 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5713 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5714 defaultNetworks.add(nai.network);
5715 }
5716 }
5717 return defaultNetworks.toArray(new Network[0]);
5718 }
5719
5720 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005721 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5722 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005723 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005724 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005725 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005726 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005727 } catch (Exception ignored) {
5728 }
5729 }
5730
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005731 @Override
5732 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005733 int user = UserHandle.getUserId(Binder.getCallingUid());
5734 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005735 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005736 return mVpns.get(user).addAddress(address, prefixLength);
5737 }
5738 }
5739
5740 @Override
5741 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005742 int user = UserHandle.getUserId(Binder.getCallingUid());
5743 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005744 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005745 return mVpns.get(user).removeAddress(address, prefixLength);
5746 }
5747 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005748
5749 @Override
5750 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005751 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005752 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005753 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005754 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005755 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005756 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005757 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005758 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005759 }
5760 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005761 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005762
5763 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005764 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07005765 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005766 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005767 }
5768
5769 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005770 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5771 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5772 enforceKeepalivePermission();
5773 mKeepaliveTracker.startNattKeepalive(
5774 getNetworkAgentInfoForNetwork(network),
5775 intervalSeconds, messenger, binder,
5776 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5777 }
5778
5779 @Override
5780 public void stopKeepalive(Network network, int slot) {
5781 mHandler.sendMessage(mHandler.obtainMessage(
5782 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5783 }
5784
5785 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005786 public void factoryReset() {
5787 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005788
5789 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5790 return;
5791 }
5792
Robin Lee3b3dd942015-05-12 18:14:58 +01005793 final int userId = UserHandle.getCallingUserId();
5794
Stuart Scottf1fb3972015-04-02 18:00:02 -07005795 // Turn airplane mode off
5796 setAirplaneMode(false);
5797
Stuart Scotte3e314d2015-04-20 14:07:45 -07005798 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5799 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005800 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005801 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005802 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005803 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005804 }
5805
Stuart Scotte3e314d2015-04-20 14:07:45 -07005806 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005807 // Remove always-on package
5808 synchronized (mVpns) {
5809 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5810 if (alwaysOnPackage != null) {
5811 setAlwaysOnVpnPackage(userId, null, false);
5812 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5813 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005814
Hugo Benichi69744342017-11-27 10:57:16 +09005815 // Turn Always-on VPN off
5816 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5817 final long ident = Binder.clearCallingIdentity();
5818 try {
5819 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5820 mLockdownEnabled = false;
5821 setLockdownTracker(null);
5822 } finally {
5823 Binder.restoreCallingIdentity(ident);
5824 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005825 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005826
Hugo Benichi69744342017-11-27 10:57:16 +09005827 // Turn VPN off
5828 VpnConfig vpnConfig = getVpnConfig(userId);
5829 if (vpnConfig != null) {
5830 if (vpnConfig.legacy) {
5831 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5832 } else {
5833 // Prevent this app (packagename = vpnConfig.user) from initiating
5834 // VPN connections in the future without user intervention.
5835 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005836
Hugo Benichi69744342017-11-27 10:57:16 +09005837 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5838 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005839 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005840 }
5841 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005842
5843 Settings.Global.putString(mContext.getContentResolver(),
5844 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005845 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005846
Ricky Wai44dcbde2018-01-23 04:09:45 +00005847 @Override
5848 public byte[] getNetworkWatchlistConfigHash() {
5849 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
5850 if (nwm == null) {
5851 loge("Unable to get NetworkWatchlistManager");
5852 return null;
5853 }
5854 // Redirect it to network watchlist service to access watchlist file and calculate hash.
5855 return nwm.getWatchlistConfigHash();
5856 }
5857
Paul Jensencf4c2c62015-07-01 14:16:32 -04005858 @VisibleForTesting
5859 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5860 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5861 return new NetworkMonitor(context, handler, nai, defaultRequest);
5862 }
Erik Kline48f12f22016-04-14 17:30:59 +09005863
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005864 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005865 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5866 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005867 }
5868
5869 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005870 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5871 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5872 }
5873
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005874 @VisibleForTesting
5875 public boolean hasService(String name) {
5876 return ServiceManager.checkService(name) != null;
5877 }
5878
Hugo Benichi64901e52017-10-19 14:42:40 +09005879 @VisibleForTesting
5880 protected IpConnectivityMetrics.Logger metricsLogger() {
5881 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5882 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005883 }
5884
5885 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005886 int[] transports = nai.networkCapabilities.getTransportTypes();
5887 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005888 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005889
5890 private static boolean toBool(int encodedBoolean) {
5891 return encodedBoolean != 0; // Only 0 means false.
5892 }
5893
5894 private static int encodeBool(boolean b) {
5895 return b ? 1 : 0;
5896 }
mswest46386886f2018-03-12 10:34:34 -07005897
5898 @Override
5899 public void onShellCommand(FileDescriptor in, FileDescriptor out,
5900 FileDescriptor err, String[] args, ShellCallback callback,
5901 ResultReceiver resultReceiver) {
5902 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
5903 }
5904
5905 private class ShellCmd extends ShellCommand {
5906
5907 @Override
5908 public int onCommand(String cmd) {
5909 if (cmd == null) {
5910 return handleDefaultCommands(cmd);
5911 }
5912 final PrintWriter pw = getOutPrintWriter();
5913 try {
5914 switch (cmd) {
5915 case "airplane-mode":
5916 final String action = getNextArg();
5917 if ("enable".equals(action)) {
5918 setAirplaneMode(true);
5919 return 0;
5920 } else if ("disable".equals(action)) {
5921 setAirplaneMode(false);
5922 return 0;
5923 } else if (action == null) {
5924 final ContentResolver cr = mContext.getContentResolver();
5925 final int enabled = Settings.Global.getInt(cr,
5926 Settings.Global.AIRPLANE_MODE_ON);
5927 pw.println(enabled == 0 ? "disabled" : "enabled");
5928 return 0;
5929 } else {
5930 onHelp();
5931 return -1;
5932 }
5933 default:
5934 return handleDefaultCommands(cmd);
5935 }
5936 } catch (Exception e) {
5937 pw.println(e);
5938 }
5939 return -1;
5940 }
5941
5942 @Override
5943 public void onHelp() {
5944 PrintWriter pw = getOutPrintWriter();
5945 pw.println("Connectivity service commands:");
5946 pw.println(" help");
5947 pw.println(" Print this help text.");
5948 pw.println(" airplane-mode [enable|disable]");
5949 pw.println(" Turn airplane mode on or off.");
5950 pw.println(" airplane-mode");
5951 pw.println(" Get airplane mode.");
5952 }
5953 }
Erik Kline79c6d052018-03-21 07:18:33 -07005954}