blob: 9994462531b2aac8d90ee1fbc6a8fcdeec63eecc [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
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900241 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700242 @GuardedBy("mVpns")
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900243 protected final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700244
Hugo Benichi69744342017-11-27 10:57:16 +0900245 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
246 // a direct call to LockdownVpnTracker.isEnabled().
247 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700248 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900249 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700250 private LockdownVpnTracker mLockdownTracker;
251
Erik Klineda4bfa82015-04-30 12:58:40 +0900252 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700254 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700255 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700258 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700260 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800261 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700262 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900263 private NetworkPolicyManagerInternal mPolicyManagerInternal;
dalyk1fcb7392018-03-05 12:42:22 -0500264 private IIpConnectivityMetrics mIpConnectivityMetrics;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700265
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700266 private String mCurrentTcpBufferSizes;
267
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700268 private static final int ENABLED = 1;
269 private static final int DISABLED = 0;
270
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900271 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900272 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
273 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900274
Paul Jensenb10e37f2014-11-25 12:33:08 -0500275 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400276 // Tear down networks that have no chance (e.g. even if validated) of becoming
277 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500278 // all networks have been rematched against all NetworkRequests.
279 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400280 // Don't reap networks. This should be passed when some networks have not yet been
281 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500282 DONT_REAP
283 };
284
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900285 private enum UnneededFor {
286 LINGER, // Determine whether this network is unneeded and should be lingered.
287 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
288 }
289
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700290 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700291 * used internally to change our mobile data enabled flag
292 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700293 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700294
295 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700296 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700297 * from one net to another. Clear happens when we get a new
298 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
299 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700300 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700301 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700302
Robert Greenwalt434203a2010-10-11 16:00:27 -0700303 /**
304 * used internally to reload global proxy settings
305 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700306 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700307
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700308 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400309 * PAC manager has received new port.
310 */
311 private static final int EVENT_PROXY_HAS_CHANGED = 16;
312
Robert Greenwalte049c232014-04-11 15:53:27 -0700313 /**
314 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700315 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700316 */
317 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
318
Robert Greenwalt7b816022014-04-18 15:25:25 -0700319 /**
320 * used internally when registering NetworkAgents
321 * obj = Messenger
322 */
323 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
324
Robert Greenwalt9258c642014-03-26 16:47:06 -0700325 /**
326 * used to add a network request
327 * includes a NetworkRequestInfo
328 */
329 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
330
331 /**
332 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900333 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700334 * cancel it.
335 * includes a NetworkRequestInfo
336 */
337 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
338
339 /**
340 * used to add a network listener - no request
341 * includes a NetworkRequestInfo
342 */
343 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
344
345 /**
346 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400347 * arg1 = UID of caller
348 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700349 */
350 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
351
Robert Greenwalta67be032014-05-16 15:49:14 -0700352 /**
353 * used internally when registering NetworkFactories
354 * obj = Messenger
355 */
356 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
357
Robert Greenwalt27711812014-06-25 16:45:57 -0700358 /**
359 * used internally to expire a wakelock when transitioning
360 * from one net to another. Expire happens when we fail to find
361 * a new network (typically after 1 minute) -
362 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
363 * a replacement network.
364 */
365 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
366
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700367 /**
368 * Used internally to indicate the system is ready.
369 */
370 private static final int EVENT_SYSTEM_READY = 25;
371
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800372 /**
373 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400374 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800375 */
376 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
377
378 /**
379 * used to remove a pending intent and its associated network request.
380 * arg1 = UID of caller
381 * obj = PendingIntent
382 */
383 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
384
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900385 /**
386 * used to specify whether a network should be used even if unvalidated.
387 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
388 * arg2 = whether to remember this choice in the future (1 or 0)
389 * obj = network
390 */
391 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
392
393 /**
394 * used to ask the user to confirm a connection to an unvalidated network.
395 * obj = network
396 */
397 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700398
Erik Klineda4bfa82015-04-30 12:58:40 +0900399 /**
400 * used internally to (re)configure mobile data always-on settings.
401 */
402 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
403
Paul Jensen694f2b82015-06-17 14:15:39 -0400404 /**
405 * used to add a network listener with a pending intent
406 * obj = NetworkRequestInfo
407 */
408 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
409
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900410 /**
411 * used to specify whether a network should not be penalized when it becomes unvalidated.
412 */
413 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
414
415 /**
416 * used to trigger revalidation of a network.
417 */
418 private static final int EVENT_REVALIDATE_NETWORK = 36;
419
Erik Klinea24d4592018-01-11 21:07:29 +0900420 // Handle changes in Private DNS settings.
421 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
422
dalyk1fcb7392018-03-05 12:42:22 -0500423 // Handle private DNS validation status updates.
424 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
425
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900426 private static String eventName(int what) {
427 return sMagicDecoderRing.get(what, Integer.toString(what));
428 }
429
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900430 /** Handler thread used for both of the handlers below. */
431 @VisibleForTesting
432 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700433 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700434 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700435 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700436 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900437 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700438
Mike Lockwood0f79b542009-08-14 14:18:49 -0400439 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800440 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400441
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700442 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700443 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800444 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700445
Robert Greenwalt434203a2010-10-11 16:00:27 -0700446 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400447 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700448 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700449 private boolean mDefaultProxyDisabled = false;
450
Robert Greenwalt434203a2010-10-11 16:00:27 -0700451 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400452 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700453
Jason Monk602b2322013-07-03 17:04:33 -0400454 private PacManager mPacManager = null;
455
Erik Klineda4bfa82015-04-30 12:58:40 +0900456 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700457
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400458 private UserManager mUserManager;
459
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700460 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700461 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700462
Robert Greenwalt50393202011-06-21 17:26:14 -0700463 // the set of network types that can only be enabled by system/sig apps
464 List mProtectedNetworks;
465
John Spurlockbf991a82013-06-24 14:20:23 -0400466 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700467
Wink Savilleab9321d2013-06-29 21:10:57 -0700468 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400469
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900470 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900471 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900472 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900473
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700474 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800475 private static final int MIN_NET_ID = 100; // some reserved marks
476 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700477 private int mNextNetId = MIN_NET_ID;
478
Robert Greenwalt34524f02014-05-18 16:22:10 -0700479 // sequence number of NetworkRequests
480 private int mNextNetworkRequestId = 1;
481
Erik Kline7523eb32015-07-09 18:24:03 +0900482 // NetworkRequest activity String log entries.
483 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
484 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
485
Hugo Benichic2ae2872016-07-11 11:05:12 +0900486 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900487 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900488 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
489
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900490 private static final int MAX_WAKELOCK_LOGS = 20;
491 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900492 private int mTotalWakelockAcquisitions = 0;
493 private int mTotalWakelockReleases = 0;
494 private long mTotalWakelockDurationMs = 0;
495 private long mMaxWakelockDurationMs = 0;
496 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900497
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700498 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
499 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400500 private static class ValidationLog {
501 final Network mNetwork;
502 final String mNetworkExtraInfo;
503 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700504
Paul Jensen0808eb82016-06-03 13:51:21 -0400505 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
506 mNetwork = network;
507 mNetworkExtraInfo = networkExtraInfo;
508 mLog = log;
509 }
510 }
511 private final ArrayDeque<ValidationLog> mValidationLogs =
512 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
513
514 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900515 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700516 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
517 mValidationLogs.removeLast();
518 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400519 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700520 }
521 }
522
Hugo Benichif9fdf872016-07-28 17:53:06 +0900523 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900524
Erik Kline065ab6e2016-10-02 18:02:14 +0900525 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900526 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900527
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900528 @VisibleForTesting
529 final MultipathPolicyTracker mMultipathPolicyTracker;
530
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700531 /**
532 * Implements support for the legacy "one network per network type" model.
533 *
534 * We used to have a static array of NetworkStateTrackers, one for each
535 * network type, but that doesn't work any more now that we can have,
536 * for example, more that one wifi network. This class stores all the
537 * NetworkAgentInfo objects that support a given type, but the legacy
538 * API will only see the first one.
539 *
540 * It serves two main purposes:
541 *
542 * 1. Provide information about "the network for a given type" (since this
543 * API only supports one).
544 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
545 * the first network for a given type changes, or if the default network
546 * changes.
547 */
548 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900549
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900550 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900551 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900552
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700553 /**
554 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
555 * Each list holds references to all NetworkAgentInfos that are used to
556 * satisfy requests for that network type.
557 *
558 * This array is built out at startup such that an unsupported network
559 * doesn't get an ArrayList instance, making this a tristate:
560 * unsupported, supported but not active and active.
561 *
562 * The actual lists are populated when we scan the network types that
563 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900564 *
565 * Threading model:
566 * - addSupportedType() is only called in the constructor
567 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
568 * They are therefore not thread-safe with respect to each other.
569 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
570 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
571 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700572 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900573 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700574
575 public LegacyTypeTracker() {
576 mTypeLists = (ArrayList<NetworkAgentInfo>[])
577 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
578 }
579
580 public void addSupportedType(int type) {
581 if (mTypeLists[type] != null) {
582 throw new IllegalStateException(
583 "legacy list for type " + type + "already initialized");
584 }
585 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
586 }
587
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700588 public boolean isTypeSupported(int type) {
589 return isNetworkTypeValid(type) && mTypeLists[type] != null;
590 }
591
592 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900593 synchronized (mTypeLists) {
594 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
595 return mTypeLists[type].get(0);
596 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700597 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900598 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700599 }
600
Robert Greenwalt8d482522015-06-24 13:23:42 -0700601 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900602 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900603 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700604 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900605 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900606 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900607 }
608 }
609
610 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700611 public void add(int type, NetworkAgentInfo nai) {
612 if (!isTypeSupported(type)) {
613 return; // Invalid network type.
614 }
615 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
616
617 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
618 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700619 return;
620 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900621 synchronized (mTypeLists) {
622 list.add(nai);
623 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900624
625 // 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 +0900626 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900627 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700628 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
629 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700630 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700631 }
632
Lorenzo Colittia793a672014-07-31 23:20:17 +0900633 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900634 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900635 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
636 if (list == null || list.isEmpty()) {
637 return;
638 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900639 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900640
Hugo Benichi78caa2582016-06-21 09:48:07 +0900641 synchronized (mTypeLists) {
642 if (!list.remove(nai)) {
643 return;
644 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900645 }
646
Robert Greenwalt8d482522015-06-24 13:23:42 -0700647 final DetailedState state = DetailedState.DISCONNECTED;
648
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900649 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700650 maybeLogBroadcast(nai, state, type, wasDefault);
651 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900652 }
653
654 if (!list.isEmpty() && wasFirstNetwork) {
655 if (DBG) log("Other network available for type " + type +
656 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900657 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700658 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
659 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900660 }
661 }
662
663 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900664 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
665 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700666 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900667 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700668 }
669 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700670
Robert Greenwalt8d482522015-06-24 13:23:42 -0700671 // send out another legacy broadcast - currently only used for suspend/unsuspend
672 // toggle
673 public void update(NetworkAgentInfo nai) {
674 final boolean isDefault = isDefaultNetwork(nai);
675 final DetailedState state = nai.networkInfo.getDetailedState();
676 for (int type = 0; type < mTypeLists.length; type++) {
677 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700678 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900679 final boolean isFirst = contains && (nai == list.get(0));
680 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700681 maybeLogBroadcast(nai, state, type, isDefault);
682 sendLegacyNetworkBroadcast(nai, state, type);
683 }
684 }
685 }
686
Lorenzo Colittia793a672014-07-31 23:20:17 +0900687 private String naiToString(NetworkAgentInfo nai) {
688 String name = (nai != null) ? nai.name() : "null";
689 String state = (nai.networkInfo != null) ?
690 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
691 "???/???";
692 return name + " " + state;
693 }
694
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700695 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900696 pw.println("mLegacyTypeTracker:");
697 pw.increaseIndent();
698 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700699 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900700 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700701 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900702 pw.println();
703 pw.println("Current state:");
704 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900705 synchronized (mTypeLists) {
706 for (int type = 0; type < mTypeLists.length; type++) {
707 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
708 for (NetworkAgentInfo nai : mTypeLists[type]) {
709 pw.println(type + " " + naiToString(nai));
710 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900711 }
712 }
713 pw.decreaseIndent();
714 pw.decreaseIndent();
715 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700716 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700717 }
718 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
719
Vishnu Nair5c010902017-10-26 10:08:50 -0700720 /**
721 * Helper class which parses out priority arguments and dumps sections according to their
722 * priority. If priority arguments are omitted, function calls the legacy dump command.
723 */
724 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
725 @Override
726 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
727 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
728 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
729 }
730
731 @Override
732 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
733 doDump(fd, pw, args, asProto);
734 }
735
736 @Override
737 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
738 doDump(fd, pw, args, asProto);
739 }
740 };
741
Jeff Sharkey899223b2012-08-04 15:24:58 -0700742 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700743 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900744 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
745 }
746
747 @VisibleForTesting
748 protected ConnectivityService(Context context, INetworkManagementService netManager,
749 INetworkStatsService statsService, INetworkPolicyManager policyManager,
750 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800751 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800752
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900753 mSystemProperties = getSystemProperties();
754
Hugo Benichif9fdf872016-07-28 17:53:06 +0900755 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900756 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900757 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900758 mNetworkRequests.put(mDefaultRequest, defaultNRI);
759 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900760
Chalard Jeandda156a2018-01-10 21:19:32 +0900761 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900762 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700763
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900764 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900765 mHandlerThread.start();
766 mHandler = new InternalHandler(mHandlerThread.getLooper());
767 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700768
Jeremy Joslin79294842014-12-03 17:15:28 -0800769 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
770 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
771
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900772 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900773
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700774 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700775 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800776 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700777 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900778 mPolicyManagerInternal = checkNotNull(
779 LocalServices.getService(NetworkPolicyManagerInternal.class),
780 "missing NetworkPolicyManagerInternal");
781
Jeff Sharkey82f85212012-08-24 11:17:25 -0700782 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700783 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700784
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700785 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900786 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700787 } catch (RemoteException e) {
788 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700789 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700790 }
791
792 final PowerManager powerManager = (PowerManager) context.getSystemService(
793 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700794 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
795 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
796 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800797 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700798
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700799 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700800
Wink Saville51f456f2013-04-23 14:26:51 -0700801 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900802 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700803 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700804 String[] naStrings = context.getResources().getStringArray(
805 com.android.internal.R.array.networkAttributes);
806 for (String naString : naStrings) {
807 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700808 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700809 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700810 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800811 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700812 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700813 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700814 }
Wink Saville51f456f2013-04-23 14:26:51 -0700815 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
816 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
817 n.type);
818 continue;
819 }
Wink Saville975c8482011-04-07 14:23:45 -0700820 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800821 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700822 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700823 continue;
824 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700825 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700826
Wink Saville975c8482011-04-07 14:23:45 -0700827 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700828 mNetworksDefined++;
829 } catch(Exception e) {
830 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700831 }
832 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700833
834 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
835 if (mNetConfigs[TYPE_VPN] == null) {
836 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
837 // don't need to add TYPE_VPN to mNetConfigs.
838 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
839 mNetworksDefined++; // used only in the log() statement below.
840 }
841
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900842 // Do the same for Ethernet, since it's often not specified in the configs, although many
843 // devices can use it via USB host adapters.
844 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
845 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
846 mNetworksDefined++;
847 }
848
Wink Saville5e56bc52013-07-29 15:00:57 -0700849 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700850
Robert Greenwalt50393202011-06-21 17:26:14 -0700851 mProtectedNetworks = new ArrayList<Integer>();
852 int[] protectedNetworks = context.getResources().getIntArray(
853 com.android.internal.R.array.config_protectedNetworks);
854 for (int p : protectedNetworks) {
855 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
856 mProtectedNetworks.add(p);
857 } else {
858 if (DBG) loge("Ignoring protectedNetwork " + p);
859 }
860 }
861
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900862 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
863 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700864
Erik Kline47222fc2017-04-30 19:36:15 +0900865 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800866
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700867 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
868
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700869 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700870 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100871 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700872 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700873 intentFilter.addAction(Intent.ACTION_USER_ADDED);
874 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000875 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700876 mContext.registerReceiverAsUser(
877 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000878 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
879 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900880
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700881 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700882 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700883 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700884 } catch (RemoteException e) {
885 loge("Error registering observer :" + e);
886 }
887
Erik Klineda4bfa82015-04-30 12:58:40 +0900888 mSettingsObserver = new SettingsObserver(mContext, mHandler);
889 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800890
John Spurlockbf991a82013-06-24 14:20:23 -0400891 mDataConnectionStats = new DataConnectionStats(mContext);
892 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400893
Jason Monkdecd2952013-10-10 14:02:51 -0400894 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700895
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400896 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900897
898 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900899 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
900 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900901
902 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
903 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
904 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
905 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
906 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
907 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
908 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900909
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900910 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900911 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900912 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900913
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900914 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
915
Erik Kline1742fe12017-12-13 19:40:49 +0900916 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900917 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700919
Erik Kline47222fc2017-04-30 19:36:15 +0900920 private Tethering makeTethering() {
921 // TODO: Move other elements into @Overridden getters.
Erik Kline7a26ba32018-03-09 14:18:02 +0900922 final TetheringDependencies deps = new TetheringDependencies() {
923 @Override
924 public boolean isTetheringSupported() {
925 return ConnectivityService.this.isTetheringSupported();
926 }
927 };
Erik Kline47222fc2017-04-30 19:36:15 +0900928 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
929 IoThread.get().getLooper(), new MockableSystemProperties(),
930 deps);
931 }
932
Chalard Jean26400492018-04-18 20:18:38 +0900933 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
934 final NetworkCapabilities netCap = new NetworkCapabilities();
935 netCap.addCapability(NET_CAPABILITY_INTERNET);
936 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
937 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
938 netCap.setSingleUid(uid);
939 return netCap;
940 }
941
Chalard Jeandda156a2018-01-10 21:19:32 +0900942 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900943 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900944 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900945 netCap.addCapability(NET_CAPABILITY_INTERNET);
946 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900947 if (transportType > -1) {
948 netCap.addTransportType(transportType);
949 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900950 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900951 }
952
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900953 // Used only for testing.
954 // TODO: Delete this and either:
Erik Kline79c6d052018-03-21 07:18:33 -0700955 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900956 // changing ContentResolver to make registerContentObserver non-final).
957 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
958 // by subclassing SettingsObserver.
959 @VisibleForTesting
960 void updateMobileDataAlwaysOn() {
961 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
962 }
963
Erik Kline79c6d052018-03-21 07:18:33 -0700964 // See FakeSettingsProvider comment above.
965 @VisibleForTesting
966 void updatePrivateDnsSettings() {
967 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
968 }
969
Erik Klineda4bfa82015-04-30 12:58:40 +0900970 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900971 final boolean enable = toBool(Settings.Global.getInt(
972 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900973 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
974 if (enable == isEnabled) {
975 return; // Nothing to do.
976 }
977
978 if (enable) {
979 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900980 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900981 } else {
982 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
983 }
984 }
985
986 private void registerSettingsCallbacks() {
987 // Watch for global HTTP proxy changes.
988 mSettingsObserver.observe(
989 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
990 EVENT_APPLY_GLOBAL_HTTP_PROXY);
991
992 // Watch for whether or not to keep mobile data always on.
993 mSettingsObserver.observe(
994 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
995 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
996 }
997
Erik Klinea24d4592018-01-11 21:07:29 +0900998 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline79c6d052018-03-21 07:18:33 -0700999 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1000 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +09001001 }
1002 }
1003
Robert Greenwalt34524f02014-05-18 16:22:10 -07001004 private synchronized int nextNetworkRequestId() {
1005 return mNextNetworkRequestId++;
1006 }
1007
Paul Jensen67b0b072015-06-10 11:22:17 -04001008 @VisibleForTesting
1009 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001010 synchronized (mNetworkForNetId) {
1011 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1012 int netId = mNextNetId;
1013 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1014 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001015 if (!mNetIdInUse.get(netId)) {
1016 mNetIdInUse.put(netId, true);
1017 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001018 }
1019 }
1020 }
1021 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001022 }
1023
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001024 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001025 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001026 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1027 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001028 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001029 state = nai.getNetworkState();
1030 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001031 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001032 final NetworkInfo info = new NetworkInfo(networkType, 0,
1033 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001034 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1035 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001036 final NetworkCapabilities capabilities = new NetworkCapabilities();
1037 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1038 !info.isRoaming());
1039 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001040 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001041 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001042 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001043 return state;
1044 } else {
1045 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001046 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001047 }
1048
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001049 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
1050 if (network == null) {
1051 return null;
1052 }
Erik Kline79c6d052018-03-21 07:18:33 -07001053 return getNetworkAgentInfoForNetId(network.netId);
1054 }
1055
1056 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001057 synchronized (mNetworkForNetId) {
Erik Kline79c6d052018-03-21 07:18:33 -07001058 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001059 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001060 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001061
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001062 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001063 synchronized (mVpns) {
1064 if (!mLockdownEnabled) {
1065 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001066 Vpn vpn = mVpns.get(user);
1067 if (vpn != null && vpn.appliesToUid(uid)) {
1068 return vpn.getUnderlyingNetworks();
1069 }
1070 }
1071 }
1072 return null;
1073 }
1074
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001075 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001076 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001077
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001078 final Network[] networks = getVpnUnderlyingNetworks(uid);
1079 if (networks != null) {
1080 // getUnderlyingNetworks() returns:
1081 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1082 // empty array => the VPN explicitly said "no default network".
1083 // non-empty array => the VPN specified one or more default networks; we use the
1084 // first one.
1085 if (networks.length > 0) {
1086 nai = getNetworkAgentInfoForNetwork(networks[0]);
1087 } else {
1088 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001089 }
1090 }
1091
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001092 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001093 return nai.getNetworkState();
1094 } else {
1095 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001096 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001097 }
1098
1099 /**
1100 * Check if UID should be blocked from using the network with the given LinkProperties.
1101 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001102 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1103 boolean ignoreBlocked) {
1104 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001105 if (ignoreBlocked) {
1106 return false;
1107 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001108 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001109 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1110 if (isSystem(uid)) {
1111 return false;
1112 }
Robin Lee17e61832016-05-09 13:46:28 +01001113 synchronized (mVpns) {
1114 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1115 if (vpn != null && vpn.isBlockingUid(uid)) {
1116 return true;
1117 }
1118 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001119 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001120 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001121 }
1122
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001123 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001124 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1125 return;
1126 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001127 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001128 synchronized (mBlockedAppUids) {
1129 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001130 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001131 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001132 blocked = false;
1133 } else {
1134 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001135 }
1136 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001137 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1138 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1139 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001140 }
1141
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001142 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001143 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1144 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001145 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001146 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001147 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001148 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1149
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001150 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001151 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001152 }
Hugo Benichi69744342017-11-27 10:57:16 +09001153 synchronized (mVpns) {
1154 if (mLockdownTracker != null) {
1155 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1156 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001157 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001158 }
1159
1160 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 * Return NetworkInfo for the active (i.e., connected) network interface.
1162 * It is assumed that at most one network is active at a time. If more
1163 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001164 * @return the info for the active network, or {@code null} if none is
1165 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001167 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001169 enforceAccessPermission();
1170 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001171 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001172 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001173 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1174 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 }
1176
Paul Jensen31a94f42015-02-13 14:18:39 -05001177 @Override
1178 public Network getActiveNetwork() {
1179 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001180 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001181 }
1182
1183 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001184 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001185 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001186 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001187 }
1188
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001189 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001190 final int user = UserHandle.getUserId(uid);
1191 int vpnNetId = NETID_UNSET;
1192 synchronized (mVpns) {
1193 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001194 // TODO : now that capabilities contain the UID, the appliesToUid test should
1195 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001196 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1197 }
1198 NetworkAgentInfo nai;
1199 if (vpnNetId != NETID_UNSET) {
Erik Kline79c6d052018-03-21 07:18:33 -07001200 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001201 if (nai != null) {
1202 final NetworkCapabilities requiredCaps =
1203 createDefaultNetworkCapabilitiesForUid(uid);
1204 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1205 return nai.network;
1206 }
1207 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001208 }
1209 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001210 if (nai != null
1211 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1212 nai = null;
1213 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001214 return nai != null ? nai.network : null;
1215 }
1216
Lorenzo Colitti18660282016-07-04 12:55:44 +09001217 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001218 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1219 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001220 final int uid = Binder.getCallingUid();
1221 NetworkState state = getUnfilteredActiveNetworkState(uid);
1222 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001223 }
1224
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001225 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001226 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001227 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001228 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001229 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001230 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001231 }
1232
1233 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 public NetworkInfo getNetworkInfo(int networkType) {
1235 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001236 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001237 if (getVpnUnderlyingNetworks(uid) != null) {
1238 // A VPN is active, so we may need to return one of its underlying networks. This
1239 // information is not available in LegacyTypeTracker, so we have to get it from
1240 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001241 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001242 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001243 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001244 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001245 }
1246 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001247 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001248 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 }
1250
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001251 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001252 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001253 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001254 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001255 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001256 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001257 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001258 return state.networkInfo;
1259 } else {
1260 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001261 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001262 }
1263
1264 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 public NetworkInfo[] getAllNetworkInfo() {
1266 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001267 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001268 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1269 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001270 NetworkInfo info = getNetworkInfo(networkType);
1271 if (info != null) {
1272 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001275 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 }
1277
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001278 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001279 public Network getNetworkForType(int networkType) {
1280 enforceAccessPermission();
1281 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001282 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1283 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001284 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001285 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001286 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001287 }
1288
1289 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001290 public Network[] getAllNetworks() {
1291 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001292 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001293 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001294 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001295 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001296 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001297 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001298 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001299 }
1300
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001301 @Override
1302 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1303 // The basic principle is: if an app's traffic could possibly go over a
1304 // network, without the app doing anything multinetwork-specific,
1305 // (hence, by "default"), then include that network's capabilities in
1306 // the array.
1307 //
1308 // In the normal case, app traffic only goes over the system's default
1309 // network connection, so that's the only network returned.
1310 //
1311 // With a VPN in force, some app traffic may go into the VPN, and thus
1312 // over whatever underlying networks the VPN specifies, while other app
1313 // traffic may go over the system default network (e.g.: a split-tunnel
1314 // VPN, or an app disallowed by the VPN), so the set of networks
1315 // returned includes the VPN's underlying networks and the system
1316 // default.
1317 enforceAccessPermission();
1318
1319 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1320
1321 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001322 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001323 if (nc != null) {
1324 result.put(nai.network, nc);
1325 }
1326
Hugo Benichi69744342017-11-27 10:57:16 +09001327 synchronized (mVpns) {
1328 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001329 Vpn vpn = mVpns.get(userId);
1330 if (vpn != null) {
1331 Network[] networks = vpn.getUnderlyingNetworks();
1332 if (networks != null) {
1333 for (Network network : networks) {
1334 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001335 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001336 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001337 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001338 }
1339 }
1340 }
1341 }
1342 }
1343 }
1344
1345 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1346 out = result.values().toArray(out);
1347 return out;
1348 }
1349
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001350 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001351 public boolean isNetworkSupported(int networkType) {
1352 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001353 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001354 }
1355
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001356 /**
1357 * Return LinkProperties for the active (i.e., connected) default
1358 * network interface. It is assumed that at most one default network
1359 * is active at a time. If more than one is active, it is indeterminate
1360 * which will be returned.
1361 * @return the ip properties for the active network, or {@code null} if
1362 * none is active
1363 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001364 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001365 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001366 enforceAccessPermission();
1367 final int uid = Binder.getCallingUid();
1368 NetworkState state = getUnfilteredActiveNetworkState(uid);
1369 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001370 }
1371
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001372 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001373 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001374 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001375 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1376 if (nai != null) {
1377 synchronized (nai) {
1378 return new LinkProperties(nai.linkProperties);
1379 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001380 }
1381 return null;
1382 }
1383
Robert Greenwalt12e67352014-05-13 21:41:06 -07001384 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001385 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001386 public LinkProperties getLinkProperties(Network network) {
1387 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001388 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1389 }
1390
1391 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1392 if (nai == null) {
1393 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001394 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001395 synchronized (nai) {
1396 return new LinkProperties(nai.linkProperties);
1397 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001398 }
1399
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001400 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001401 if (nai != null) {
1402 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001403 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001404 return networkCapabilitiesRestrictedForCallerPermissions(
1405 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001406 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001407 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001408 }
1409 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001410 return null;
1411 }
1412
1413 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001414 public NetworkCapabilities getNetworkCapabilities(Network network) {
1415 enforceAccessPermission();
1416 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1417 }
1418
Chalard Jeanb03a6222018-04-11 21:09:10 +09001419 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001420 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001421 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001422 if (!checkSettingsPermission(callerPid, callerUid)) {
1423 newNc.setUids(null);
1424 newNc.setSSID(null);
1425 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001426 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001427 }
1428
Chalard Jeanb552c462018-02-21 18:43:54 +09001429 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1430 if (!checkSettingsPermission()) {
1431 nc.setSingleUid(Binder.getCallingUid());
1432 }
1433 }
1434
Chalard Jean26aa91a2018-03-20 19:13:57 +09001435 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1436 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1437 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1438 }
1439 }
1440
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001441 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001442 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001443 // Require internal since we're handing out IMSI details
1444 enforceConnectivityInternalPermission();
1445
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001446 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001447 for (Network network : getAllNetworks()) {
1448 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1449 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001450 // TODO (b/73321673) : NetworkState contains a copy of the
1451 // NetworkCapabilities, which may contain UIDs of apps to which the
1452 // network applies. Should the UIDs be cleared so as not to leak or
1453 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001454 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001455 }
1456 }
1457 return result.toArray(new NetworkState[result.size()]);
1458 }
1459
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001460 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001461 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001462 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001463 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1464 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1465 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001466 }
1467
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001468 @Override
1469 public boolean isActiveNetworkMetered() {
1470 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001471
Eric Enslenc81ef192018-02-07 18:03:53 -08001472 final int uid = Binder.getCallingUid();
1473 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001474 if (caps != null) {
1475 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1476 } else {
1477 // Always return the most conservative value
1478 return true;
1479 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001480 }
1481
Jeff Sharkey216c1812012-08-05 14:29:23 -07001482 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1483 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001484 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001485 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001486 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001487 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001488 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001489
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001490 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 * Ensure that a network route exists to deliver traffic to the specified
1492 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001493 * @param networkType the type of the network over which traffic to the
1494 * specified host is to be routed
1495 * @param hostAddress the IP address of the host to which the route is
1496 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 * @return {@code true} on success, {@code false} on failure
1498 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001499 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001500 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001502 if (mProtectedNetworks.contains(networkType)) {
1503 enforceConnectivityInternalPermission();
1504 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001505
Chad Brubakerc0234532014-02-14 13:24:29 -08001506 InetAddress addr;
1507 try {
1508 addr = InetAddress.getByAddress(hostAddress);
1509 } catch (UnknownHostException e) {
1510 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1511 return false;
1512 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001515 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 return false;
1517 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001518
1519 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1520 if (nai == null) {
1521 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1522 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1523 } else {
1524 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1525 }
1526 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001527 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001528
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001529 DetailedState netState;
1530 synchronized (nai) {
1531 netState = nai.networkInfo.getDetailedState();
1532 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001533
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001534 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001535 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001536 log("requestRouteToHostAddress on down network "
1537 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001538 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001539 }
1540 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001542
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001543 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001544 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001545 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001546 LinkProperties lp;
1547 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001548 synchronized (nai) {
1549 lp = nai.linkProperties;
1550 netId = nai.network.netId;
1551 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001552 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001553 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1554 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001555 } finally {
1556 Binder.restoreCallingIdentity(token);
1557 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001558 }
1559
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001560 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001561 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001562 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001563 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001564 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001565 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001566 if (bestRoute.getGateway().equals(addr)) {
1567 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001568 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001569 } else {
1570 // if we will connect to this through another route, add a direct route
1571 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001572 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001573 }
1574 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001575 if (DBG) log("Adding legacy route " + bestRoute +
1576 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001577 try {
1578 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1579 } catch (Exception e) {
1580 // never crash - catch them all
1581 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001582 return false;
1583 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001584 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 }
1586
dalyk1fcb7392018-03-05 12:42:22 -05001587 @VisibleForTesting
1588 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1589 @Override
1590 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1591 String hostname, boolean validated) {
1592 try {
1593 mHandler.sendMessage(mHandler.obtainMessage(
1594 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1595 new PrivateDnsValidationUpdate(netId,
1596 InetAddress.parseNumericAddress(ipAddress),
1597 hostname, validated)));
1598 } catch (IllegalArgumentException e) {
1599 loge("Error parsing ip address in validation event");
1600 }
1601 }
1602 };
1603
1604 @VisibleForTesting
1605 protected void registerNetdEventCallback() {
1606 mIpConnectivityMetrics =
1607 (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1608 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1609 if (mIpConnectivityMetrics == null) {
1610 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
1611 }
1612
1613 try {
1614 mIpConnectivityMetrics.addNetdEventCallback(
1615 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1616 mNetdEventCallback);
1617 } catch (Exception e) {
1618 loge("Error registering netd callback: " + e);
1619 }
1620 }
1621
Jeff Sharkey75d31892018-01-18 22:01:59 +09001622 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001623 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001624 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001625 // TODO: notify UID when it has requested targeted updates
1626 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001627 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001628 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001629 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001630 if (restrictBackground) {
1631 log("onRestrictBackgroundChanged(true): disabling tethering");
1632 mTethering.untetherAll();
1633 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001634 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001635 };
1636
Robin Lee3b3dd942015-05-12 18:14:58 +01001637 /**
1638 * Require that the caller is either in the same user or has appropriate permission to interact
1639 * across users.
1640 *
1641 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1642 */
1643 private void enforceCrossUserPermission(int userId) {
1644 if (userId == UserHandle.getCallingUserId()) {
1645 // Not a cross-user call.
1646 return;
1647 }
1648 mContext.enforceCallingOrSelfPermission(
1649 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1650 "ConnectivityService");
1651 }
1652
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001653 private void enforceInternetPermission() {
1654 mContext.enforceCallingOrSelfPermission(
1655 android.Manifest.permission.INTERNET,
1656 "ConnectivityService");
1657 }
1658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001660 mContext.enforceCallingOrSelfPermission(
1661 android.Manifest.permission.ACCESS_NETWORK_STATE,
1662 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 }
1664
1665 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001666 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 }
1668
Charles He36738632017-05-15 17:07:18 +01001669 private void enforceSettingsPermission() {
1670 mContext.enforceCallingOrSelfPermission(
1671 android.Manifest.permission.NETWORK_SETTINGS,
1672 "ConnectivityService");
1673 }
1674
Chalard Jeanb552c462018-02-21 18:43:54 +09001675 private boolean checkSettingsPermission() {
1676 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1677 android.Manifest.permission.NETWORK_SETTINGS);
1678 }
1679
1680 private boolean checkSettingsPermission(int pid, int uid) {
1681 return PERMISSION_GRANTED == mContext.checkPermission(
1682 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1683 }
1684
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001685 private void enforceTetherAccessPermission() {
1686 mContext.enforceCallingOrSelfPermission(
1687 android.Manifest.permission.ACCESS_NETWORK_STATE,
1688 "ConnectivityService");
1689 }
1690
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001691 private void enforceConnectivityInternalPermission() {
1692 mContext.enforceCallingOrSelfPermission(
1693 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1694 "ConnectivityService");
1695 }
1696
Hugo Benichi514da602016-07-19 15:59:27 +09001697 private void enforceConnectivityRestrictedNetworksPermission() {
1698 try {
1699 mContext.enforceCallingOrSelfPermission(
1700 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1701 "ConnectivityService");
1702 return;
1703 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1704 enforceConnectivityInternalPermission();
1705 }
1706
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001707 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001708 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001709 }
1710
Lorenzo Colitti18660282016-07-04 12:55:44 +09001711 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001712 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001713 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001714 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001715 }
1716
1717 private void sendInetConditionBroadcast(NetworkInfo info) {
1718 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1719 }
1720
Wink Saville628b0852011-08-04 15:01:58 -07001721 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001722 synchronized (mVpns) {
1723 if (mLockdownTracker != null) {
1724 info = new NetworkInfo(info);
1725 mLockdownTracker.augmentNetworkInfo(info);
1726 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001727 }
1728
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001729 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001730 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001731 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 if (info.isFailover()) {
1733 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1734 info.setFailover(false);
1735 }
1736 if (info.getReason() != null) {
1737 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1738 }
1739 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001740 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1741 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001743 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001744 return intent;
1745 }
1746
1747 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1748 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1749 }
1750
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001751 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001752 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1753 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1754 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001755 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001756 final long ident = Binder.clearCallingIdentity();
1757 try {
1758 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1759 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1760 } finally {
1761 Binder.restoreCallingIdentity(ident);
1762 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001763 }
1764
Mike Lockwood0f79b542009-08-14 14:18:49 -04001765 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001766 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001767 if (!mSystemReady) {
1768 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001769 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001770 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001771 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001772 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001773 }
1774
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001775 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001776 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001777 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001778 final NetworkInfo ni = intent.getParcelableExtra(
1779 ConnectivityManager.EXTRA_NETWORK_INFO);
1780 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1781 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1782 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001783 } else {
1784 BroadcastOptions opts = BroadcastOptions.makeBasic();
1785 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1786 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001787 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001788 final IBatteryStats bs = BatteryStatsService.getService();
1789 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001790 bs.noteConnectivityChanged(intent.getIntExtra(
1791 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1792 ni != null ? ni.getState().toString() : "?");
1793 } catch (RemoteException e) {
1794 }
Chad Brubakerac925012018-03-08 10:37:09 -08001795 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001796 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001797 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001798 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001799 } finally {
1800 Binder.restoreCallingIdentity(ident);
1801 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001802 }
1803 }
1804
1805 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001806 loadGlobalProxy();
dalyk1fcb7392018-03-05 12:42:22 -05001807 registerNetdEventCallback();
Wink Saville948282b2013-08-29 08:55:16 -07001808
Hugo Benichi20035e02017-04-26 14:53:28 +09001809 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001810 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001811 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001812 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001813 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001814 }
1815 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001816 // load the global proxy at startup
1817 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001818
Robin Lee244ce8e2016-01-05 18:03:46 +00001819 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1820 // for user to unlock device too.
1821 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001822
Erik Klineda4bfa82015-04-30 12:58:40 +09001823 // Configure whether mobile data is always on.
1824 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1825
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001826 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001827
1828 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 }
1830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001832 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001833 *
1834 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001835 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001836 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001837 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1838 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001839
1840 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001841 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001842
Robert Greenwalt7b816022014-04-18 15:25:25 -07001843 if (networkAgent.networkCapabilities.hasTransport(
1844 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001845 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1846 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001847 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001848 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001849 } else if (networkAgent.networkCapabilities.hasTransport(
1850 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001851 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1852 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001853 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001854 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001855 } else {
1856 // do not track any other networks
1857 timeout = 0;
1858 }
1859
Robert Greenwalt7b816022014-04-18 15:25:25 -07001860 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001861 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001862 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001863 } catch (Exception e) {
1864 // You shall not crash!
1865 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001866 }
1867 }
1868 }
1869
1870 /**
1871 * Remove data activity tracking when network disconnects.
1872 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001873 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1874 final String iface = networkAgent.linkProperties.getInterfaceName();
1875 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001876
Robert Greenwalt7b816022014-04-18 15:25:25 -07001877 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1878 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001879 try {
1880 // the call fails silently if no idletimer setup for this interface
1881 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001882 } catch (Exception e) {
1883 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001884 }
1885 }
1886 }
1887
1888 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001889 * Reads the network specific MTU size from reources.
1890 * and set it on it's iface.
1891 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001892 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1893 final String iface = newLp.getInterfaceName();
1894 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001895 if (oldLp == null && mtu == 0) {
1896 // Silently ignore unset MTU value.
1897 return;
1898 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001899 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1900 if (VDBG) log("identical MTU - not setting");
1901 return;
1902 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001903 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001904 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001905 return;
1906 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001907
w1997615afd812014-08-05 15:18:11 -07001908 // Cannot set MTU without interface name
1909 if (TextUtils.isEmpty(iface)) {
1910 loge("Setting MTU size with null iface.");
1911 return;
1912 }
1913
Robert Greenwalt7b816022014-04-18 15:25:25 -07001914 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001915 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001916 mNetd.setMtu(iface, mtu);
1917 } catch (Exception e) {
1918 Slog.e(TAG, "exception in setMtu()" + e);
1919 }
1920 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001921
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001922 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001923 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1924
1925 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001926 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001927 protected MockableSystemProperties getSystemProperties() {
1928 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001929 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001930
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001931 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1932 if (isDefaultNetwork(nai) == false) {
1933 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001934 }
1935
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001936 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1937 String[] values = null;
1938 if (tcpBufferSizes != null) {
1939 values = tcpBufferSizes.split(",");
1940 }
1941
1942 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001943 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001944 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1945 values = tcpBufferSizes.split(",");
1946 }
1947
1948 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1949
1950 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001951 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001952
1953 final String prefix = "/sys/kernel/ipv4/tcp_";
1954 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1955 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1956 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1957 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1958 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1959 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1960 mCurrentTcpBufferSizes = tcpBufferSizes;
1961 } catch (IOException e) {
1962 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001963 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001964
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001965 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001966 Settings.Global.TCP_DEFAULT_INIT_RWND,
1967 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001968 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1969 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001970 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001971 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001972 }
1973
Robert Greenwalt562cc542014-05-15 18:07:26 -07001974 @Override
1975 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001976 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001977 NETWORK_RESTORE_DELAY_PROP_NAME);
1978 if(restoreDefaultNetworkDelayStr != null &&
1979 restoreDefaultNetworkDelayStr.length() != 0) {
1980 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001981 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001982 } catch (NumberFormatException e) {
1983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001985 // if the system property isn't set, use the value for the apn type
1986 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1987
1988 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1989 (mNetConfigs[networkType] != null)) {
1990 ret = mNetConfigs[networkType].restoreTime;
1991 }
1992 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 }
1994
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001995 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001996 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001997 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001998 }
1999 return false;
2000 }
2001
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002002 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2003 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2004 final long DIAG_TIME_MS = 5000;
2005 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2006 // Start gathering diagnostic information.
2007 netDiags.add(new NetworkDiagnostics(
2008 nai.network,
2009 new LinkProperties(nai.linkProperties), // Must be a copy.
2010 DIAG_TIME_MS));
2011 }
2012
2013 for (NetworkDiagnostics netDiag : netDiags) {
2014 pw.println();
2015 netDiag.waitForMeasurements();
2016 netDiag.dump(pw);
2017 }
2018 }
2019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002021 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002022 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2023 }
2024
2025 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002026 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002027 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002028 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002029
Erik Kline7747fd42017-05-12 16:52:48 +09002030 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002031 dumpNetworkDiagnostics(pw);
2032 return;
Erik Klineee363c42017-05-29 09:11:03 +09002033 } else if (argsContain(args, TETHERING_ARG)) {
2034 mTethering.dump(fd, pw, args);
2035 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002036 }
Erik Kline379747a2015-06-05 17:47:34 +09002037
Lorenzo Colittie3805462015-06-03 11:18:24 +09002038 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002039 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002040 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002041 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002042 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002043 pw.println();
2044
Paul Jensen85cf78e2015-06-25 13:25:07 -04002045 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002046 pw.print("Active default network: ");
2047 if (defaultNai == null) {
2048 pw.println("none");
2049 } else {
2050 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002052 pw.println();
2053
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002054 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002055 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002056 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2057 pw.println(nai.toString());
2058 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002059 pw.println(String.format(
2060 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2061 nai.numForegroundNetworkRequests(),
2062 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2063 nai.numBackgroundNetworkRequests(),
2064 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002065 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002066 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2067 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002068 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002069 pw.decreaseIndent();
2070 pw.println("Lingered:");
2071 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002072 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002073 pw.decreaseIndent();
2074 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002075 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002076 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002077 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002078
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002079 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002080 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002081 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2082 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002083 }
2084 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002085 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002086
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002087 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002088
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002089 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002090 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002091
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002092 pw.println();
2093 mKeepaliveTracker.dump(pw);
2094
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002095 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002096 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002097
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002098 pw.println();
2099 mMultipathPolicyTracker.dump(pw);
2100
Erik Kline7747fd42017-05-12 16:52:48 +09002101 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002102 pw.println();
2103 synchronized (mValidationLogs) {
2104 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002105 for (ValidationLog p : mValidationLogs) {
2106 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002107 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002108 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002109 pw.decreaseIndent();
2110 }
2111 }
Erik Kline7523eb32015-07-09 18:24:03 +09002112
2113 pw.println();
2114 pw.println("mNetworkRequestInfoLogs (most recent first):");
2115 pw.increaseIndent();
2116 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2117 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002118
2119 pw.println();
2120 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2121 pw.increaseIndent();
2122 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2123 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002124
2125 pw.println();
2126 pw.println("NetTransition WakeLock activity (most recent first):");
2127 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002128 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2129 pw.println("total releases: " + mTotalWakelockReleases);
2130 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2131 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2132 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2133 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2134 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2135 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002136 mWakelockLogs.reverseDump(fd, pw, args);
2137 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 }
2140
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002141 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002142 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002143 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002144 if (officialNai != null && officialNai.equals(nai)) return true;
2145 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002146 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002147 " - " + nai);
2148 }
2149 return false;
2150 }
2151
Robert Greenwalt42acef32009-08-12 16:08:25 -07002152 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002153 private class NetworkStateTrackerHandler extends Handler {
2154 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002155 super(looper);
2156 }
2157
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002158 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002160 default:
2161 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002162 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002163 handleAsyncChannelHalfConnect(msg);
2164 break;
2165 }
2166 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2167 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2168 if (nai != null) nai.asyncChannel.disconnect();
2169 break;
2170 }
2171 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2172 handleAsyncChannelDisconnected(msg);
2173 break;
2174 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002175 }
2176 return true;
2177 }
2178
2179 private void maybeHandleNetworkAgentMessage(Message msg) {
2180 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2181 if (nai == null) {
2182 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002183 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002184 }
2185 return;
2186 }
2187
2188 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002189 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002190 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2191 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002192 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2193 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002194 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002195 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002196 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002197 break;
2198 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002199 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002200 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002201 break;
2202 }
2203 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002204 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002205 updateNetworkInfo(nai, info);
2206 break;
2207 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002208 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002209 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002210 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002211 break;
2212 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002213 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002214 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2215 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002216 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002217 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002218 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002219 break;
2220 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002221 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002222 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2223 break;
2224 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002225 }
2226 }
2227
2228 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2229 switch (msg.what) {
2230 default:
2231 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002232 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Erik Kline79c6d052018-03-21 07:18:33 -07002233 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002234 if (nai == null) break;
2235
2236 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2237 final boolean wasValidated = nai.lastValidated;
2238 final boolean wasDefault = isDefaultNetwork(nai);
2239
Erik Klinea24d4592018-01-11 21:07:29 +09002240 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2241
Erik Klinea24d4592018-01-11 21:07:29 +09002242 if (DBG) {
Erik Kline79c6d052018-03-21 07:18:33 -07002243 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2244 ? " with redirect to " + redirectUrl
2245 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002246 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2247 }
Erik Klinea24d4592018-01-11 21:07:29 +09002248 if (valid != nai.lastValidated) {
2249 if (wasDefault) {
2250 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2251 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002252 }
Erik Klinea24d4592018-01-11 21:07:29 +09002253 final int oldScore = nai.getCurrentScore();
2254 nai.lastValidated = valid;
2255 nai.everValidated |= valid;
2256 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2257 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2258 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2259 }
2260 updateInetCondition(nai);
2261 // Let the NetworkAgent know the state of its network
2262 Bundle redirectUrlBundle = new Bundle();
2263 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2264 nai.asyncChannel.sendMessage(
2265 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2266 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2267 0, redirectUrlBundle);
2268 if (wasValidated && !nai.lastValidated) {
2269 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002270 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002271 break;
2272 }
Paul Jensen869868be2014-05-15 10:33:05 -04002273 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002274 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002275 final boolean visible = toBool(msg.arg1);
Erik Kline79c6d052018-03-21 07:18:33 -07002276 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002277 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002278 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002279 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002280 nai.lastCaptivePortalDetected = visible;
2281 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002282 if (nai.lastCaptivePortalDetected &&
2283 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2284 if (DBG) log("Avoiding captive portal network: " + nai.name());
2285 nai.asyncChannel.sendMessage(
2286 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2287 teardownUnneededNetwork(nai);
2288 break;
2289 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002290 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002291 }
2292 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002293 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002294 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002295 if (nai == null) {
2296 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2297 break;
2298 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002299 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002300 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002301 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002302 }
Paul Jensen869868be2014-05-15 10:33:05 -04002303 }
Paul Jensen869868be2014-05-15 10:33:05 -04002304 break;
2305 }
Erik Klinea24d4592018-01-11 21:07:29 +09002306 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline79c6d052018-03-21 07:18:33 -07002307 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002308 if (nai == null) break;
2309
Erik Kline79c6d052018-03-21 07:18:33 -07002310 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002311 break;
2312 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002313 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002314 return true;
2315 }
2316
Calvin Onbe96da12016-10-11 15:10:46 -07002317 private int getCaptivePortalMode() {
2318 return Settings.Global.getInt(mContext.getContentResolver(),
2319 Settings.Global.CAPTIVE_PORTAL_MODE,
2320 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2321 }
2322
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002323 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2324 switch (msg.what) {
2325 default:
2326 return false;
2327 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2328 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2329 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2330 handleLingerComplete(nai);
2331 }
2332 break;
2333 }
2334 }
2335 return true;
2336 }
2337
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002338 @Override
2339 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002340 if (!maybeHandleAsyncChannelMessage(msg) &&
2341 !maybeHandleNetworkMonitorMessage(msg) &&
2342 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002343 maybeHandleNetworkAgentMessage(msg);
2344 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002345 }
2346 }
2347
Erik Kline79c6d052018-03-21 07:18:33 -07002348 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
2349 return NetworkMonitor.isValidationRequired(
2350 mDefaultRequest.networkCapabilities, nai.networkCapabilities);
2351 }
2352
Erik Klinea24d4592018-01-11 21:07:29 +09002353 private void handlePrivateDnsSettingsChanged() {
2354 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2355
2356 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline79c6d052018-03-21 07:18:33 -07002357 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk1fcb7392018-03-05 12:42:22 -05002358 if (networkRequiresValidation(nai)) {
2359 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2360 }
Erik Klinea24d4592018-01-11 21:07:29 +09002361 }
2362 }
2363
Erik Kline79c6d052018-03-21 07:18:33 -07002364 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2365 // Private DNS only ever applies to networks that might provide
2366 // Internet access and therefore also require validation.
2367 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002368
Erik Kline79c6d052018-03-21 07:18:33 -07002369 // Notify the NetworkMonitor thread in case it needs to cancel or
2370 // schedule DNS resolutions. If a DNS resolution is required the
2371 // result will be sent back to us.
2372 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2373
2374 // With Private DNS bypass support, we can proceed to update the
2375 // Private DNS config immediately, even if we're in strict mode
2376 // and have not yet resolved the provider name into a set of IPs.
2377 updatePrivateDns(nai, cfg);
2378 }
2379
2380 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2381 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002382 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002383 }
2384
dalyk1fcb7392018-03-05 12:42:22 -05002385 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2386 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2387 if (nai == null) {
2388 return;
2389 }
2390 mDnsManager.updatePrivateDnsValidation(update);
2391 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2392 }
2393
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002394 private void updateLingerState(NetworkAgentInfo nai, long now) {
2395 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2396 // 2. If the network was lingering and there are now requests, unlinger it.
2397 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2398 // one lingered request, start lingering.
2399 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002400 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002401 if (DBG) log("Unlingering " + nai.name());
2402 nai.unlinger();
2403 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002404 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002405 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002406 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002407 nai.linger();
2408 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2409 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2410 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002411 }
2412
Robert Greenwalt7b816022014-04-18 15:25:25 -07002413 private void handleAsyncChannelHalfConnect(Message msg) {
2414 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002415 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002416 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2417 if (VDBG) log("NetworkFactory connected");
2418 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002419 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002420 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002421 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002422 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002423 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002424 }
2425 } else {
2426 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002427 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002428 }
2429 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2430 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2431 if (VDBG) log("NetworkAgent connected");
2432 // A network agent has requested a connection. Establish the connection.
2433 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2434 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2435 } else {
2436 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002437 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002438 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002439 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002440 synchronized (mNetworkForNetId) {
2441 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002442 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002443 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002444 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002445 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002446 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002447 }
2448 }
2449 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002450
Robert Greenwalt7b816022014-04-18 15:25:25 -07002451 private void handleAsyncChannelDisconnected(Message msg) {
2452 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2453 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002454 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002455 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002456 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002457 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002458 // TODO - if we move the logic to the network agent (have them disconnect
2459 // because they lost all their requests or because their score isn't good)
2460 // then they would disconnect organically, report their new state and then
2461 // disconnect the channel.
2462 if (nai.networkInfo.isConnected()) {
2463 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2464 null, null);
2465 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002466 final boolean wasDefault = isDefaultNetwork(nai);
2467 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002468 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002469 // Log default network disconnection before required book-keeping.
2470 // Let rematchAllNetworksAndRequests() below record a new default network event
2471 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2472 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002473 long now = SystemClock.elapsedRealtime();
2474 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002475 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002476 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002477 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2478 // by other networks that are already connected. Perhaps that can be done by
2479 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2480 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002481 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002482 mKeepaliveTracker.handleStopAllKeepalives(nai,
2483 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002484 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2485 // Disable wakeup packet monitoring for each interface.
2486 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2487 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002488 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002489 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002490 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002491 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002492 // Remove the NetworkAgent, but don't mark the netId as
2493 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002494 mNetworkForNetId.remove(nai.network.netId);
2495 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002496 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002497 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2498 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002499 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002500 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002501 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002502 sendUpdatedScoreToFactories(request, 0);
2503 }
2504 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002505 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002506 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002507 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002508 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002509 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002510 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002511 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002512 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002513 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002514 if (nai.created) {
2515 // Tell netd to clean up the configuration for this network
2516 // (routing rules, DNS, etc).
2517 // This may be slow as it requires a lot of netd shelling out to ip and
2518 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2519 // after we've rematched networks with requests which should make a potential
2520 // fallback network the default or requested a new network from the
2521 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2522 // long time.
2523 try {
2524 mNetd.removeNetwork(nai.network.netId);
2525 } catch (Exception e) {
2526 loge("Exception removing network: " + e);
2527 }
Erik Klinea24d4592018-01-11 21:07:29 +09002528 mDnsManager.removeNetwork(nai.network);
Paul Jensen62d30802015-06-17 14:42:30 -04002529 }
2530 synchronized (mNetworkForNetId) {
2531 mNetIdInUse.delete(nai.network.netId);
2532 }
2533 } else {
2534 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2535 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002536 }
2537 }
2538
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002539 // If this method proves to be too slow then we can maintain a separate
2540 // pendingIntent => NetworkRequestInfo map.
2541 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2542 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2543 Intent intent = pendingIntent.getIntent();
2544 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2545 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2546 if (existingPendingIntent != null &&
2547 existingPendingIntent.getIntent().filterEquals(intent)) {
2548 return entry.getValue();
2549 }
2550 }
2551 return null;
2552 }
2553
2554 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2555 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2556
2557 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2558 if (existingRequest != null) { // remove the existing request.
2559 if (DBG) log("Replacing " + existingRequest.request + " with "
2560 + nri.request + " because their intents matched.");
2561 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2562 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002563 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002564 }
2565
Erik Klineda4bfa82015-04-30 12:58:40 +09002566 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002567 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002568 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002569 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002570 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002571 if (nri.request.networkCapabilities.hasSignalStrength() &&
2572 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2573 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002574 }
2575 }
2576 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002577 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002578 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002579 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002580 }
2581 }
2582
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002583 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2584 int callingUid) {
2585 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2586 if (nri != null) {
2587 handleReleaseNetworkRequest(nri.request, callingUid);
2588 }
2589 }
2590
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002591 // Determines whether the network is the best (or could become the best, if it validated), for
2592 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2593 // on the value of reason:
2594 //
2595 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2596 // then it should be torn down.
2597 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2598 // then it should be lingered.
2599 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2600 final int numRequests;
2601 switch (reason) {
2602 case TEARDOWN:
2603 numRequests = nai.numRequestNetworkRequests();
2604 break;
2605 case LINGER:
2606 numRequests = nai.numForegroundNetworkRequests();
2607 break;
2608 default:
2609 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2610 return true;
2611 }
2612
2613 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002614 return false;
2615 }
Paul Jensene0988542015-06-25 15:30:08 -04002616 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002617 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2618 // Background requests don't affect lingering.
2619 continue;
2620 }
2621
Paul Jensene0988542015-06-25 15:30:08 -04002622 // If this Network is already the highest scoring Network for a request, or if
2623 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002624 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002625 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002626 // Note that this catches two important cases:
2627 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2628 // is currently satisfying the request. This is desirable when
2629 // cellular ends up validating but WiFi does not.
2630 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002631 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002632 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002633 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002634 nai.getCurrentScoreAsValidated())) {
2635 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002636 }
2637 }
Paul Jensene0988542015-06-25 15:30:08 -04002638 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002639 }
2640
Erik Klineacdd6392016-07-07 16:50:58 +09002641 private NetworkRequestInfo getNriForAppRequest(
2642 NetworkRequest request, int callingUid, String requestedOperation) {
2643 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2644
Robert Greenwalt9258c642014-03-26 16:47:06 -07002645 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002646 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002647 log(String.format("UID %d attempted to %s for unowned request %s",
2648 callingUid, requestedOperation, nri));
2649 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002650 }
Erik Klineacdd6392016-07-07 16:50:58 +09002651 }
2652
2653 return nri;
2654 }
2655
Erik Kline57faba92015-11-25 12:49:38 +09002656 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002657 if (mNetworkRequests.get(nri.request) == null) {
2658 return;
Erik Kline57faba92015-11-25 12:49:38 +09002659 }
Hugo Benichicd952782017-09-20 11:20:14 +09002660 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002661 return;
2662 }
2663 if (VDBG || (DBG && nri.request.isRequest())) {
2664 log("releasing " + nri.request + " (timeout)");
2665 }
2666 handleRemoveNetworkRequest(nri);
2667 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002668 }
2669
Erik Klineacdd6392016-07-07 16:50:58 +09002670 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002671 final NetworkRequestInfo nri =
2672 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2673 if (nri == null) {
2674 return;
Erik Kline57faba92015-11-25 12:49:38 +09002675 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002676 if (VDBG || (DBG && nri.request.isRequest())) {
2677 log("releasing " + nri.request + " (release request)");
2678 }
2679 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002680 }
Erik Klineacdd6392016-07-07 16:50:58 +09002681
Hugo Benichidba33db2017-03-23 22:40:44 +09002682 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002683 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002684 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002685
Erik Klineacdd6392016-07-07 16:50:58 +09002686 synchronized (mUidToNetworkRequestCount) {
2687 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2688 if (requests < 1) {
2689 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2690 nri.mUid);
2691 } else if (requests == 1) {
2692 mUidToNetworkRequestCount.removeAt(
2693 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2694 } else {
2695 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2696 }
2697 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002698
Erik Klineacdd6392016-07-07 16:50:58 +09002699 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2700 if (nri.request.isRequest()) {
2701 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002702 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002703 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002704 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002705 nai.removeRequest(nri.request.requestId);
2706 if (VDBG) {
2707 log(" Removing from current network " + nai.name() +
2708 ", leaving " + nai.numNetworkRequests() + " requests.");
2709 }
2710 // If there are still lingered requests on this network, don't tear it down,
2711 // but resume lingering instead.
2712 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002713 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002714 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2715 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002716 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002717 wasKept = true;
2718 }
Hugo Benichicd952782017-09-20 11:20:14 +09002719 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002720 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2721 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002722 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002723 }
Erik Klineacdd6392016-07-07 16:50:58 +09002724 }
2725
2726 // TODO: remove this code once we know that the Slog.wtf is never hit.
2727 //
2728 // Find all networks that are satisfying this request and remove the request
2729 // from their request lists.
2730 // TODO - it's my understanding that for a request there is only a single
2731 // network satisfying it, so this loop is wasteful
2732 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2733 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2734 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2735 otherNai.name() + ", but mNetworkAgentInfos says " +
2736 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002737 }
2738 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002739
Erik Klineacdd6392016-07-07 16:50:58 +09002740 // Maintain the illusion. When this request arrived, we might have pretended
2741 // that a network connected to serve it, even though the network was already
2742 // connected. Now that this request has gone away, we might have to pretend
2743 // that the network disconnected. LegacyTypeTracker will generate that
2744 // phantom disconnect for this type.
2745 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2746 boolean doRemove = true;
2747 if (wasKept) {
2748 // check if any of the remaining requests for this network are for the
2749 // same legacy type - if so, don't remove the nai
2750 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2751 NetworkRequest otherRequest = nai.requestAt(i);
2752 if (otherRequest.legacyType == nri.request.legacyType &&
2753 otherRequest.isRequest()) {
2754 if (DBG) log(" still have other legacy request - leaving");
2755 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002756 }
2757 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002758 }
2759
Erik Klineacdd6392016-07-07 16:50:58 +09002760 if (doRemove) {
2761 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002762 }
2763 }
Erik Klineacdd6392016-07-07 16:50:58 +09002764
2765 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2766 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2767 nri.request);
2768 }
2769 } else {
2770 // listens don't have a singular affectedNetwork. Check all networks to see
2771 // if this listen request applies and remove it.
2772 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2773 nai.removeRequest(nri.request.requestId);
2774 if (nri.request.networkCapabilities.hasSignalStrength() &&
2775 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2776 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2777 }
2778 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002779 }
2780 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002781
Lorenzo Colitti18660282016-07-04 12:55:44 +09002782 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002783 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2784 enforceConnectivityInternalPermission();
2785 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002786 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002787 }
2788
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002789 @Override
2790 public void setAvoidUnvalidated(Network network) {
2791 enforceConnectivityInternalPermission();
2792 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2793 }
2794
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002795 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2796 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2797 " accept=" + accept + " always=" + always);
2798
2799 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2800 if (nai == null) {
2801 // Nothing to do.
2802 return;
2803 }
2804
2805 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002806 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002807 return;
2808 }
2809
2810 if (!nai.networkMisc.explicitlySelected) {
2811 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2812 }
2813
2814 if (accept != nai.networkMisc.acceptUnvalidated) {
2815 int oldScore = nai.getCurrentScore();
2816 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002817 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002818 sendUpdatedScoreToFactories(nai);
2819 }
2820
2821 if (always) {
2822 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002823 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002824 }
2825
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002826 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002827 // Tell the NetworkAgent to not automatically reconnect to the network.
2828 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2829 // Teardown the nework.
2830 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002831 }
2832
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002833 }
2834
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002835 private void handleSetAvoidUnvalidated(Network network) {
2836 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2837 if (nai == null || nai.lastValidated) {
2838 // Nothing to do. The network either disconnected or revalidated.
2839 return;
2840 }
2841 if (!nai.avoidUnvalidated) {
2842 int oldScore = nai.getCurrentScore();
2843 nai.avoidUnvalidated = true;
2844 rematchAllNetworksAndRequests(nai, oldScore);
2845 sendUpdatedScoreToFactories(nai);
2846 }
2847 }
2848
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002849 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002850 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002851 mHandler.sendMessageDelayed(
2852 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2853 PROMPT_UNVALIDATED_DELAY_MS);
2854 }
2855
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002856 @Override
2857 public void startCaptivePortalApp(Network network) {
2858 enforceConnectivityInternalPermission();
2859 mHandler.post(() -> {
2860 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2861 if (nai == null) return;
2862 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2863 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2864 });
2865 }
2866
Hugo Benichic8e9e122016-09-14 23:23:08 +00002867 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002868 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002869 }
2870
Erik Kline065ab6e2016-10-02 18:02:14 +09002871 private void rematchForAvoidBadWifiUpdate() {
2872 rematchAllNetworksAndRequests(null, 0);
2873 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2874 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2875 sendUpdatedScoreToFactories(nai);
2876 }
2877 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002878 }
2879
Erik Kline065ab6e2016-10-02 18:02:14 +09002880 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002881 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002882 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002883 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002884 if (!configRestrict) {
2885 pw.println("Bad Wi-Fi avoidance: unrestricted");
2886 return;
2887 }
2888
2889 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2890 pw.increaseIndent();
2891 pw.println("Config restrict: " + configRestrict);
2892
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002893 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002894 String description;
2895 // Can't use a switch statement because strings are legal case labels, but null is not.
2896 if ("0".equals(value)) {
2897 description = "get stuck";
2898 } else if (value == null) {
2899 description = "prompt";
2900 } else if ("1".equals(value)) {
2901 description = "avoid";
2902 } else {
2903 description = value + " (?)";
2904 }
2905 pw.println("User setting: " + description);
2906 pw.println("Network overrides:");
2907 pw.increaseIndent();
2908 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2909 if (nai.avoidUnvalidated) {
2910 pw.println(nai.name());
2911 }
2912 }
2913 pw.decreaseIndent();
2914 pw.decreaseIndent();
2915 }
2916
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002917 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2918 final String action;
2919 switch (type) {
2920 case NO_INTERNET:
2921 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2922 break;
2923 case LOST_INTERNET:
2924 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2925 break;
2926 default:
2927 Slog.wtf(TAG, "Unknown notification type " + type);
2928 return;
2929 }
2930
2931 Intent intent = new Intent(action);
2932 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2933 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2934 intent.setClassName("com.android.settings",
2935 "com.android.settings.wifi.WifiNoInternetDialog");
2936
2937 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2938 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2939 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2940 }
2941
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002942 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002943 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002944 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2945
2946 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2947 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002948 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002949 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002950 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2951 return;
2952 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002953 showValidationNotification(nai, NotificationType.NO_INTERNET);
2954 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002955
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002956 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2957 NetworkCapabilities nc = nai.networkCapabilities;
2958 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002959
Erik Kline065ab6e2016-10-02 18:02:14 +09002960 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002961 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002962 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2963 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002964 }
2965
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002966 @Override
2967 public int getMultipathPreference(Network network) {
2968 enforceAccessPermission();
2969
2970 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002971 if (nai != null && nai.networkCapabilities
2972 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002973 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2974 }
2975
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002976 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
2977 if (networkPreference != null) {
2978 return networkPreference;
2979 }
2980
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002981 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2982 }
2983
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002984 private class InternalHandler extends Handler {
2985 public InternalHandler(Looper looper) {
2986 super(looper);
2987 }
2988
2989 @Override
2990 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002991 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002992 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002993 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002994 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002995 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002996 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002997 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002998 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002999 break;
3000 }
Jason Monkdecd2952013-10-10 14:02:51 -04003001 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003002 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003003 break;
3004 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003005 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003006 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3007 break;
3008 }
3009 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3010 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003011 break;
3012 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003013 case EVENT_REGISTER_NETWORK_AGENT: {
3014 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
3015 break;
3016 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003017 case EVENT_REGISTER_NETWORK_REQUEST:
3018 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003019 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003020 break;
3021 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003022 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3023 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003024 handleRegisterNetworkRequestWithIntent(msg);
3025 break;
3026 }
Erik Kline57faba92015-11-25 12:49:38 +09003027 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3028 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3029 handleTimedOutNetworkRequest(nri);
3030 break;
3031 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003032 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3033 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3034 break;
3035 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003036 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003037 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003038 break;
3039 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003040 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003041 Network network = (Network) msg.obj;
3042 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003043 break;
3044 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003045 case EVENT_SET_AVOID_UNVALIDATED: {
3046 handleSetAvoidUnvalidated((Network) msg.obj);
3047 break;
3048 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003049 case EVENT_PROMPT_UNVALIDATED: {
3050 handlePromptUnvalidated((Network) msg.obj);
3051 break;
3052 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003053 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
3054 handleMobileDataAlwaysOn();
3055 break;
3056 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003057 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3058 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3059 mKeepaliveTracker.handleStartKeepalive(msg);
3060 break;
3061 }
3062 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3063 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3064 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3065 int slot = msg.arg1;
3066 int reason = msg.arg2;
3067 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3068 break;
3069 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003070 case EVENT_SYSTEM_READY: {
3071 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3072 nai.networkMonitor.systemReady = true;
3073 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003074 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003075 break;
3076 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003077 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003078 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003079 break;
3080 }
Erik Klinea24d4592018-01-11 21:07:29 +09003081 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3082 handlePrivateDnsSettingsChanged();
3083 break;
dalyk1fcb7392018-03-05 12:42:22 -05003084 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3085 handlePrivateDnsValidationUpdate(
3086 (PrivateDnsValidationUpdate) msg.obj);
3087 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 }
3089 }
3090 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003091
3092 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003093 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003094 public int tether(String iface, String callerPkg) {
3095 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003096 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003097 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003098 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003099 } else {
3100 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3101 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003102 }
3103
3104 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003105 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003106 public int untether(String iface, String callerPkg) {
3107 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003108
3109 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003110 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003111 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003112 } else {
3113 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3114 }
3115 }
3116
3117 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003118 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003119 public int getLastTetherError(String iface) {
3120 enforceTetherAccessPermission();
3121
3122 if (isTetheringSupported()) {
3123 return mTethering.getLastTetherError(iface);
3124 } else {
3125 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3126 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003127 }
3128
3129 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003130 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003131 public String[] getTetherableUsbRegexs() {
3132 enforceTetherAccessPermission();
3133 if (isTetheringSupported()) {
3134 return mTethering.getTetherableUsbRegexs();
3135 } else {
3136 return new String[0];
3137 }
3138 }
3139
Lorenzo Colitti18660282016-07-04 12:55:44 +09003140 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003141 public String[] getTetherableWifiRegexs() {
3142 enforceTetherAccessPermission();
3143 if (isTetheringSupported()) {
3144 return mTethering.getTetherableWifiRegexs();
3145 } else {
3146 return new String[0];
3147 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003148 }
3149
Lorenzo Colitti18660282016-07-04 12:55:44 +09003150 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003151 public String[] getTetherableBluetoothRegexs() {
3152 enforceTetherAccessPermission();
3153 if (isTetheringSupported()) {
3154 return mTethering.getTetherableBluetoothRegexs();
3155 } else {
3156 return new String[0];
3157 }
3158 }
3159
Lorenzo Colitti18660282016-07-04 12:55:44 +09003160 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003161 public int setUsbTethering(boolean enable, String callerPkg) {
3162 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003163 if (isTetheringSupported()) {
3164 return mTethering.setUsbTethering(enable);
3165 } else {
3166 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3167 }
3168 }
3169
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003170 // TODO - move iface listing, queries, etc to new module
3171 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003172 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003173 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003174 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003175 return mTethering.getTetherableIfaces();
3176 }
3177
Lorenzo Colitti18660282016-07-04 12:55:44 +09003178 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003179 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003180 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003181 return mTethering.getTetheredIfaces();
3182 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003183
Lorenzo Colitti18660282016-07-04 12:55:44 +09003184 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003185 public String[] getTetheringErroredIfaces() {
3186 enforceTetherAccessPermission();
3187 return mTethering.getErroredIfaces();
3188 }
3189
Lorenzo Colitti18660282016-07-04 12:55:44 +09003190 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003191 public String[] getTetheredDhcpRanges() {
3192 enforceConnectivityInternalPermission();
3193 return mTethering.getTetheredDhcpRanges();
3194 }
3195
Udam Saini0e94c362017-06-07 12:06:28 -07003196 @Override
3197 public boolean isTetheringSupported(String callerPkg) {
3198 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3199 return isTetheringSupported();
3200 }
3201
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003202 // if ro.tether.denied = true we default to no tethering
3203 // gservices could set the secure setting to 1 though to enable it on a build where it
3204 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003205 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003206 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3207 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3208 Settings.Global.TETHER_SUPPORTED, defaultVal));
3209 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003210 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003211
3212 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3213 boolean adminUser = false;
3214 final long token = Binder.clearCallingIdentity();
3215 try {
3216 adminUser = mUserManager.isAdminUser();
3217 } finally {
3218 Binder.restoreCallingIdentity(token);
3219 }
3220
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003221 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003222 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003223
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003224 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003225 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3226 String callerPkg) {
3227 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003228 if (!isTetheringSupported()) {
3229 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3230 return;
3231 }
3232 mTethering.startTethering(type, receiver, showProvisioningUi);
3233 }
3234
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003235 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003236 public void stopTethering(int type, String callerPkg) {
3237 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003238 mTethering.stopTethering(type);
3239 }
3240
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003241 // Called when we lose the default network and have no replacement yet.
3242 // This will automatically be cleared after X seconds or a new default network
3243 // becomes CONNECTED, whichever happens first. The timer is started by the
3244 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003245 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003246 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003247 if (mNetTransitionWakeLock.isHeld()) {
3248 return;
3249 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003250 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003251 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3252 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003253 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003254 mWakelockLogs.log("ACQUIRE for " + forWhom);
3255 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3256 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003257 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003258
Hugo Benichi4c31b342017-03-30 23:18:10 +09003259 // Called when we gain a new default network to release the network transition wakelock in a
3260 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3261 // message is cancelled.
3262 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003263 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003264 if (!mNetTransitionWakeLock.isHeld()) {
3265 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003266 }
3267 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003268 // Cancel self timeout on wakelock hold.
3269 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3270 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3271 mHandler.sendMessageDelayed(msg, 1000);
3272 }
3273
3274 // Called when either message of ensureNetworkTransitionWakelock or
3275 // scheduleReleaseNetworkTransitionWakelock is processed.
3276 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3277 String event = eventName(eventId);
3278 synchronized (this) {
3279 if (!mNetTransitionWakeLock.isHeld()) {
3280 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3281 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3282 return;
3283 }
3284 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003285 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3286 mTotalWakelockDurationMs += lockDuration;
3287 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3288 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003289 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003290 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003291 }
3292
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003293 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003294 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003295 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003296 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003297 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003298 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003299 }
3300
Lorenzo Colitti18660282016-07-04 12:55:44 +09003301 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003302 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003303 enforceAccessPermission();
3304 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003305 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003306 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003307 mHandler.sendMessage(
3308 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3309 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003310
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003311 private void handleReportNetworkConnectivity(
3312 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003313 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003314 if (network == null) {
3315 nai = getDefaultNetwork();
3316 } else {
3317 nai = getNetworkAgentInfoForNetwork(network);
3318 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003319 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3320 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3321 return;
3322 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003323 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003324 if (hasConnectivity == nai.lastValidated) {
3325 return;
3326 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003327 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003328 int netid = nai.network.netId;
3329 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003330 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003331 // Validating a network that has not yet connected could result in a call to
3332 // rematchNetworkAndRequests() which is not meant to work on such networks.
3333 if (!nai.everConnected) {
3334 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003335 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003336 LinkProperties lp = getLinkProperties(nai);
3337 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3338 return;
3339 }
Erik Kline79c6d052018-03-21 07:18:33 -07003340 nai.networkMonitor.forceReevaluation(uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003341 }
3342
Paul Jensencee9b512015-05-06 07:32:40 -04003343 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003344 // this information is already available as a world read/writable jvm property
3345 // so this API change wouldn't have a benifit. It also breaks the passing
3346 // of proxy info to all the JVMs.
3347 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003348 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003349 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003350 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3351 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003352 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003353 }
3354
Lorenzo Colitti18660282016-07-04 12:55:44 +09003355 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003356 public ProxyInfo getProxyForNetwork(Network network) {
3357 if (network == null) return getDefaultProxy();
3358 final ProxyInfo globalProxy = getGlobalProxy();
3359 if (globalProxy != null) return globalProxy;
3360 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3361 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3362 // caller may not have.
3363 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3364 if (nai == null) return null;
3365 synchronized (nai) {
3366 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3367 if (proxyInfo == null) return null;
3368 return new ProxyInfo(proxyInfo);
3369 }
3370 }
3371
Paul Jensene0bef712014-12-10 15:12:18 -05003372 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3373 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3374 // proxy is null then there is no proxy in place).
3375 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3376 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3377 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3378 proxy = null;
3379 }
3380 return proxy;
3381 }
3382
3383 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3384 // better for determining if a new proxy broadcast is necessary:
3385 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3386 // avoid unnecessary broadcasts.
3387 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3388 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3389 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3390 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3391 // all set.
3392 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3393 a = canonicalizeProxyInfo(a);
3394 b = canonicalizeProxyInfo(b);
3395 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3396 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3397 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3398 }
3399
Jason Monk207900c2014-04-25 15:00:09 -04003400 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003401 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003402
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003403 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003404 if (proxyProperties == mGlobalProxy) return;
3405 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3406 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3407
3408 String host = "";
3409 int port = 0;
3410 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003411 String pacFileUrl = "";
3412 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003413 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003414 if (!proxyProperties.isValid()) {
3415 if (DBG)
3416 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3417 return;
3418 }
Jason Monk207900c2014-04-25 15:00:09 -04003419 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003420 host = mGlobalProxy.getHost();
3421 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003422 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003423 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003424 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003425 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003426 } else {
3427 mGlobalProxy = null;
3428 }
3429 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003430 final long token = Binder.clearCallingIdentity();
3431 try {
3432 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3433 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3434 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3435 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003436 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003437 } finally {
3438 Binder.restoreCallingIdentity(token);
3439 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003440
Jason Monkcf0f97a2014-10-02 15:39:38 -04003441 if (mGlobalProxy == null) {
3442 proxyProperties = mDefaultProxy;
3443 }
3444 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003445 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003446 }
3447
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003448 private void loadGlobalProxy() {
3449 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003450 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3451 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3452 String exclList = Settings.Global.getString(res,
3453 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003454 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3455 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003456 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003457 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003458 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003459 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003460 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003461 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003462 if (!proxyProperties.isValid()) {
3463 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3464 return;
3465 }
3466
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003467 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003468 mGlobalProxy = proxyProperties;
3469 }
3470 }
3471 }
3472
Jason Monk207900c2014-04-25 15:00:09 -04003473 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003474 // this information is already available as a world read/writable jvm property
3475 // so this API change wouldn't have a benifit. It also breaks the passing
3476 // of proxy info to all the JVMs.
3477 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003478 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003479 return mGlobalProxy;
3480 }
3481 }
3482
Jason Monk207900c2014-04-25 15:00:09 -04003483 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003484 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003485 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003486 proxy = null;
3487 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003488 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003489 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003490 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003491 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003492 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3493 return;
3494 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003495
3496 // This call could be coming from the PacManager, containing the port of the local
3497 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3498 // global (to get the correct local port), and send a broadcast.
3499 // TODO: Switch PacManager to have its own message to send back rather than
3500 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003501 if ((mGlobalProxy != null) && (proxy != null)
3502 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003503 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3504 mGlobalProxy = proxy;
3505 sendProxyBroadcast(mGlobalProxy);
3506 return;
3507 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003508 mDefaultProxy = proxy;
3509
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003510 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003511 if (!mDefaultProxyDisabled) {
3512 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003513 }
3514 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003515 }
3516
Paul Jensene0bef712014-12-10 15:12:18 -05003517 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3518 // This method gets called when any network changes proxy, but the broadcast only ever contains
3519 // the default proxy (even if it hasn't changed).
3520 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3521 // world where an app might be bound to a non-default network.
3522 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3523 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3524 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3525
3526 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3527 sendProxyBroadcast(getDefaultProxy());
3528 }
3529 }
3530
Robert Greenwalt434203a2010-10-11 16:00:27 -07003531 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003532 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3533 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003534 if (!TextUtils.isEmpty(proxy)) {
3535 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003536 if (data.length == 0) {
3537 return;
3538 }
3539
Robert Greenwalt434203a2010-10-11 16:00:27 -07003540 String proxyHost = data[0];
3541 int proxyPort = 8080;
3542 if (data.length > 1) {
3543 try {
3544 proxyPort = Integer.parseInt(data[1]);
3545 } catch (NumberFormatException e) {
3546 return;
3547 }
3548 }
Jason Monk207900c2014-04-25 15:00:09 -04003549 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003550 setGlobalProxy(p);
3551 }
3552 }
3553
Jason Monk207900c2014-04-25 15:00:09 -04003554 private void sendProxyBroadcast(ProxyInfo proxy) {
3555 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003556 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003557 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003558 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003559 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3560 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003561 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003562 final long ident = Binder.clearCallingIdentity();
3563 try {
3564 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3565 } finally {
3566 Binder.restoreCallingIdentity(ident);
3567 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003568 }
3569
3570 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003571 final private HashMap<Uri, Integer> mUriEventMap;
3572 final private Context mContext;
3573 final private Handler mHandler;
3574
3575 SettingsObserver(Context context, Handler handler) {
3576 super(null);
3577 mUriEventMap = new HashMap<Uri, Integer>();
3578 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003579 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003580 }
3581
Erik Klineda4bfa82015-04-30 12:58:40 +09003582 void observe(Uri uri, int what) {
3583 mUriEventMap.put(uri, what);
3584 final ContentResolver resolver = mContext.getContentResolver();
3585 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003586 }
3587
3588 @Override
3589 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003590 Slog.wtf(TAG, "Should never be reached.");
3591 }
3592
3593 @Override
3594 public void onChange(boolean selfChange, Uri uri) {
3595 final Integer what = mUriEventMap.get(uri);
3596 if (what != null) {
3597 mHandler.obtainMessage(what.intValue()).sendToTarget();
3598 } else {
3599 loge("No matching event to send for URI=" + uri);
3600 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003601 }
3602 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003603
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003604 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003605 Slog.d(TAG, s);
3606 }
3607
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003608 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003609 Slog.e(TAG, s);
3610 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003611
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003612 private static void loge(String s, Throwable t) {
3613 Slog.e(TAG, s, t);
3614 }
3615
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003616 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003617 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003618 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3619 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3620 *
3621 * @param oldPackage Package name of the application which currently controls VPN, which will
3622 * be replaced. If there is no such application, this should should either be
3623 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3624 * @param newPackage Package name of the application which should gain control of VPN, or
3625 * {@code null} to disable.
3626 * @param userId User for whom to prepare the new VPN.
3627 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003628 * @hide
3629 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003630 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003631 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3632 int userId) {
3633 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003634
Hugo Benichi20035e02017-04-26 14:53:28 +09003635 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003636 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003637 Vpn vpn = mVpns.get(userId);
3638 if (vpn != null) {
3639 return vpn.prepare(oldPackage, newPackage);
3640 } else {
3641 return false;
3642 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003643 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003644 }
3645
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003646 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003647 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3648 * This method is used by system-privileged apps.
3649 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3650 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3651 *
3652 * @param packageName The package for which authorization state should change.
3653 * @param userId User for whom {@code packageName} is installed.
3654 * @param authorized {@code true} if this app should be able to start a VPN connection without
3655 * explicit user approval, {@code false} if not.
3656 *
Jeff Davidson05542602014-08-11 14:07:27 -07003657 * @hide
3658 */
3659 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003660 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3661 enforceCrossUserPermission(userId);
3662
Hugo Benichi20035e02017-04-26 14:53:28 +09003663 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003664 Vpn vpn = mVpns.get(userId);
3665 if (vpn != null) {
3666 vpn.setPackageAuthorization(packageName, authorized);
3667 }
Jeff Davidson05542602014-08-11 14:07:27 -07003668 }
3669 }
3670
3671 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003672 * Configure a TUN interface and return its file descriptor. Parameters
3673 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003674 * and not available in ConnectivityManager. Permissions are checked in
3675 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003676 * @hide
3677 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003678 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003679 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003680 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003681 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003682 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003683 return mVpns.get(user).establish(config);
3684 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003685 }
3686
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003687 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003688 * Start legacy VPN, controlling native daemons as needed. Creates a
3689 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003690 */
3691 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003692 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003693 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003694 final LinkProperties egress = getActiveLinkProperties();
3695 if (egress == null) {
3696 throw new IllegalStateException("Missing active network connection");
3697 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003698 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003699 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003700 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3701 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003702 }
3703
3704 /**
3705 * Return the information of the ongoing legacy VPN. This method is used
3706 * by VpnSettings and not available in ConnectivityManager. Permissions
3707 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003708 */
3709 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003710 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3711 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003712
Hugo Benichi20035e02017-04-26 14:53:28 +09003713 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003714 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003715 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003716 }
3717
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003718 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003719 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3720 * and not available in ConnectivityManager.
3721 */
3722 @Override
3723 public VpnInfo[] getAllVpnInfo() {
3724 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003725 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003726 if (mLockdownEnabled) {
3727 return new VpnInfo[0];
3728 }
3729
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003730 List<VpnInfo> infoList = new ArrayList<>();
3731 for (int i = 0; i < mVpns.size(); i++) {
3732 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3733 if (info != null) {
3734 infoList.add(info);
3735 }
3736 }
3737 return infoList.toArray(new VpnInfo[infoList.size()]);
3738 }
3739 }
3740
3741 /**
3742 * @return VPN information for accounting, or null if we can't retrieve all required
3743 * information, e.g primary underlying iface.
3744 */
3745 @Nullable
3746 private VpnInfo createVpnInfo(Vpn vpn) {
3747 VpnInfo info = vpn.getVpnInfo();
3748 if (info == null) {
3749 return null;
3750 }
3751 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3752 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3753 // the underlyingNetworks list.
3754 if (underlyingNetworks == null) {
3755 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3756 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3757 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3758 }
3759 } else if (underlyingNetworks.length > 0) {
3760 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3761 if (linkProperties != null) {
3762 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3763 }
3764 }
3765 return info.primaryUnderlyingIface == null ? null : info;
3766 }
3767
3768 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003769 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3770 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003771 * Permissions are checked in Vpn class.
3772 * @hide
3773 */
3774 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003775 public VpnConfig getVpnConfig(int userId) {
3776 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003777 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003778 Vpn vpn = mVpns.get(userId);
3779 if (vpn != null) {
3780 return vpn.getVpnConfig();
3781 } else {
3782 return null;
3783 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003784 }
3785 }
3786
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003787 @Override
3788 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003789 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3790 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3791 return false;
3792 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003793
Hugo Benichi69744342017-11-27 10:57:16 +09003794 synchronized (mVpns) {
3795 // Tear down existing lockdown if profile was removed
3796 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3797 if (mLockdownEnabled) {
3798 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3799 if (profileTag == null) {
3800 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3801 return false;
3802 }
3803 String profileName = new String(profileTag);
3804 final VpnProfile profile = VpnProfile.decode(
3805 profileName, mKeyStore.get(Credentials.VPN + profileName));
3806 if (profile == null) {
3807 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3808 setLockdownTracker(null);
3809 return true;
3810 }
3811 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003812 Vpn vpn = mVpns.get(user);
3813 if (vpn == null) {
3814 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3815 return false;
3816 }
3817 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003818 } else {
3819 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003820 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003821 }
3822
3823 return true;
3824 }
3825
3826 /**
3827 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3828 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3829 */
Hugo Benichi69744342017-11-27 10:57:16 +09003830 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003831 private void setLockdownTracker(LockdownVpnTracker tracker) {
3832 // Shutdown any existing tracker
3833 final LockdownVpnTracker existing = mLockdownTracker;
3834 mLockdownTracker = null;
3835 if (existing != null) {
3836 existing.shutdown();
3837 }
3838
Robin Leec3736bc2017-03-10 16:19:54 +00003839 if (tracker != null) {
3840 mLockdownTracker = tracker;
3841 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003842 }
3843 }
3844
Hugo Benichi69744342017-11-27 10:57:16 +09003845 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003846 private void throwIfLockdownEnabled() {
3847 if (mLockdownEnabled) {
3848 throw new IllegalStateException("Unavailable in lockdown mode");
3849 }
3850 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003851
Robin Lee244ce8e2016-01-05 18:03:46 +00003852 /**
Robin Lee17e61832016-05-09 13:46:28 +01003853 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3854 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003855 *
Robin Lee17e61832016-05-09 13:46:28 +01003856 * @return {@code true} if the service was started, the service was already connected, or there
3857 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003858 */
Robin Lee17e61832016-05-09 13:46:28 +01003859 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003860 synchronized (mVpns) {
3861 Vpn vpn = mVpns.get(userId);
3862 if (vpn == null) {
3863 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3864 // exists already.
3865 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3866 return false;
3867 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003868
Robin Lee812800c2016-05-13 15:38:08 +01003869 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003870 }
3871 }
3872
3873 @Override
Charles He36738632017-05-15 17:07:18 +01003874 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3875 enforceSettingsPermission();
3876 enforceCrossUserPermission(userId);
3877
3878 synchronized (mVpns) {
3879 Vpn vpn = mVpns.get(userId);
3880 if (vpn == null) {
3881 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3882 return false;
3883 }
3884 return vpn.isAlwaysOnPackageSupported(packageName);
3885 }
3886 }
3887
3888 @Override
Robin Leedc679712016-05-03 13:23:03 +01003889 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003890 enforceConnectivityInternalPermission();
3891 enforceCrossUserPermission(userId);
3892
Robin Lee244ce8e2016-01-05 18:03:46 +00003893 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003894 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3895 if (LockdownVpnTracker.isEnabled()) {
3896 return false;
3897 }
3898
Robin Lee244ce8e2016-01-05 18:03:46 +00003899 Vpn vpn = mVpns.get(userId);
3900 if (vpn == null) {
3901 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3902 return false;
3903 }
Robin Lee17e61832016-05-09 13:46:28 +01003904 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003905 return false;
3906 }
Robin Lee17e61832016-05-09 13:46:28 +01003907 if (!startAlwaysOnVpn(userId)) {
3908 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003909 return false;
3910 }
3911 }
3912 return true;
3913 }
3914
3915 @Override
3916 public String getAlwaysOnVpnPackage(int userId) {
3917 enforceConnectivityInternalPermission();
3918 enforceCrossUserPermission(userId);
3919
3920 synchronized (mVpns) {
3921 Vpn vpn = mVpns.get(userId);
3922 if (vpn == null) {
3923 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3924 return null;
3925 }
3926 return vpn.getAlwaysOnPackage();
3927 }
3928 }
3929
Wink Savilleab9321d2013-06-29 21:10:57 -07003930 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003931 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003932 // TODO: Remove? Any reason to trigger a provisioning check?
3933 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003934 }
3935
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003936 /** Location to an updatable file listing carrier provisioning urls.
3937 * An example:
3938 *
3939 * <?xml version="1.0" encoding="utf-8"?>
3940 * <provisioningUrls>
3941 * <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 -07003942 * </provisioningUrls>
3943 */
3944 private static final String PROVISIONING_URL_PATH =
3945 "/data/misc/radio/provisioning_urls.xml";
3946 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003947
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003948 /** XML tag for root element. */
3949 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3950 /** XML tag for individual url */
3951 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003952 /** XML attribute for mcc */
3953 private static final String ATTR_MCC = "mcc";
3954 /** XML attribute for mnc */
3955 private static final String ATTR_MNC = "mnc";
3956
Paul Jensen434dde82015-06-11 09:43:30 -04003957 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003958 FileReader fileReader = null;
3959 XmlPullParser parser = null;
3960 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003961
3962 try {
3963 fileReader = new FileReader(mProvisioningUrlFile);
3964 parser = Xml.newPullParser();
3965 parser.setInput(fileReader);
3966 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3967
3968 while (true) {
3969 XmlUtils.nextElement(parser);
3970
3971 String element = parser.getName();
3972 if (element == null) break;
3973
Paul Jensen434dde82015-06-11 09:43:30 -04003974 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003975 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3976 try {
3977 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3978 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3979 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3980 parser.next();
3981 if (parser.getEventType() == XmlPullParser.TEXT) {
3982 return parser.getText();
3983 }
3984 }
3985 }
3986 } catch (NumberFormatException e) {
3987 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3988 }
3989 }
3990 }
3991 return null;
3992 } catch (FileNotFoundException e) {
3993 loge("Carrier Provisioning Urls file not found");
3994 } catch (XmlPullParserException e) {
3995 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3996 } catch (IOException e) {
3997 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3998 } finally {
3999 if (fileReader != null) {
4000 try {
4001 fileReader.close();
4002 } catch (IOException e) {}
4003 }
4004 }
4005 return null;
4006 }
4007
Wink Saville42d4f082013-07-20 20:31:59 -07004008 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004009 public String getMobileProvisioningUrl() {
4010 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04004011 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004012 if (TextUtils.isEmpty(url)) {
4013 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004014 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004015 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004016 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004017 }
Wink Saville8cf35602013-07-10 23:00:07 -07004018 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004019 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004020 String phoneNumber = mTelephonyManager.getLine1Number();
4021 if (TextUtils.isEmpty(phoneNumber)) {
4022 phoneNumber = "0000000000";
4023 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004024 url = String.format(url,
4025 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4026 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07004027 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004028 }
4029
Wink Savilleab9321d2013-06-29 21:10:57 -07004030 return url;
4031 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004032
Wink Saville948282b2013-08-29 08:55:16 -07004033 @Override
4034 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004035 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004036 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004037 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4038 return;
4039 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004040 final long ident = Binder.clearCallingIdentity();
4041 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004042 // Concatenate the range of types onto the range of NetIDs.
4043 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4044 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004045 } finally {
4046 Binder.restoreCallingIdentity(ident);
4047 }
Wink Saville948282b2013-08-29 08:55:16 -07004048 }
Wink Saville7788c612013-08-29 14:57:08 -07004049
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004050 @Override
4051 public void setAirplaneMode(boolean enable) {
4052 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004053 final long ident = Binder.clearCallingIdentity();
4054 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004055 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004056 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004057 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4058 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004059 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004060 } finally {
4061 Binder.restoreCallingIdentity(ident);
4062 }
4063 }
4064
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004065 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004066 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004067 Vpn userVpn = mVpns.get(userId);
4068 if (userVpn != null) {
4069 loge("Starting user already has a VPN");
4070 return;
4071 }
Paul Jensene75b9e32015-04-06 11:54:53 -04004072 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004073 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004074 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4075 updateLockdownVpn();
4076 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004077 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004078 }
4079
4080 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004081 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004082 Vpn userVpn = mVpns.get(userId);
4083 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004084 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004085 return;
4086 }
Robin Lee17e61832016-05-09 13:46:28 +01004087 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004088 mVpns.delete(userId);
4089 }
4090 }
4091
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004092 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004093 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004094 final int vpnsSize = mVpns.size();
4095 for (int i = 0; i < vpnsSize; i++) {
4096 Vpn vpn = mVpns.valueAt(i);
4097 vpn.onUserAdded(userId);
4098 }
4099 }
4100 }
4101
4102 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004103 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004104 final int vpnsSize = mVpns.size();
4105 for (int i = 0; i < vpnsSize; i++) {
4106 Vpn vpn = mVpns.valueAt(i);
4107 vpn.onUserRemoved(userId);
4108 }
4109 }
4110 }
4111
Robin Lee89e7a692016-02-29 14:38:17 +00004112 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004113 synchronized (mVpns) {
4114 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4115 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4116 updateLockdownVpn();
4117 } else {
4118 startAlwaysOnVpn(userId);
4119 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004120 }
4121 }
4122
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004123 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4124 @Override
4125 public void onReceive(Context context, Intent intent) {
4126 final String action = intent.getAction();
4127 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4128 if (userId == UserHandle.USER_NULL) return;
4129
Robin Lee323f29d2016-05-04 16:38:06 +01004130 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004131 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004132 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004133 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004134 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4135 onUserAdded(userId);
4136 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4137 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004138 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4139 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004140 }
4141 }
4142 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004143
Robin Lee95204e02017-01-27 11:59:22 +00004144 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4145 @Override
4146 public void onReceive(Context context, Intent intent) {
4147 // Try creating lockdown tracker, since user present usually means
4148 // unlocked keystore.
4149 updateLockdownVpn();
4150 mContext.unregisterReceiver(this);
4151 }
4152 };
4153
Robert Greenwalta67be032014-05-16 15:49:14 -07004154 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4155 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004156 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4157 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004158
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004159 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4160 // Map from UID to number of NetworkRequests that UID has filed.
4161 @GuardedBy("mUidToNetworkRequestCount")
4162 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4163
Robert Greenwalta67be032014-05-16 15:49:14 -07004164 private static class NetworkFactoryInfo {
4165 public final String name;
4166 public final Messenger messenger;
4167 public final AsyncChannel asyncChannel;
4168
4169 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4170 this.name = name;
4171 this.messenger = messenger;
4172 this.asyncChannel = asyncChannel;
4173 }
4174 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004175
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004176 private void ensureNetworkRequestHasType(NetworkRequest request) {
4177 if (request.type == NetworkRequest.Type.NONE) {
4178 throw new IllegalArgumentException(
4179 "All NetworkRequests in ConnectivityService must have a type");
4180 }
4181 }
4182
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004183 /**
4184 * Tracks info about the requester.
4185 * Also used to notice when the calling process dies so we can self-expire
4186 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004187 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004188 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004189 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004190 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004191 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004192 final int mPid;
4193 final int mUid;
4194 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004195
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004196 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004197 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004198 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004199 mPendingIntent = pi;
4200 messenger = null;
4201 mBinder = null;
4202 mPid = getCallingPid();
4203 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004204 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004205 }
4206
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004207 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004208 super();
4209 messenger = m;
4210 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004211 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004212 mBinder = binder;
4213 mPid = getCallingPid();
4214 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004215 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004216 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004217
4218 try {
4219 mBinder.linkToDeath(this, 0);
4220 } catch (RemoteException e) {
4221 binderDied();
4222 }
4223 }
4224
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004225 private void enforceRequestCountLimit() {
4226 synchronized (mUidToNetworkRequestCount) {
4227 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4228 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004229 throw new ServiceSpecificException(
4230 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004231 }
4232 mUidToNetworkRequestCount.put(mUid, networkRequests);
4233 }
4234 }
4235
Robert Greenwalt9258c642014-03-26 16:47:06 -07004236 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004237 if (mBinder != null) {
4238 mBinder.unlinkToDeath(this, 0);
4239 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004240 }
4241
4242 public void binderDied() {
4243 log("ConnectivityService NetworkRequestInfo binderDied(" +
4244 request + ", " + mBinder + ")");
4245 releaseNetworkRequest(request);
4246 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004247
4248 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004249 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004250 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004251 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004252 }
4253
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004254 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4255 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4256 if (badCapability != null) {
4257 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004258 }
4259 }
4260
Chalard Jeanb03a6222018-04-11 21:09:10 +09004261 // This checks that the passed capabilities either do not request a specific SSID, or the
4262 // calling app has permission to do so.
4263 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4264 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004265 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004266 throw new SecurityException("Insufficient permissions to request a specific SSID");
4267 }
4268 }
4269
Erik Kline9d598e12015-07-13 16:37:51 +09004270 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004271 final SortedSet<Integer> thresholds = new TreeSet();
4272 synchronized (nai) {
4273 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4274 if (nri.request.networkCapabilities.hasSignalStrength() &&
4275 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4276 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4277 }
4278 }
4279 }
Erik Kline9d598e12015-07-13 16:37:51 +09004280 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004281 }
4282
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004283 private void updateSignalStrengthThresholds(
4284 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4285 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004286 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004287 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4288
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004289 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004290 String detail;
4291 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4292 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4293 } else {
4294 detail = reason;
4295 }
4296 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4297 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4298 }
4299
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004300 nai.asyncChannel.sendMessage(
4301 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004302 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004303 }
4304
Etan Cohen859748f2017-04-03 17:42:34 -07004305 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4306 if (nc == null) {
4307 return;
4308 }
4309 NetworkSpecifier ns = nc.getNetworkSpecifier();
4310 if (ns == null) {
4311 return;
4312 }
4313 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4314 ns.assertValidFromUid(Binder.getCallingUid());
4315 }
4316
Robert Greenwalt9258c642014-03-26 16:47:06 -07004317 @Override
4318 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004319 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004320 final NetworkRequest.Type type = (networkCapabilities == null)
4321 ? NetworkRequest.Type.TRACK_DEFAULT
4322 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004323 // If the requested networkCapabilities is null, take them instead from
4324 // the default network request. This allows callers to keep track of
4325 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004326 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09004327 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09004328 enforceAccessPermission();
4329 } else {
4330 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4331 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004332 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4333 // of the app when the request is filed, but we never change the request if the app
4334 // changes network state. http://b/29964605
4335 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004336 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004337 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004338 ensureSufficientPermissionsForRequest(networkCapabilities,
4339 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004340 // Set the UID range for this request to the single UID of the requester, or to an empty
4341 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004342 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4343 // are no visible methods to set the UIDs, an app could use reflection to try and get
4344 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004345 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004346
Etan Cohenba07c8c2017-02-05 10:42:27 -08004347 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004348 throw new IllegalArgumentException("Bad timeout specified");
4349 }
Etan Cohen859748f2017-04-03 17:42:34 -07004350 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004351
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004352 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004353 nextNetworkRequestId(), type);
4354 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004355 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004356
4357 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004358 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004359 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004360 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004361 }
4362 return networkRequest;
4363 }
4364
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004365 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004366 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004367 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004368 } else {
4369 enforceChangePermission();
4370 }
4371 }
4372
fenglub15e72b2015-03-20 11:29:56 -07004373 @Override
fengludb571472015-04-21 17:12:05 -07004374 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004375 enforceAccessPermission();
4376 NetworkAgentInfo nai = null;
4377 if (network == null) {
4378 return false;
4379 }
4380 synchronized (mNetworkForNetId) {
4381 nai = mNetworkForNetId.get(network.netId);
4382 }
4383 if (nai != null) {
4384 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4385 return true;
4386 }
4387 return false;
4388 }
4389
Felipe Lemeee27cab2016-06-20 16:36:29 -07004390 private boolean isSystem(int uid) {
4391 return uid < Process.FIRST_APPLICATION_UID;
4392 }
fenglub15e72b2015-03-20 11:29:56 -07004393
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004394 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004395 final int uid = Binder.getCallingUid();
4396 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004397 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004398 return;
4399 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004400 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4401 // Policy already enforced.
4402 return;
4403 }
4404 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4405 // If UID is restricted, don't allow them to bring up metered APNs.
4406 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004407 }
4408 }
4409
Robert Greenwalt9258c642014-03-26 16:47:06 -07004410 @Override
4411 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4412 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004413 checkNotNull(operation, "PendingIntent cannot be null.");
4414 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4415 enforceNetworkRequestPermissions(networkCapabilities);
4416 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004417 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004418 ensureSufficientPermissionsForRequest(networkCapabilities,
4419 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07004420 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004421 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004422
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004423 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004424 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4425 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004426 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004427 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4428 nri));
4429 return networkRequest;
4430 }
4431
Jeremy Joslin79294842014-12-03 17:15:28 -08004432 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4433 mHandler.sendMessageDelayed(
4434 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4435 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4436 }
4437
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004438 @Override
4439 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004440 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004441 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4442 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004443 }
4444
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004445 // In order to implement the compatibility measure for pre-M apps that call
4446 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4447 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4448 // This ensures it has permission to do so.
4449 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4450 if (nc == null) {
4451 return false;
4452 }
4453 int[] transportTypes = nc.getTransportTypes();
4454 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4455 return false;
4456 }
4457 try {
4458 mContext.enforceCallingOrSelfPermission(
4459 android.Manifest.permission.ACCESS_WIFI_STATE,
4460 "ConnectivityService");
4461 } catch (SecurityException e) {
4462 return false;
4463 }
4464 return true;
4465 }
4466
Robert Greenwalt9258c642014-03-26 16:47:06 -07004467 @Override
4468 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4469 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004470 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4471 enforceAccessPermission();
4472 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004473
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004474 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004475 ensureSufficientPermissionsForRequest(networkCapabilities,
4476 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004477 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09004478 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4479 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4480 // onLost and onAvailable callbacks when networks move in and out of the background.
4481 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4482 // can't request networks.
4483 restrictBackgroundRequestForCaller(nc);
4484 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004485
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004486 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004487 NetworkRequest.Type.LISTEN);
4488 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004489 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004490
4491 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4492 return networkRequest;
4493 }
4494
4495 @Override
4496 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4497 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004498 checkNotNull(operation, "PendingIntent cannot be null.");
4499 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4500 enforceAccessPermission();
4501 }
Etan Cohen859748f2017-04-03 17:42:34 -07004502 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004503 ensureSufficientPermissionsForRequest(networkCapabilities,
4504 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004505
Chalard Jeandda156a2018-01-10 21:19:32 +09004506 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004507 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004508
4509 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004510 NetworkRequest.Type.LISTEN);
4511 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004512 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004513
4514 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004515 }
4516
Erik Klineacdd6392016-07-07 16:50:58 +09004517 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004518 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004519 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004520 mHandler.sendMessage(mHandler.obtainMessage(
4521 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004522 }
4523
4524 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004525 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004526 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004527 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4528 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004529 }
4530
Robert Greenwalta67be032014-05-16 15:49:14 -07004531 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004532 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004533 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4534 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4535 }
4536
4537 @Override
4538 public void unregisterNetworkFactory(Messenger messenger) {
4539 enforceConnectivityInternalPermission();
4540 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4541 }
4542
4543 private void handleUnregisterNetworkFactory(Messenger messenger) {
4544 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4545 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004546 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004547 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004548 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004549 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004550 }
4551
Robert Greenwalt7b816022014-04-18 15:25:25 -07004552 /**
4553 * NetworkAgentInfo supporting a request by requestId.
4554 * These have already been vetted (their Capabilities satisfy the request)
4555 * and the are the highest scored network available.
4556 * the are keyed off the Requests requestId.
4557 */
Hugo Benichicd952782017-09-20 11:20:14 +09004558 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4559 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004560 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4561 new SparseArray<NetworkAgentInfo>();
4562
Paul Jensen31a94f42015-02-13 14:18:39 -05004563 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4564 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004565 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4566 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004567 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4568 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4569 // there may not be a strict 1:1 correlation between the two.
4570 @GuardedBy("mNetworkForNetId")
4571 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004572
Robert Greenwalt7b816022014-04-18 15:25:25 -07004573 // NetworkAgentInfo keyed off its connecting messenger
4574 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004575 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004576 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4577 new HashMap<Messenger, NetworkAgentInfo>();
4578
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004579 @GuardedBy("mBlockedAppUids")
4580 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4581
Paul Jensen2c311d62014-11-17 12:34:51 -05004582 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004583 private final NetworkRequest mDefaultRequest;
Chalard Jean26400492018-04-18 20:18:38 +09004584
Erik Klineda4bfa82015-04-30 12:58:40 +09004585 // Request used to optionally keep mobile data active even when higher
4586 // priority networks like Wi-Fi are active.
4587 private final NetworkRequest mDefaultMobileDataRequest;
4588
Hugo Benichicd952782017-09-20 11:20:14 +09004589 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4590 synchronized (mNetworkForRequestId) {
4591 return mNetworkForRequestId.get(requestId);
4592 }
4593 }
4594
4595 private void clearNetworkForRequest(int requestId) {
4596 synchronized (mNetworkForRequestId) {
4597 mNetworkForRequestId.remove(requestId);
4598 }
4599 }
4600
4601 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4602 synchronized (mNetworkForRequestId) {
4603 mNetworkForRequestId.put(requestId, nai);
4604 }
4605 }
4606
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004607 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004608 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004609 }
4610
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004611 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004612 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004613 }
4614
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004615 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4616 return nri.request.requestId == mDefaultRequest.requestId;
4617 }
4618
Paul Jensen31a94f42015-02-13 14:18:39 -05004619 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004620 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004621 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004622 enforceConnectivityInternalPermission();
4623
Rubin Xu1bb5c082017-09-05 18:40:49 +01004624 LinkProperties lp = new LinkProperties(linkProperties);
4625 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004626 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4627 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004628 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004629 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004630 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004631 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004632 // Make sure the network capabilities reflect what the agent info says.
4633 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004634 synchronized (this) {
4635 nai.networkMonitor.systemReady = mSystemReady;
4636 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004637 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4638 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004639 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004640 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004641 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004642 }
4643
Erik Kline117e7f32018-03-04 21:01:01 +09004644 private void handleRegisterNetworkAgent(NetworkAgentInfo nai) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004645 if (VDBG) log("Got NetworkAgent Messenger");
Erik Kline117e7f32018-03-04 21:01:01 +09004646 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004647 synchronized (mNetworkForNetId) {
Erik Kline117e7f32018-03-04 21:01:01 +09004648 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004649 }
Erik Kline117e7f32018-03-04 21:01:01 +09004650 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
4651 NetworkInfo networkInfo = nai.networkInfo;
4652 nai.networkInfo = null;
4653 updateNetworkInfo(nai, networkInfo);
4654 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004655 }
4656
4657 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4658 LinkProperties newLp = networkAgent.linkProperties;
4659 int netId = networkAgent.network.netId;
4660
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004661 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4662 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004663 if (networkAgent.clatd != null) {
4664 networkAgent.clatd.fixupLinkProperties(oldLp);
4665 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004666
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004667 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004668 updateMtu(newLp, oldLp);
4669 // TODO - figure out what to do for clat
4670// for (LinkProperties lp : newLp.getStackedLinks()) {
4671// updateMtu(lp, null);
4672// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004673 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004674
Erik Kline94887872016-04-05 13:30:49 +09004675 updateRoutes(newLp, oldLp, netId);
4676 updateDnses(newLp, oldLp, netId);
dalyk1fcb7392018-03-05 12:42:22 -05004677 // Make sure LinkProperties represents the latest private DNS status.
4678 // This does not need to be done before updateDnses because the
4679 // LinkProperties are not the source of the private DNS configuration.
4680 // updateDnses will fetch the private DNS configuration from DnsManager.
4681 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004682
Hugo Benichi6f62b732017-06-27 15:13:20 +09004683 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004684 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004685 if (isDefaultNetwork(networkAgent)) {
4686 handleApplyDefaultProxy(newLp.getHttpProxy());
4687 } else {
4688 updateProxy(newLp, oldLp, networkAgent);
4689 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004690 // TODO - move this check to cover the whole function
4691 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004692 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004693 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4694 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004695
4696 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004697 }
4698
Joel Scherpelz668370b2017-06-08 15:35:21 +09004699 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004700 // Marks are only available on WiFi interaces. Checking for
4701 // marks on unsupported interfaces is harmless.
4702 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4703 return;
4704 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004705
Joel Scherpelz668370b2017-06-08 15:35:21 +09004706 int mark = mContext.getResources().getInteger(
4707 com.android.internal.R.integer.config_networkWakeupPacketMark);
4708 int mask = mContext.getResources().getInteger(
4709 com.android.internal.R.integer.config_networkWakeupPacketMask);
4710
4711 // Mask/mark of zero will not detect anything interesting.
4712 // Don't install rules unless both values are nonzero.
4713 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004714 return;
4715 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004716
4717 final String prefix = "iface:" + iface;
4718 try {
4719 if (add) {
4720 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4721 } else {
4722 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4723 }
4724 } catch (Exception e) {
4725 loge("Exception modifying wakeup packet monitoring: " + e);
4726 }
4727
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004728 }
4729
4730 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4731 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004732 CompareResult<String> interfaceDiff = new CompareResult<String>(
4733 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4734 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004735 for (String iface : interfaceDiff.added) {
4736 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004737 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004738 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004739 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004740 } catch (Exception e) {
4741 loge("Exception adding interface: " + e);
4742 }
4743 }
4744 for (String iface : interfaceDiff.removed) {
4745 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004746 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004747 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004748 mNetd.removeInterfaceFromNetwork(iface, netId);
4749 } catch (Exception e) {
4750 loge("Exception removing interface: " + e);
4751 }
4752 }
4753 }
4754
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004755 /**
4756 * Have netd update routes from oldLp to newLp.
4757 * @return true if routes changed between oldLp and newLp
4758 */
4759 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004760 // Compare the route diff to determine which routes should be added and removed.
4761 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4762 oldLp != null ? oldLp.getAllRoutes() : null,
4763 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004764
4765 // add routes before removing old in case it helps with continuous connectivity
4766
4767 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4768 for (RouteInfo route : routeDiff.added) {
4769 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004770 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004771 try {
4772 mNetd.addRoute(netId, route);
4773 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004774 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4775 loge("Exception in addRoute for non-gateway: " + e);
4776 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004777 }
4778 }
4779 for (RouteInfo route : routeDiff.added) {
4780 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004781 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004782 try {
4783 mNetd.addRoute(netId, route);
4784 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004785 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4786 loge("Exception in addRoute for gateway: " + e);
4787 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004788 }
4789 }
4790
4791 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004792 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004793 try {
4794 mNetd.removeRoute(netId, route);
4795 } catch (Exception e) {
4796 loge("Exception in removeRoute: " + e);
4797 }
4798 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004799 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004800 }
Erik Kline41368502015-06-17 13:19:54 +09004801
Erik Kline94887872016-04-05 13:30:49 +09004802 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4803 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4804 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004805 }
Erik Kline94887872016-04-05 13:30:49 +09004806
Erik Kline1742fe12017-12-13 19:40:49 +09004807 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4808 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4809
Erik Klinea24d4592018-01-11 21:07:29 +09004810 if (DBG) {
4811 final Collection<InetAddress> dnses = newLp.getDnsServers();
4812 log("Setting DNS servers for network " + netId + " to " + dnses);
4813 }
Erik Kline94887872016-04-05 13:30:49 +09004814 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004815 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004816 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004817 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004818 }
Erik Kline4edba012017-04-07 15:29:29 +09004819 }
4820
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004821 private String getNetworkPermission(NetworkCapabilities nc) {
4822 // TODO: make these permission strings AIDL constants instead.
4823 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4824 return NetworkManagementService.PERMISSION_SYSTEM;
4825 }
4826 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4827 return NetworkManagementService.PERMISSION_NETWORK;
4828 }
4829 return null;
4830 }
4831
Paul Jensen3d194ea2015-06-16 14:27:36 -04004832 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004833 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4834 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4835 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004836 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004837 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004838 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004839 if (nai.everConnected &&
4840 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4841 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004842 // does not cause any request (that is not a listen) currently matching that agent to
4843 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004844 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09004845 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004846 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09004847 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004848 }
4849
Paul Jensen3d194ea2015-06-16 14:27:36 -04004850 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004851 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004852 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004853 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004854 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004855 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004856 }
Paul Jensene0988542015-06-25 15:30:08 -04004857 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004858 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004859 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004860 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004861 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004862 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004863 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004864 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004865 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004866 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004867 if (nai.isSuspended()) {
4868 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4869 } else {
4870 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4871 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004872
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004873 return newNc;
4874 }
4875
4876 /**
4877 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4878 *
4879 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4880 * capabilities we manage and store in {@code nai}, such as validated status and captive
4881 * portal status)
4882 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4883 * potentially triggers rematches.
4884 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4885 * change.)
4886 *
4887 * @param oldScore score of the network before any of the changes that prompted us
4888 * to call this function.
4889 * @param nai the network having its capabilities updated.
4890 * @param nc the new network capabilities.
4891 */
4892 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4893 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4894
4895 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004896
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004897 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004898 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004899 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004900 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004901 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004902 } catch (RemoteException e) {
4903 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004904 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004905 }
4906
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004907 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004908 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004909 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004910 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004911 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004912
Chalard Jeanf213ca12018-01-16 18:43:05 +09004913 updateUids(nai, prevNc, newNc);
4914
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004915 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004916 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4917 // the change we're processing can't affect any requests, it can only affect the listens
4918 // on this network. We might have been called by rematchNetworkAndRequests when a
4919 // network changed foreground state.
4920 processListenRequests(nai, true);
4921 } else {
4922 // If the requestable capabilities have changed or the score changed, we can't have been
4923 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004924 rematchAllNetworksAndRequests(nai, oldScore);
4925 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004926 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004927
4928 // Report changes that are interesting for network statistics tracking.
4929 if (prevNc != null) {
4930 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004931 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004932 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004933 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004934 if (meteredChanged || roamingChanged) {
4935 notifyIfacesChangedForNetworkStats();
4936 }
4937 }
4938
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004939 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004940 // Tell VPNs about updated capabilities, since they may need to
4941 // bubble those changes through.
4942 synchronized (mVpns) {
4943 for (int i = 0; i < mVpns.size(); i++) {
4944 final Vpn vpn = mVpns.valueAt(i);
4945 vpn.updateCapabilities();
4946 }
4947 }
4948 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004949 }
4950
Chalard Jeanf213ca12018-01-16 18:43:05 +09004951 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4952 NetworkCapabilities newNc) {
4953 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4954 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4955 if (null == prevRanges) prevRanges = new ArraySet<>();
4956 if (null == newRanges) newRanges = new ArraySet<>();
4957 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4958
4959 prevRanges.removeAll(newRanges);
4960 newRanges.removeAll(prevRangesCopy);
4961
4962 try {
4963 if (!newRanges.isEmpty()) {
4964 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4965 newRanges.toArray(addedRangesArray);
4966 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4967 }
4968 if (!prevRanges.isEmpty()) {
4969 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4970 prevRanges.toArray(removedRangesArray);
4971 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4972 }
4973 } catch (Exception e) {
4974 // Never crash!
4975 loge("Exception in updateUids: " + e);
4976 }
4977 }
4978
Hugo Benichief502882017-09-01 01:23:32 +00004979 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Erik Kline79c6d052018-03-21 07:18:33 -07004980 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00004981 // Ignore updates for disconnected networks
4982 return;
4983 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004984 // newLp is already a defensive copy.
4985 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004986 if (VDBG) {
4987 log("Update of LinkProperties for " + nai.name() +
4988 "; created=" + nai.created +
4989 "; everConnected=" + nai.everConnected);
4990 }
4991 LinkProperties oldLp = nai.linkProperties;
4992 synchronized (nai) {
4993 nai.linkProperties = newLp;
4994 }
4995 if (nai.everConnected) {
4996 updateLinkProperties(nai, oldLp);
4997 }
4998 }
4999
Paul Jensenc8b9a742014-09-30 15:37:41 -04005000 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005001 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5002 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005003 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005004 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04005005 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
5006 }
5007 }
5008
Robert Greenwalt7b816022014-04-18 15:25:25 -07005009 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
5010 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07005011 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07005012 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
5013 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005014 }
5015 }
5016
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005017 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5018 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005019 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005020 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005021 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5022 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005023 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005024 sendIntent(nri.mPendingIntent, intent);
5025 }
5026 // else not handled
5027 }
5028
5029 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5030 mPendingIntentWakeLock.acquire();
5031 try {
5032 if (DBG) log("Sending " + pendingIntent);
5033 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5034 } catch (PendingIntent.CanceledException e) {
5035 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5036 mPendingIntentWakeLock.release();
5037 releasePendingNetworkRequest(pendingIntent);
5038 }
5039 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5040 }
5041
5042 @Override
5043 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5044 String resultData, Bundle resultExtras) {
5045 if (DBG) log("Finished sending " + pendingIntent);
5046 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005047 // Release with a delay so the receiving client has an opportunity to put in its
5048 // own request.
5049 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005050 }
5051
Chalard Jeanf19db372018-01-26 19:24:40 +09005052 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005053 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005054 if (nri.messenger == null) {
5055 return; // Default request has no msgr
5056 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005057 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005058 // TODO: check if defensive copies of data is needed.
5059 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005060 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005061 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5062 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005063 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005064 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005065 case ConnectivityManager.CALLBACK_AVAILABLE: {
5066 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
5067 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
5068 break;
5069 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005070 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005071 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005072 break;
5073 }
5074 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005075 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005076 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005077 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005078 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005079 break;
5080 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005081 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005082 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005083 break;
5084 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005085 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005086 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005087 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005088 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005089 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005090 String notification = ConnectivityManager.getCallbackName(notificationType);
5091 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005092 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005093 nri.messenger.send(msg);
5094 } catch (RemoteException e) {
5095 // may occur naturally in the race of binder death.
5096 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5097 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005098 }
5099
Hugo Benichidba33db2017-03-23 22:40:44 +09005100 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5101 bundle.putParcelable(t.getClass().getSimpleName(), t);
5102 }
5103
Paul Jensenc8b9a742014-09-30 15:37:41 -04005104 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005105 if (nai.numRequestNetworkRequests() != 0) {
5106 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5107 NetworkRequest nr = nai.requestAt(i);
5108 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005109 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005110 loge("Dead network still had at least " + nr);
5111 break;
5112 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005113 }
5114 nai.asyncChannel.disconnect();
5115 }
5116
Robert Greenwalt7b816022014-04-18 15:25:25 -07005117 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5118 if (oldNetwork == null) {
5119 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5120 return;
5121 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005122 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005123
5124 // If we get here it means that the last linger timeout for this network expired. So there
5125 // must be no other active linger timers, and we must stop lingering.
5126 oldNetwork.clearLingerState();
5127
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005128 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005129 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005130 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005131 } else {
5132 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005133 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5134 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005135 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005136 }
5137
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005138 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005139 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005140 setupDataActivityTracking(newNetwork);
5141 try {
5142 mNetd.setDefaultNetId(newNetwork.network.netId);
5143 } catch (Exception e) {
5144 loge("Exception setting default network :" + e);
5145 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005146
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005147 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005148 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005149 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005150 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005151 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005152 }
5153
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005154 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005155 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5156 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5157 NetworkRequest nr = nri.request;
5158 if (!nr.isListen()) continue;
5159 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5160 nai.removeRequest(nri.request.requestId);
5161 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5162 }
5163 }
5164
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005165 if (capabilitiesChanged) {
5166 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5167 }
5168
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005169 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5170 NetworkRequest nr = nri.request;
5171 if (!nr.isListen()) continue;
5172 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5173 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005174 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005175 }
5176 }
5177 }
5178
Paul Jensen2161a8e2014-09-11 11:00:39 -04005179 // Handles a network appearing or improving its score.
5180 //
5181 // - Evaluates all current NetworkRequests that can be
5182 // satisfied by newNetwork, and reassigns to newNetwork
5183 // any such requests for which newNetwork is the best.
5184 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005185 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005186 // needed. A network is needed if it is the best network for
5187 // one or more NetworkRequests, or if it is a VPN.
5188 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005189 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005190 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005191 //
5192 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5193 // networks that have no chance (i.e. even if validated)
5194 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005195 //
5196 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5197 // it does not remove NetworkRequests that other Networks could better satisfy.
5198 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5199 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5200 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005201 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005202 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005203 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5204 // performed to tear down unvalidated networks that have no chance (i.e. even if
5205 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005206 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005207 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005208 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005209 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005210 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005211 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005212
5213 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5214 final int score = newNetwork.getCurrentScore();
5215
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005216 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005217
Paul Jensen2161a8e2014-09-11 11:00:39 -04005218 // Find and migrate to this Network any NetworkRequests for
5219 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07005220 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04005221 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005222 NetworkCapabilities nc = newNetwork.networkCapabilities;
5223 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005224 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005225 // Process requests in the first pass and listens in the second pass. This allows us to
5226 // change a network's capabilities depending on which requests it has. This is only
5227 // correct if the change in capabilities doesn't affect whether the network satisfies
5228 // requests or not, and doesn't affect the network's score.
5229 if (nri.request.isListen()) continue;
5230
Hugo Benichicd952782017-09-20 11:20:14 +09005231 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005232 final boolean satisfies = newNetwork.satisfies(nri.request);
5233 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005234 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005235 log("Network " + newNetwork.name() + " was already satisfying" +
5236 " request " + nri.request.requestId + ". No change.");
5237 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005238 keep = true;
5239 continue;
5240 }
5241
5242 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005243 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005244 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005245 // next check if it's better than any current network we're using for
5246 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005247 if (VDBG) {
5248 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005249 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005250 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005251 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005252 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005253 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005254 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005255 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005256 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005257 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005258 affectedNetworks.add(currentNetwork);
5259 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005260 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005261 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005262 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005263 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005264 if (!newNetwork.addRequest(nri.request)) {
5265 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5266 }
5267 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005268 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005269 // Tell NetworkFactories about the new score, so they can stop
5270 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005271 // TODO - this could get expensive if we have alot of requests for this
5272 // network. Think about if there is a way to reduce this. Push
5273 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005274 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005275 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005276 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005277 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005278 if (currentNetwork != null) {
5279 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5280 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005281 }
5282 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005283 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005284 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5285 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005286 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005287 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5288 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5289 // This means this code doesn't have to handle the case where "currentNetwork" no
5290 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5291 if (DBG) {
5292 log("Network " + newNetwork.name() + " stopped satisfying" +
5293 " request " + nri.request.requestId);
5294 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005295 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005296 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005297 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005298 sendUpdatedScoreToFactories(nri.request, 0);
5299 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005300 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5301 newNetwork.name() +
5302 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005303 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005304 // TODO: Technically, sending CALLBACK_LOST here is
5305 // incorrect if there is a replacement network currently
5306 // connected that can satisfy nri, which is a request
5307 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005308 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5309 // so this code is only incorrect for a network that loses
5310 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005311 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005312 }
5313 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005314 if (isNewDefault) {
5315 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005316 makeDefault(newNetwork);
5317 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005318 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005319 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005320 // Have a new default network, release the transition wakelock in
5321 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005322 }
5323
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005324 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5325 Slog.wtf(TAG, String.format(
5326 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005327 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005328 }
5329 if (newNetwork.getCurrentScore() != score) {
5330 Slog.wtf(TAG, String.format(
5331 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005332 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005333 }
5334
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005335 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005336 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5337 // If the network went from background to foreground or vice versa, we need to update
5338 // its foreground state. It is safe to do this after rematching the requests because
5339 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5340 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005341 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005342 } else {
5343 processListenRequests(newNetwork, false);
5344 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005345
Paul Jensencf4c2c62015-07-01 14:16:32 -04005346 // do this after the default net is switched, but
5347 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005348 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005349
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005350 // Linger any networks that are no longer needed. This should be done after sending the
5351 // available callback for newNetwork.
5352 for (NetworkAgentInfo nai : affectedNetworks) {
5353 updateLingerState(nai, now);
5354 }
5355 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5356 // does not need to be done in any particular order.
5357 updateLingerState(newNetwork, now);
5358
Paul Jensencf4c2c62015-07-01 14:16:32 -04005359 if (isNewDefault) {
5360 // Maintain the illusion: since the legacy API only
5361 // understands one network at a time, we must pretend
5362 // that the current default network disconnected before
5363 // the new one connected.
5364 if (oldDefaultNetwork != null) {
5365 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5366 oldDefaultNetwork, true);
5367 }
5368 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5369 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5370 notifyLockdownVpn(newNetwork);
5371 }
5372
Robert Greenwalt7b816022014-04-18 15:25:25 -07005373 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005374 // Notify battery stats service about this network, both the normal
5375 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005376 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005377 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005378 final IBatteryStats bs = BatteryStatsService.getService();
5379 final int type = newNetwork.networkInfo.getType();
5380
5381 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5382 bs.noteNetworkInterfaceType(baseIface, type);
5383 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5384 final String stackedIface = stacked.getInterfaceName();
5385 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005386 }
5387 } catch (RemoteException ignored) {
5388 }
5389
Robert Greenwalt152ed372014-12-17 17:19:53 -08005390 // This has to happen after the notifyNetworkCallbacks as that tickles each
5391 // ConnectivityManager instance so that legacy requests correctly bind dns
5392 // requests to this network. The legacy users are listening for this bcast
5393 // and will generally do a dns request so they can ensureRouteToHost and if
5394 // they do that before the callbacks happen they'll use the default network.
5395 //
5396 // TODO: Is there still a race here? We send the broadcast
5397 // after sending the callback, but if the app can receive the
5398 // broadcast before the callback, it might still break.
5399 //
5400 // This *does* introduce a race where if the user uses the new api
5401 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5402 // they may get old info. Reverse this after the old startUsing api is removed.
5403 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005404 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5405 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005406 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005407 // legacy type tracker filters out repeat adds
5408 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5409 }
5410 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005411
5412 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5413 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5414 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5415 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5416 if (newNetwork.isVPN()) {
5417 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5418 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005419 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005420 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5421 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005422 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005423 if (nai.getLingerExpiry() > 0) {
5424 // This network has active linger timers and no requests, but is not
5425 // lingering. Linger it.
5426 //
5427 // One way (the only way?) this can happen if this network is unvalidated
5428 // and became unneeded due to another network improving its score to the
5429 // point where this network will no longer be able to satisfy any requests
5430 // even if it validates.
5431 updateLingerState(nai, now);
5432 } else {
5433 if (DBG) log("Reaping " + nai.name());
5434 teardownUnneededNetwork(nai);
5435 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005436 }
5437 }
5438 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005439 }
5440
Paul Jensen1c7ba022015-06-16 14:27:36 -04005441 /**
5442 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5443 * being disconnected.
5444 * @param changed If only one Network's score or capabilities have been modified since the last
5445 * time this function was called, pass this Network in this argument, otherwise pass
5446 * null.
5447 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5448 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5449 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5450 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5451 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005452 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005453 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005454 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5455 // to avoid the slowness. It is not simply enough to process just "changed", for
5456 // example in the case where "changed"'s score decreases and another network should begin
5457 // satifying a NetworkRequest that "changed" currently satisfies.
5458
5459 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5460 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5461 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005462 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005463 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005464 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005465 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005466 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5467 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5468 // Rematch higher scoring networks first to prevent requests first matching a lower
5469 // scoring network and then a higher scoring network, which could produce multiple
5470 // callbacks and inadvertently unlinger networks.
5471 Arrays.sort(nais);
5472 for (NetworkAgentInfo nai : nais) {
5473 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005474 // Only reap the last time through the loop. Reaping before all rematching
5475 // is complete could incorrectly teardown a network that hasn't yet been
5476 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005477 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005478 : ReapUnvalidatedNetworks.REAP,
5479 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005480 }
5481 }
5482 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005483
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005484 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005485 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005486 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005487 // For now only update icons for default connection.
5488 // TODO: Update WiFi and cellular icons separately. b/17237507
5489 if (!isDefaultNetwork(nai)) return;
5490
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005491 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005492 // Don't repeat publish.
5493 if (newInetCondition == mDefaultInetConditionPublished) return;
5494
5495 mDefaultInetConditionPublished = newInetCondition;
5496 sendInetConditionBroadcast(nai.networkInfo);
5497 }
5498
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005499 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005500 synchronized (mVpns) {
5501 if (mLockdownTracker != null) {
5502 if (nai != null && nai.isVPN()) {
5503 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5504 } else {
5505 mLockdownTracker.onNetworkInfoChanged();
5506 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005507 }
5508 }
5509 }
5510
Robert Greenwalt7b816022014-04-18 15:25:25 -07005511 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005512 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005513 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005514 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005515 synchronized (networkAgent) {
5516 oldInfo = networkAgent.networkInfo;
5517 networkAgent.networkInfo = newInfo;
5518 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005519 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005520
Robert Greenwalt7b816022014-04-18 15:25:25 -07005521 if (DBG) {
5522 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5523 (oldInfo == null ? "null" : oldInfo.getState()) +
5524 " to " + state);
5525 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005526
Robin Lee585e2482016-05-01 23:00:00 +01005527 if (!networkAgent.created
5528 && (state == NetworkInfo.State.CONNECTED
5529 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005530
5531 // A network that has just connected has zero requests and is thus a foreground network.
5532 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5533
Robert Greenwalt7b816022014-04-18 15:25:25 -07005534 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005535 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005536 if (networkAgent.isVPN()) {
5537 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005538 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5539 (networkAgent.networkMisc == null ||
5540 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005541 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005542 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005543 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005544 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005545 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005546 loge("Error creating network " + networkAgent.network.netId + ": "
5547 + e.getMessage());
5548 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005549 }
Paul Jenseneec75412014-08-04 12:21:19 -04005550 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005551 }
5552
5553 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5554 networkAgent.everConnected = true;
5555
Erik Kline79c6d052018-03-21 07:18:33 -07005556 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005557 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005558 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005559
Paul Jensenca8f16a2014-05-09 12:47:55 -04005560 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005561 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005562
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005563 if (networkAgent.isVPN()) {
5564 // Temporarily disable the default proxy (not global).
5565 synchronized (mProxyLock) {
5566 if (!mDefaultProxyDisabled) {
5567 mDefaultProxyDisabled = true;
5568 if (mGlobalProxy == null && mDefaultProxy != null) {
5569 sendProxyBroadcast(null);
5570 }
5571 }
5572 }
5573 // TODO: support proxy per network.
5574 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005575
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005576 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5577 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5578 // capabilities, so it only needs to be done once on initial connect, not every time the
5579 // network's capabilities change. Note that we do this before rematching the network,
5580 // so we could decide to tear it down immediately afterwards. That's fine though - on
5581 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5582 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005583 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005584
Paul Jensen2161a8e2014-09-11 11:00:39 -04005585 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005586 final long now = SystemClock.elapsedRealtime();
5587 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005588
5589 // This has to happen after matching the requests, because callbacks are just requests.
5590 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005591 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005592 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005593 if (networkAgent.isVPN()) {
5594 synchronized (mProxyLock) {
5595 if (mDefaultProxyDisabled) {
5596 mDefaultProxyDisabled = false;
5597 if (mGlobalProxy == null && mDefaultProxy != null) {
5598 sendProxyBroadcast(mDefaultProxy);
5599 }
5600 }
5601 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005602 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005603 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005604 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5605 state == NetworkInfo.State.SUSPENDED) {
5606 // going into or coming out of SUSPEND: rescore and notify
5607 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005608 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005609 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005610 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5611 networkAgent.networkCapabilities);
5612 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5613 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005614 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5615 ConnectivityManager.CALLBACK_SUSPENDED :
5616 ConnectivityManager.CALLBACK_RESUMED));
5617 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005618 }
5619 }
5620
Robert Greenwaltac96c522014-06-03 16:43:57 -07005621 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005622 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005623 if (score < 0) {
5624 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5625 "). Bumping score to min of 0");
5626 score = 0;
5627 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005628
Paul Jensen2161a8e2014-09-11 11:00:39 -04005629 final int oldScore = nai.getCurrentScore();
5630 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005631
Paul Jensen85cf78e2015-06-25 13:25:07 -04005632 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005633
Paul Jensenc8b9a742014-09-30 15:37:41 -04005634 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005635 }
5636
Erik Klinec75d4fa2017-02-15 19:59:17 +09005637 // Notify only this one new request of the current state. Transfer all the
5638 // current state by calling NetworkCapabilities and LinkProperties callbacks
5639 // so that callers can be guaranteed to have as close to atomicity in state
5640 // transfer as can be supported by this current API.
5641 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005642 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005643 if (nri.mPendingIntent != null) {
5644 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5645 // Attempt no subsequent state pushes where intents are involved.
5646 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005647 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005648
5649 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005650 }
5651
Robert Greenwalt8d482522015-06-24 13:23:42 -07005652 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005653 // The NetworkInfo we actually send out has no bearing on the real
5654 // state of affairs. For example, if the default connection is mobile,
5655 // and a request for HIPRI has just gone away, we need to pretend that
5656 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5657 // the state to DISCONNECTED, even though the network is of type MOBILE
5658 // and is still connected.
5659 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5660 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005661 if (state != DetailedState.DISCONNECTED) {
5662 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005663 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005664 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005665 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005666 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5667 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5668 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5669 if (info.isFailover()) {
5670 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5671 nai.networkInfo.setFailover(false);
5672 }
5673 if (info.getReason() != null) {
5674 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5675 }
5676 if (info.getExtraInfo() != null) {
5677 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5678 }
5679 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005680 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005681 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005682 if (newDefaultAgent != null) {
5683 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5684 newDefaultAgent.networkInfo);
5685 } else {
5686 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5687 }
5688 }
5689 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5690 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005691 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005692 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005693 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005694 }
5695 }
5696 }
5697
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005698 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005699 if (VDBG) {
5700 String notification = ConnectivityManager.getCallbackName(notifyType);
5701 log("notifyType " + notification + " for " + networkAgent.name());
5702 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005703 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5704 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005705 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5706 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005707 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5708 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005709 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005710 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005711 } else {
5712 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5713 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005714 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005715 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005716
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005717 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5718 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5719 }
5720
Jeff Sharkey69736342014-12-08 14:50:12 -08005721 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005722 * Returns the list of all interfaces that could be used by network traffic that does not
5723 * explicitly specify a network. This includes the default network, but also all VPNs that are
5724 * currently connected.
5725 *
5726 * Must be called on the handler thread.
5727 */
5728 private Network[] getDefaultNetworks() {
5729 ArrayList<Network> defaultNetworks = new ArrayList<>();
5730 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5731 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5732 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5733 defaultNetworks.add(nai.network);
5734 }
5735 }
5736 return defaultNetworks.toArray(new Network[0]);
5737 }
5738
5739 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005740 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5741 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005742 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005743 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005744 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005745 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005746 } catch (Exception ignored) {
5747 }
5748 }
5749
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005750 @Override
5751 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005752 int user = UserHandle.getUserId(Binder.getCallingUid());
5753 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005754 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005755 return mVpns.get(user).addAddress(address, prefixLength);
5756 }
5757 }
5758
5759 @Override
5760 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005761 int user = UserHandle.getUserId(Binder.getCallingUid());
5762 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005763 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005764 return mVpns.get(user).removeAddress(address, prefixLength);
5765 }
5766 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005767
5768 @Override
5769 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005770 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005771 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005772 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005773 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005774 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005775 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005776 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005777 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005778 }
5779 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005780 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005781
5782 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005783 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07005784 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005785 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005786 }
5787
5788 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005789 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5790 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5791 enforceKeepalivePermission();
5792 mKeepaliveTracker.startNattKeepalive(
5793 getNetworkAgentInfoForNetwork(network),
5794 intervalSeconds, messenger, binder,
5795 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5796 }
5797
5798 @Override
5799 public void stopKeepalive(Network network, int slot) {
5800 mHandler.sendMessage(mHandler.obtainMessage(
5801 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5802 }
5803
5804 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005805 public void factoryReset() {
5806 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005807
5808 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5809 return;
5810 }
5811
Robin Lee3b3dd942015-05-12 18:14:58 +01005812 final int userId = UserHandle.getCallingUserId();
5813
Stuart Scottf1fb3972015-04-02 18:00:02 -07005814 // Turn airplane mode off
5815 setAirplaneMode(false);
5816
Stuart Scotte3e314d2015-04-20 14:07:45 -07005817 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5818 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005819 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005820 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005821 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005822 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005823 }
5824
Stuart Scotte3e314d2015-04-20 14:07:45 -07005825 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005826 // Remove always-on package
5827 synchronized (mVpns) {
5828 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5829 if (alwaysOnPackage != null) {
5830 setAlwaysOnVpnPackage(userId, null, false);
5831 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5832 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005833
Hugo Benichi69744342017-11-27 10:57:16 +09005834 // Turn Always-on VPN off
5835 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5836 final long ident = Binder.clearCallingIdentity();
5837 try {
5838 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5839 mLockdownEnabled = false;
5840 setLockdownTracker(null);
5841 } finally {
5842 Binder.restoreCallingIdentity(ident);
5843 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005844 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005845
Hugo Benichi69744342017-11-27 10:57:16 +09005846 // Turn VPN off
5847 VpnConfig vpnConfig = getVpnConfig(userId);
5848 if (vpnConfig != null) {
5849 if (vpnConfig.legacy) {
5850 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5851 } else {
5852 // Prevent this app (packagename = vpnConfig.user) from initiating
5853 // VPN connections in the future without user intervention.
5854 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005855
Hugo Benichi69744342017-11-27 10:57:16 +09005856 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5857 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005858 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005859 }
5860 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005861
5862 Settings.Global.putString(mContext.getContentResolver(),
5863 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005864 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005865
Ricky Wai44dcbde2018-01-23 04:09:45 +00005866 @Override
5867 public byte[] getNetworkWatchlistConfigHash() {
5868 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
5869 if (nwm == null) {
5870 loge("Unable to get NetworkWatchlistManager");
5871 return null;
5872 }
5873 // Redirect it to network watchlist service to access watchlist file and calculate hash.
5874 return nwm.getWatchlistConfigHash();
5875 }
5876
Paul Jensencf4c2c62015-07-01 14:16:32 -04005877 @VisibleForTesting
5878 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5879 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5880 return new NetworkMonitor(context, handler, nai, defaultRequest);
5881 }
Erik Kline48f12f22016-04-14 17:30:59 +09005882
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005883 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005884 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5885 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005886 }
5887
5888 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005889 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5890 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5891 }
5892
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005893 @VisibleForTesting
5894 public boolean hasService(String name) {
5895 return ServiceManager.checkService(name) != null;
5896 }
5897
Hugo Benichi64901e52017-10-19 14:42:40 +09005898 @VisibleForTesting
5899 protected IpConnectivityMetrics.Logger metricsLogger() {
5900 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5901 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005902 }
5903
5904 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005905 int[] transports = nai.networkCapabilities.getTransportTypes();
5906 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005907 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005908
5909 private static boolean toBool(int encodedBoolean) {
5910 return encodedBoolean != 0; // Only 0 means false.
5911 }
5912
5913 private static int encodeBool(boolean b) {
5914 return b ? 1 : 0;
5915 }
mswest46386886f2018-03-12 10:34:34 -07005916
5917 @Override
5918 public void onShellCommand(FileDescriptor in, FileDescriptor out,
5919 FileDescriptor err, String[] args, ShellCallback callback,
5920 ResultReceiver resultReceiver) {
5921 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
5922 }
5923
5924 private class ShellCmd extends ShellCommand {
5925
5926 @Override
5927 public int onCommand(String cmd) {
5928 if (cmd == null) {
5929 return handleDefaultCommands(cmd);
5930 }
5931 final PrintWriter pw = getOutPrintWriter();
5932 try {
5933 switch (cmd) {
5934 case "airplane-mode":
5935 final String action = getNextArg();
5936 if ("enable".equals(action)) {
5937 setAirplaneMode(true);
5938 return 0;
5939 } else if ("disable".equals(action)) {
5940 setAirplaneMode(false);
5941 return 0;
5942 } else if (action == null) {
5943 final ContentResolver cr = mContext.getContentResolver();
5944 final int enabled = Settings.Global.getInt(cr,
5945 Settings.Global.AIRPLANE_MODE_ON);
5946 pw.println(enabled == 0 ? "disabled" : "enabled");
5947 return 0;
5948 } else {
5949 onHelp();
5950 return -1;
5951 }
5952 default:
5953 return handleDefaultCommands(cmd);
5954 }
5955 } catch (Exception e) {
5956 pw.println(e);
5957 }
5958 return -1;
5959 }
5960
5961 @Override
5962 public void onHelp() {
5963 PrintWriter pw = getOutPrintWriter();
5964 pw.println("Connectivity service commands:");
5965 pw.println(" help");
5966 pw.println(" Print this help text.");
5967 pw.println(" airplane-mode [enable|disable]");
5968 pw.println(" Turn airplane mode on or off.");
5969 pw.println(" airplane-mode");
5970 pw.println(" Get airplane mode.");
5971 }
5972 }
Erik Kline79c6d052018-03-21 07:18:33 -07005973}